Completed
Push — add/user-authentication ( 651ac4...684086 )
by
unknown
26:10 queued 18:04
created

class.jetpack.php (2 issues)

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
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\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * Contains all assets that have had their URL rewritten to minified versions.
86
	 *
87
	 * @var array
88
	 */
89
	static $min_assets = array();
90
91
	public $plugins_to_deactivate = array(
92
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
93
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
94
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
95
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
96
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
97
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
98
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
99
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
100
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
101
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
102
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
103
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
104
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
105
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
106
	);
107
108
	/**
109
	 * Map of roles we care about, and their corresponding minimum capabilities.
110
	 *
111
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
112
	 *
113
	 * @access public
114
	 * @static
115
	 *
116
	 * @var array
117
	 */
118
	public static $capability_translations = array(
119
		'administrator' => 'manage_options',
120
		'editor'        => 'edit_others_posts',
121
		'author'        => 'publish_posts',
122
		'contributor'   => 'edit_posts',
123
		'subscriber'    => 'read',
124
	);
125
126
	/**
127
	 * Map of modules that have conflicts with plugins and should not be auto-activated
128
	 * if the plugins are active.  Used by filter_default_modules
129
	 *
130
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
131
	 * change `module-slug` and add this to your plugin:
132
	 *
133
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
134
	 * function my_jetpack_get_default_modules( $modules ) {
135
	 *     return array_diff( $modules, array( 'module-slug' ) );
136
	 * }
137
	 *
138
	 * @var array
139
	 */
140
	private $conflicting_plugins = array(
141
		'comments'          => array(
142
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
143
			'Disqus'                               => 'disqus-comment-system/disqus.php',
144
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
145
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
146
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
147
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
148
		),
149
		'comment-likes' => array(
150
			'Epoch'                                => 'epoch/plugincore.php',
151
		),
152
		'contact-form'      => array(
153
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
154
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
155
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
156
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
157
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
158
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
159
		),
160
		'minileven'         => array(
161
			'WPtouch'                              => 'wptouch/wptouch.php',
162
		),
163
		'latex'             => array(
164
			'LaTeX for WordPress'                  => 'latex/latex.php',
165
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
166
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
167
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
168
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
169
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
170
		),
171
		'protect'           => array(
172
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
173
			'Captcha'                              => 'captcha/captcha.php',
174
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
175
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
176
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
177
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
178
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
179
			'Security-protection'                  => 'security-protection/security-protection.php',
180
			'Login Security'                       => 'login-security/login-security.php',
181
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
182
			'Wordfence Security'                   => 'wordfence/wordfence.php',
183
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
184
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
185
		),
186
		'random-redirect'   => array(
187
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
188
		),
189
		'related-posts'     => array(
190
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
191
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
192
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
193
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
194
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
195
			'outbrain'                             => 'outbrain/outbrain.php',
196
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
197
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
198
		),
199
		'sharedaddy'        => array(
200
			'AddThis'                              => 'addthis/addthis_social_widget.php',
201
			'Add To Any'                           => 'add-to-any/add-to-any.php',
202
			'ShareThis'                            => 'share-this/sharethis.php',
203
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
204
		),
205
		'seo-tools' => array(
206
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
207
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
208
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
209
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
210
			'The SEO Framework'                    => 'autodescription/autodescription.php',
211
		),
212
		'verification-tools' => array(
213
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
214
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
215
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
216
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
217
			'The SEO Framework'                    => 'autodescription/autodescription.php',
218
		),
219
		'widget-visibility' => array(
220
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
221
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
222
		),
223
		'sitemaps' => array(
224
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
225
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
226
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
227
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
228
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
229
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
230
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
231
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
232
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
233
			'The SEO Framework'                    => 'autodescription/autodescription.php',
234
			'Sitemap'                              => 'sitemap/sitemap.php',
235
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
236
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
237
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
238
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
239
		),
240
		'lazy-images' => array(
241
			'Lazy Load'              => 'lazy-load/lazy-load.php',
242
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
243
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
244
		),
245
	);
246
247
	/**
248
	 * Plugins for which we turn off our Facebook OG Tags implementation.
249
	 *
250
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
251
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
252
	 *
253
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
254
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
255
	 */
256
	private $open_graph_conflicting_plugins = array(
257
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
258
		                                                         // 2 Click Social Media Buttons
259
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
260
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
261
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
262
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
263
		                                                         // Open Graph Meta Tags by Heateor
264
		'facebook/facebook.php',                                 // Facebook (official plugin)
265
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
266
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
267
		                                                         // Facebook Featured Image & OG Meta Tags
268
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
269
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
270
		                                                         // Facebook Open Graph Meta Tags for WordPress
271
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
272
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
273
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
274
		                                                         // Fedmich's Facebook Open Graph Meta
275
		'network-publisher/networkpub.php',                      // Network Publisher
276
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
277
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
278
		                                                         // NextScripts SNAP
279
		'og-tags/og-tags.php',                                   // OG Tags
280
		'opengraph/opengraph.php',                               // Open Graph
281
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
282
		                                                         // Open Graph Protocol Framework
283
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
284
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
285
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
286
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
287
		'sharepress/sharepress.php',                             // SharePress
288
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
289
		'social-discussions/social-discussions.php',             // Social Discussions
290
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
291
		'socialize/socialize.php',                               // Socialize
292
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
293
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
294
		                                                         // Tweet, Like, Google +1 and Share
295
		'wordbooker/wordbooker.php',                             // Wordbooker
296
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
297
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
298
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
299
		                                                         // WP Facebook Like Send & Open Graph Meta
300
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
301
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
302
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
303
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
304
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
305
	);
306
307
	/**
308
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
309
	 */
310
	private $twitter_cards_conflicting_plugins = array(
311
	//	'twitter/twitter.php',                       // The official one handles this on its own.
312
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
313
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
314
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
315
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
316
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
317
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
318
		'twitter-cards/twitter-cards.php',           // Twitter Cards
319
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
320
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
321
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
322
	);
323
324
	/**
325
	 * Message to display in admin_notice
326
	 * @var string
327
	 */
328
	public $message = '';
329
330
	/**
331
	 * Error to display in admin_notice
332
	 * @var string
333
	 */
334
	public $error = '';
335
336
	/**
337
	 * Modules that need more privacy description.
338
	 * @var string
339
	 */
340
	public $privacy_checks = '';
341
342
	/**
343
	 * Stats to record once the page loads
344
	 *
345
	 * @var array
346
	 */
347
	public $stats = array();
348
349
	/**
350
	 * Jetpack_Sync object
351
	 */
352
	public $sync;
353
354
	/**
355
	 * Verified data for JSON authorization request
356
	 */
357
	public $json_api_authorization_request = array();
358
359
	/**
360
	 * @var \Automattic\Jetpack\Connection\Manager
361
	 */
362
	protected $connection_manager;
363
364
	/**
365
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
366
	 */
367
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
368
369
	/**
370
	 * Holds the singleton instance of this class
371
	 * @since 2.3.3
372
	 * @var Jetpack
373
	 */
374
	static $instance = false;
375
376
	/**
377
	 * Singleton
378
	 * @static
379
	 */
380
	public static function init() {
381
		if ( ! self::$instance ) {
382
			self::$instance = new Jetpack;
383
384
			self::$instance->plugin_upgrade();
385
		}
386
387
		return self::$instance;
388
	}
389
390
	/**
391
	 * Must never be called statically
392
	 */
393
	function plugin_upgrade() {
394
		if ( Jetpack::is_active() ) {
395
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
396
			if ( JETPACK__VERSION != $version ) {
397
				// Prevent multiple upgrades at once - only a single process should trigger
398
				// an upgrade to avoid stampedes
399
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
400
					return;
401
				}
402
403
				// Set a short lock to prevent multiple instances of the upgrade
404
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
405
406
				// check which active modules actually exist and remove others from active_modules list
407
				$unfiltered_modules = Jetpack::get_active_modules();
408
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
409
				if ( array_diff( $unfiltered_modules, $modules ) ) {
410
					Jetpack::update_active_modules( $modules );
411
				}
412
413
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
414
415
				// Upgrade to 4.3.0
416
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
417
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
418
				}
419
420
				// Make sure Markdown for posts gets turned back on
421
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
422
					update_option( 'wpcom_publish_posts_with_markdown', true );
423
				}
424
425
				if ( did_action( 'wp_loaded' ) ) {
426
					self::upgrade_on_load();
427
				} else {
428
					add_action(
429
						'wp_loaded',
430
						array( __CLASS__, 'upgrade_on_load' )
431
					);
432
				}
433
			}
434
		}
435
	}
436
437
	/**
438
	 * Runs upgrade routines that need to have modules loaded.
439
	 */
440
	static function upgrade_on_load() {
441
442
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
443
		// This can happen in case Jetpack has been just upgraded and is
444
		// being initialized late during the page load. In this case we wait
445
		// until the next proper admin page load with Jetpack active.
446
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
447
			delete_transient( self::$plugin_upgrade_lock_key );
448
449
			return;
450
		}
451
452
		Jetpack::maybe_set_version_option();
453
454
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
455
			Jetpack_Widget_Conditions::migrate_post_type_rules();
456
		}
457
458
		if (
459
			class_exists( 'Jetpack_Sitemap_Manager' )
460
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
461
		) {
462
			do_action( 'jetpack_sitemaps_purge_data' );
463
		}
464
465
		// Delete old stats cache
466
		delete_option( 'jetpack_restapi_stats_cache' );
467
468
		delete_transient( self::$plugin_upgrade_lock_key );
469
	}
470
471
	/**
472
	 * Saves all the currently active modules to options.
473
	 * Also fires Action hooks for each newly activated and deactivated module.
474
	 *
475
	 * @param $modules Array Array of active modules to be saved in options.
476
	 *
477
	 * @return $success bool true for success, false for failure.
478
	 */
479
	static function update_active_modules( $modules ) {
480
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
481
		$active_modules       = Jetpack::get_active_modules();
482
		$new_active_modules   = array_diff( $modules, $current_modules );
483
		$new_inactive_modules = array_diff( $active_modules, $modules );
484
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
485
		$reindexed_modules    = array_values( $new_current_modules );
486
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
487
488
		foreach ( $new_active_modules as $module ) {
489
			/**
490
			 * Fires when a specific module is activated.
491
			 *
492
			 * @since 1.9.0
493
			 *
494
			 * @param string $module Module slug.
495
			 * @param boolean $success whether the module was activated. @since 4.2
496
			 */
497
			do_action( 'jetpack_activate_module', $module, $success );
498
			/**
499
			 * Fires when a module is activated.
500
			 * The dynamic part of the filter, $module, is the module slug.
501
			 *
502
			 * @since 1.9.0
503
			 *
504
			 * @param string $module Module slug.
505
			 */
506
			do_action( "jetpack_activate_module_$module", $module );
507
		}
508
509
		foreach ( $new_inactive_modules as $module ) {
510
			/**
511
			 * Fired after a module has been deactivated.
512
			 *
513
			 * @since 4.2.0
514
			 *
515
			 * @param string $module Module slug.
516
			 * @param boolean $success whether the module was deactivated.
517
			 */
518
			do_action( 'jetpack_deactivate_module', $module, $success );
519
			/**
520
			 * Fires when a module is deactivated.
521
			 * The dynamic part of the filter, $module, is the module slug.
522
			 *
523
			 * @since 1.9.0
524
			 *
525
			 * @param string $module Module slug.
526
			 */
527
			do_action( "jetpack_deactivate_module_$module", $module );
528
		}
529
530
		return $success;
531
	}
532
533
	static function delete_active_modules() {
534
		self::update_active_modules( array() );
535
	}
536
537
	/**
538
	 * Constructor.  Initializes WordPress hooks
539
	 */
540
	private function __construct() {
541
		/*
542
		 * Check for and alert any deprecated hooks
543
		 */
544
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
545
546
		/*
547
		 * Enable enhanced handling of previewing sites in Calypso
548
		 */
549
		if ( Jetpack::is_active() ) {
550
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
551
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
552
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
553
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
554
		}
555
556
		if ( self::jetpack_tos_agreed() ) {
557
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
558
			add_action( 'init', array( $tracking, 'init' ) );
559
		}
560
561
562
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
563
			return function() {
564
				return wp_generate_password( 32, false );
565
			};
566
		} );
567
568
		$this->connection_manager = new Connection_Manager();
569
		$this->connection_manager->init();
570
571
		/*
572
		 * Load things that should only be in Network Admin.
573
		 *
574
		 * For now blow away everything else until a more full
575
		 * understanding of what is needed at the network level is
576
		 * available
577
		 */
578
		if ( is_multisite() ) {
579
			$network = Jetpack_Network::init();
580
			$network->set_connection( $this->connection_manager );
581
		}
582
583
		add_filter(
584
			'jetpack_signature_check_token',
585
			array( __CLASS__, 'verify_onboarding_token' ),
586
			10,
587
			3
588
		);
589
590
		/**
591
		 * Prepare Gutenberg Editor functionality
592
		 */
593
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
594
		Jetpack_Gutenberg::init();
595
		Jetpack_Gutenberg::load_independent_blocks();
596
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
597
598
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
599
600
		// Unlink user before deleting the user from .com
601
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
602
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
603
604
		if ( Jetpack::is_active() ) {
605
			Jetpack_Heartbeat::init();
606
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
607
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
608
				Jetpack_Search_Performance_Logger::init();
609
			}
610
		}
611
612
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
613
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
614
615
		add_action( 'admin_init', array( $this, 'admin_init' ) );
616
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
617
618
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
619
620
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
621
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
622
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
623
624
		// returns HTTPS support status
625
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
626
627
		// JITM AJAX callback function
628
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
629
630
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
631
632
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
633
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
634
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
635
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
636
637
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
638
639
		/**
640
		 * These actions run checks to load additional files.
641
		 * They check for external files or plugins, so they need to run as late as possible.
642
		 */
643
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
644
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
645
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
646
647
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
648
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
649
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
650
651
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
652
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
653
654
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
655
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
656
657
		// A filter to control all just in time messages
658
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
659
660
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
661
662
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
663
		// We should make sure to only do this for front end links.
664
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
665
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
666
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
667
668
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
669
			//so they point moderation links on emails to Calypso
670
			jetpack_require_lib( 'functions.wp-notify' );
671
		}
672
673
		// Hide edit post link if mobile app.
674
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
675
			add_filter( 'edit_post_link', '__return_empty_string' );
676
		}
677
678
		// Update the Jetpack plan from API on heartbeats
679
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
680
681
		/**
682
		 * This is the hack to concatenate all css files into one.
683
		 * For description and reasoning see the implode_frontend_css method
684
		 *
685
		 * Super late priority so we catch all the registered styles
686
		 */
687
		if( !is_admin() ) {
688
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
689
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
690
		}
691
692
693
		/**
694
		 * These are sync actions that we need to keep track of for jitms
695
		 */
696
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
697
698
		// Actually push the stats on shutdown.
699
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
700
			add_action( 'shutdown', array( $this, 'push_stats' ) );
701
		}
702
	}
703
704
	/**
705
	 * Sets up the XMLRPC request handlers.
706
	 *
707
	 * @param Array                 $request_params incoming request parameters.
708
	 * @param Boolean               $is_active whether the connection is currently active.
709
	 * @param Boolean               $is_signed whether the signature check has been successful.
710
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server (optional) an instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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...
711
	 */
712
	public function setup_xmlrpc_handlers(
713
		$request_params,
714
		$is_active,
715
		$is_signed,
716
		Jetpack_XMLRPC_Server $xmlrpc_server = null
717
	) {
718
		return $this->connection_manager->setup_xmlrpc_handlers(
719
			$request_params,
720
			$is_active,
721
			$is_signed,
722
			$xmlrpc_server
723
		);
724
	}
725
726
	/**
727
	 * This is ported over from the manage module, which has been deprecated and baked in here.
728
	 *
729
	 * @param $domains
730
	 */
731
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
732
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
733
	}
734
735
	/**
736
	 * Return $domains, with 'wordpress.com' appended.
737
	 * This is ported over from the manage module, which has been deprecated and baked in here.
738
	 *
739
	 * @param $domains
740
	 * @return array
741
	 */
742
	function allow_wpcom_domain( $domains ) {
743
		if ( empty( $domains ) ) {
744
			$domains = array();
745
		}
746
		$domains[] = 'wordpress.com';
747
		return array_unique( $domains );
748
	}
749
750
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
751
		$post = get_post( $post_id );
752
753
		if ( empty( $post ) ) {
754
			return $default_url;
755
		}
756
757
		$post_type = $post->post_type;
758
759
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
760
		// https://en.support.wordpress.com/custom-post-types/
761
		$allowed_post_types = array(
762
			'post' => 'post',
763
			'page' => 'page',
764
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
765
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
766
		);
767
768
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
769
			return $default_url;
770
		}
771
772
		$path_prefix = $allowed_post_types[ $post_type ];
773
774
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
775
776
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
777
	}
778
779
	function point_edit_comment_links_to_calypso( $url ) {
780
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
781
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
782
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
783
			Jetpack::build_raw_urls( get_home_url() ),
784
			$query_args['amp;c']
785
		) );
786
	}
787
788
	function jetpack_track_last_sync_callback( $params ) {
789
		/**
790
		 * Filter to turn off jitm caching
791
		 *
792
		 * @since 5.4.0
793
		 *
794
		 * @param bool false Whether to cache just in time messages
795
		 */
796
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
797
			return $params;
798
		}
799
800
		if ( is_array( $params ) && isset( $params[0] ) ) {
801
			$option = $params[0];
802
			if ( 'active_plugins' === $option ) {
803
				// use the cache if we can, but not terribly important if it gets evicted
804
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
805
			}
806
		}
807
808
		return $params;
809
	}
810
811
	function jetpack_connection_banner_callback() {
812
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
813
814
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
815
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
816
			wp_send_json_success();
817
		}
818
819
		wp_die();
820
	}
821
822
	/**
823
	 * The callback for the JITM ajax requests.
824
	 */
825
	function jetpack_jitm_ajax_callback() {
826
		// Check for nonce
827
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
828
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
829
		}
830
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
831
			$module_slug = $_REQUEST['jitmModule'];
832
			Jetpack::log( 'activate', $module_slug );
833
			Jetpack::activate_module( $module_slug, false, false );
834
			Jetpack::state( 'message', 'no_message' );
835
836
			//A Jetpack module is being activated through a JITM, track it
837
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
838
			$this->do_stats( 'server_side' );
839
840
			wp_send_json_success();
841
		}
842
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
843
			// get the hide_jitm options array
844
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
845
			$module_slug = $_REQUEST['jitmModule'];
846
847
			if( ! $jetpack_hide_jitm ) {
848
				$jetpack_hide_jitm = array(
849
					$module_slug => 'hide'
850
				);
851
			} else {
852
				$jetpack_hide_jitm[$module_slug] = 'hide';
853
			}
854
855
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
856
857
			//jitm is being dismissed forever, track it
858
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
859
			$this->do_stats( 'server_side' );
860
861
			wp_send_json_success();
862
		}
863 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
864
			$module_slug = $_REQUEST['jitmModule'];
865
866
			// User went to WordPress.com, track this
867
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
868
			$this->do_stats( 'server_side' );
869
870
			wp_send_json_success();
871
		}
872 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
873
			$track = $_REQUEST['jitmModule'];
874
875
			// User is viewing JITM, track it.
876
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
877
			$this->do_stats( 'server_side' );
878
879
			wp_send_json_success();
880
		}
881
	}
882
883
	/**
884
	 * If there are any stats that need to be pushed, but haven't been, push them now.
885
	 */
886
	function push_stats() {
887
		if ( ! empty( $this->stats ) ) {
888
			$this->do_stats( 'server_side' );
889
		}
890
	}
891
892
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
893
		switch( $cap ) {
894
			case 'jetpack_connect' :
895
			case 'jetpack_reconnect' :
896
				if ( Jetpack::is_development_mode() ) {
897
					$caps = array( 'do_not_allow' );
898
					break;
899
				}
900
				/**
901
				 * Pass through. If it's not development mode, these should match disconnect.
902
				 * Let users disconnect if it's development mode, just in case things glitch.
903
				 */
904
			case 'jetpack_disconnect' :
905
				/**
906
				 * In multisite, can individual site admins manage their own connection?
907
				 *
908
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
909
				 */
910
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
911
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
912
						/**
913
						 * We need to update the option name -- it's terribly unclear which
914
						 * direction the override goes.
915
						 *
916
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
917
						 */
918
						$caps = array( 'do_not_allow' );
919
						break;
920
					}
921
				}
922
923
				$caps = array( 'manage_options' );
924
				break;
925
			case 'jetpack_manage_modules' :
926
			case 'jetpack_activate_modules' :
927
			case 'jetpack_deactivate_modules' :
928
				$caps = array( 'manage_options' );
929
				break;
930
			case 'jetpack_configure_modules' :
931
				$caps = array( 'manage_options' );
932
				break;
933
			case 'jetpack_manage_autoupdates' :
934
				$caps = array(
935
					'manage_options',
936
					'update_plugins',
937
				);
938
				break;
939
			case 'jetpack_network_admin_page':
940
			case 'jetpack_network_settings_page':
941
				$caps = array( 'manage_network_plugins' );
942
				break;
943
			case 'jetpack_network_sites_page':
944
				$caps = array( 'manage_sites' );
945
				break;
946
			case 'jetpack_admin_page' :
947
				if ( Jetpack::is_development_mode() ) {
948
					$caps = array( 'manage_options' );
949
					break;
950
				} else {
951
					$caps = array( 'read' );
952
				}
953
				break;
954
			case 'jetpack_connect_user' :
955
				if ( Jetpack::is_development_mode() ) {
956
					$caps = array( 'do_not_allow' );
957
					break;
958
				}
959
				$caps = array( 'read' );
960
				break;
961
		}
962
		return $caps;
963
	}
964
965
	/**
966
	 * Load language files
967
	 * @action plugins_loaded
968
	 */
969
	public static function plugin_textdomain() {
970
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
971
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
972
	}
973
974
	/**
975
	 * Register assets for use in various modules and the Jetpack admin page.
976
	 *
977
	 * @uses wp_script_is, wp_register_script, plugins_url
978
	 * @action wp_loaded
979
	 * @return null
980
	 */
981
	public function register_assets() {
982
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
983
			wp_register_script(
984
				'spin',
985
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
986
				false,
987
				'1.3'
988
			);
989
		}
990
991 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
992
			wp_register_script(
993
				'jquery.spin',
994
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
995
				array( 'jquery', 'spin' ),
996
				'1.3'
997
			);
998
		}
999
1000 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1001
			wp_register_script(
1002
				'jetpack-gallery-settings',
1003
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1004
				array( 'media-views' ),
1005
				'20121225'
1006
			);
1007
		}
1008
1009 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1010
			wp_register_script(
1011
				'jetpack-twitter-timeline',
1012
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1013
				array( 'jquery' ),
1014
				'4.0.0',
1015
				true
1016
			);
1017
		}
1018
1019
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1020
			wp_register_script(
1021
				'jetpack-facebook-embed',
1022
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1023
				array( 'jquery' ),
1024
				null,
1025
				true
1026
			);
1027
1028
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1029
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1030
			if ( ! is_numeric( $fb_app_id ) ) {
1031
				$fb_app_id = '';
1032
			}
1033
			wp_localize_script(
1034
				'jetpack-facebook-embed',
1035
				'jpfbembed',
1036
				array(
1037
					'appid' => $fb_app_id,
1038
					'locale' => $this->get_locale(),
1039
				)
1040
			);
1041
		}
1042
1043
		/**
1044
		 * As jetpack_register_genericons is by default fired off a hook,
1045
		 * the hook may have already fired by this point.
1046
		 * So, let's just trigger it manually.
1047
		 */
1048
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1049
		jetpack_register_genericons();
1050
1051
		/**
1052
		 * Register the social logos
1053
		 */
1054
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1055
		jetpack_register_social_logos();
1056
1057 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1058
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1059
	}
1060
1061
	/**
1062
	 * Guess locale from language code.
1063
	 *
1064
	 * @param string $lang Language code.
1065
	 * @return string|bool
1066
	 */
1067 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1068
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1069
			return 'en_US';
1070
		}
1071
1072
		if ( ! class_exists( 'GP_Locales' ) ) {
1073
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1074
				return false;
1075
			}
1076
1077
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1078
		}
1079
1080
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1081
			// WP.com: get_locale() returns 'it'
1082
			$locale = GP_Locales::by_slug( $lang );
1083
		} else {
1084
			// Jetpack: get_locale() returns 'it_IT';
1085
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1086
		}
1087
1088
		if ( ! $locale ) {
1089
			return false;
1090
		}
1091
1092
		if ( empty( $locale->facebook_locale ) ) {
1093
			if ( empty( $locale->wp_locale ) ) {
1094
				return false;
1095
			} else {
1096
				// Facebook SDK is smart enough to fall back to en_US if a
1097
				// locale isn't supported. Since supported Facebook locales
1098
				// can fall out of sync, we'll attempt to use the known
1099
				// wp_locale value and rely on said fallback.
1100
				return $locale->wp_locale;
1101
			}
1102
		}
1103
1104
		return $locale->facebook_locale;
1105
	}
1106
1107
	/**
1108
	 * Get the locale.
1109
	 *
1110
	 * @return string|bool
1111
	 */
1112
	function get_locale() {
1113
		$locale = $this->guess_locale_from_lang( get_locale() );
1114
1115
		if ( ! $locale ) {
1116
			$locale = 'en_US';
1117
		}
1118
1119
		return $locale;
1120
	}
1121
1122
	/**
1123
	 * Device Pixels support
1124
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1125
	 */
1126
	function devicepx() {
1127
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1128
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1129
		}
1130
	}
1131
1132
	/**
1133
	 * Return the network_site_url so that .com knows what network this site is a part of.
1134
	 * @param  bool $option
1135
	 * @return string
1136
	 */
1137
	public function jetpack_main_network_site_option( $option ) {
1138
		return network_site_url();
1139
	}
1140
	/**
1141
	 * Network Name.
1142
	 */
1143
	static function network_name( $option = null ) {
1144
		global $current_site;
1145
		return $current_site->site_name;
1146
	}
1147
	/**
1148
	 * Does the network allow new user and site registrations.
1149
	 * @return string
1150
	 */
1151
	static function network_allow_new_registrations( $option = null ) {
1152
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1153
	}
1154
	/**
1155
	 * Does the network allow admins to add new users.
1156
	 * @return boolian
1157
	 */
1158
	static function network_add_new_users( $option = null ) {
1159
		return (bool) get_site_option( 'add_new_users' );
1160
	}
1161
	/**
1162
	 * File upload psace left per site in MB.
1163
	 *  -1 means NO LIMIT.
1164
	 * @return number
1165
	 */
1166
	static function network_site_upload_space( $option = null ) {
1167
		// value in MB
1168
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1169
	}
1170
1171
	/**
1172
	 * Network allowed file types.
1173
	 * @return string
1174
	 */
1175
	static function network_upload_file_types( $option = null ) {
1176
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1177
	}
1178
1179
	/**
1180
	 * Maximum file upload size set by the network.
1181
	 * @return number
1182
	 */
1183
	static function network_max_upload_file_size( $option = null ) {
1184
		// value in KB
1185
		return get_site_option( 'fileupload_maxk', 300 );
1186
	}
1187
1188
	/**
1189
	 * Lets us know if a site allows admins to manage the network.
1190
	 * @return array
1191
	 */
1192
	static function network_enable_administration_menus( $option = null ) {
1193
		return get_site_option( 'menu_items' );
1194
	}
1195
1196
	/**
1197
	 * If a user has been promoted to or demoted from admin, we need to clear the
1198
	 * jetpack_other_linked_admins transient.
1199
	 *
1200
	 * @since 4.3.2
1201
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1202
	 *
1203
	 * @param int    $user_id   The user ID whose role changed.
1204
	 * @param string $role      The new role.
1205
	 * @param array  $old_roles An array of the user's previous roles.
1206
	 */
1207
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1208
		if ( 'administrator' == $role
1209
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1210
			|| is_null( $old_roles )
1211
		) {
1212
			delete_transient( 'jetpack_other_linked_admins' );
1213
		}
1214
	}
1215
1216
	/**
1217
	 * Checks to see if there are any other users available to become primary
1218
	 * Users must both:
1219
	 * - Be linked to wpcom
1220
	 * - Be an admin
1221
	 *
1222
	 * @return mixed False if no other users are linked, Int if there are.
1223
	 */
1224
	static function get_other_linked_admins() {
1225
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1226
1227
		if ( false === $other_linked_users ) {
1228
			$admins = get_users( array( 'role' => 'administrator' ) );
1229
			if ( count( $admins ) > 1 ) {
1230
				$available = array();
1231
				foreach ( $admins as $admin ) {
1232
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1233
						$available[] = $admin->ID;
1234
					}
1235
				}
1236
1237
				$count_connected_admins = count( $available );
1238
				if ( count( $available ) > 1 ) {
1239
					$other_linked_users = $count_connected_admins;
1240
				} else {
1241
					$other_linked_users = 0;
1242
				}
1243
			} else {
1244
				$other_linked_users = 0;
1245
			}
1246
1247
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1248
		}
1249
1250
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1251
	}
1252
1253
	/**
1254
	 * Return whether we are dealing with a multi network setup or not.
1255
	 * The reason we are type casting this is because we want to avoid the situation where
1256
	 * the result is false since when is_main_network_option return false it cases
1257
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1258
	 * database which could be set to anything as opposed to what this function returns.
1259
	 * @param  bool  $option
1260
	 *
1261
	 * @return boolean
1262
	 */
1263
	public function is_main_network_option( $option ) {
1264
		// return '1' or ''
1265
		return (string) (bool) Jetpack::is_multi_network();
1266
	}
1267
1268
	/**
1269
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1270
	 *
1271
	 * @param  string  $option
1272
	 * @return boolean
1273
	 */
1274
	public function is_multisite( $option ) {
1275
		return (string) (bool) is_multisite();
1276
	}
1277
1278
	/**
1279
	 * Implemented since there is no core is multi network function
1280
	 * Right now there is no way to tell if we which network is the dominant network on the system
1281
	 *
1282
	 * @since  3.3
1283
	 * @return boolean
1284
	 */
1285 View Code Duplication
	public static function is_multi_network() {
1286
		global  $wpdb;
1287
1288
		// if we don't have a multi site setup no need to do any more
1289
		if ( ! is_multisite() ) {
1290
			return false;
1291
		}
1292
1293
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1294
		if ( $num_sites > 1 ) {
1295
			return true;
1296
		} else {
1297
			return false;
1298
		}
1299
	}
1300
1301
	/**
1302
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1303
	 * @return null
1304
	 */
1305
	function update_jetpack_main_network_site_option() {
1306
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1307
	}
1308
	/**
1309
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1310
	 *
1311
	 */
1312
	function update_jetpack_network_settings() {
1313
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1314
		// Only sync this info for the main network site.
1315
	}
1316
1317
	/**
1318
	 * Get back if the current site is single user site.
1319
	 *
1320
	 * @return bool
1321
	 */
1322 View Code Duplication
	public static function is_single_user_site() {
1323
		global $wpdb;
1324
1325
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1326
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1327
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1328
		}
1329
		return 1 === (int) $some_users;
1330
	}
1331
1332
	/**
1333
	 * Returns true if the site has file write access false otherwise.
1334
	 * @return string ( '1' | '0' )
1335
	 **/
1336
	public static function file_system_write_access() {
1337
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1338
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1339
		}
1340
1341
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1342
1343
		$filesystem_method = get_filesystem_method();
1344
		if ( $filesystem_method === 'direct' ) {
1345
			return 1;
1346
		}
1347
1348
		ob_start();
1349
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1350
		ob_end_clean();
1351
		if ( $filesystem_credentials_are_stored ) {
1352
			return 1;
1353
		}
1354
		return 0;
1355
	}
1356
1357
	/**
1358
	 * Finds out if a site is using a version control system.
1359
	 * @return string ( '1' | '0' )
1360
	 **/
1361
	public static function is_version_controlled() {
1362
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1363
		return (string) (int) Functions::is_version_controlled();
1364
	}
1365
1366
	/**
1367
	 * Determines whether the current theme supports featured images or not.
1368
	 * @return string ( '1' | '0' )
1369
	 */
1370
	public static function featured_images_enabled() {
1371
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1372
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1373
	}
1374
1375
	/**
1376
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1377
	 *
1378
	 * @deprecated 4.7 use get_avatar_url instead.
1379
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1380
	 * @param int $size Size of the avatar image
1381
	 * @param string $default URL to a default image to use if no avatar is available
1382
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1383
	 *
1384
	 * @return array
1385
	 */
1386
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1387
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1388
		return get_avatar_url( $id_or_email, array(
1389
			'size' => $size,
1390
			'default' => $default,
1391
			'force_default' => $force_display,
1392
		) );
1393
	}
1394
1395
	/**
1396
	 * jetpack_updates is saved in the following schema:
1397
	 *
1398
	 * array (
1399
	 *      'plugins'                       => (int) Number of plugin updates available.
1400
	 *      'themes'                        => (int) Number of theme updates available.
1401
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1402
	 *      'translations'                  => (int) Number of translation updates available.
1403
	 *      'total'                         => (int) Total of all available updates.
1404
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1405
	 * )
1406
	 * @return array
1407
	 */
1408
	public static function get_updates() {
1409
		$update_data = wp_get_update_data();
1410
1411
		// Stores the individual update counts as well as the total count.
1412
		if ( isset( $update_data['counts'] ) ) {
1413
			$updates = $update_data['counts'];
1414
		}
1415
1416
		// If we need to update WordPress core, let's find the latest version number.
1417 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1418
			$cur = get_preferred_from_update_core();
1419
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1420
				$updates['wp_update_version'] = $cur->current;
1421
			}
1422
		}
1423
		return isset( $updates ) ? $updates : array();
1424
	}
1425
1426
	public static function get_update_details() {
1427
		$update_details = array(
1428
			'update_core' => get_site_transient( 'update_core' ),
1429
			'update_plugins' => get_site_transient( 'update_plugins' ),
1430
			'update_themes' => get_site_transient( 'update_themes' ),
1431
		);
1432
		return $update_details;
1433
	}
1434
1435
	public static function refresh_update_data() {
1436
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1437
1438
	}
1439
1440
	public static function refresh_theme_data() {
1441
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1442
	}
1443
1444
	/**
1445
	 * Is Jetpack active?
1446
	 */
1447
	public static function is_active() {
1448
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1449
	}
1450
1451
	/**
1452
	 * Make an API call to WordPress.com for plan status
1453
	 *
1454
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1455
	 *
1456
	 * @return bool True if plan is updated, false if no update
1457
	 */
1458
	public static function refresh_active_plan_from_wpcom() {
1459
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1460
		return Jetpack_Plan::refresh_from_wpcom();
1461
	}
1462
1463
	/**
1464
	 * Get the plan that this Jetpack site is currently using
1465
	 *
1466
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1467
	 * @return array Active Jetpack plan details.
1468
	 */
1469
	public static function get_active_plan() {
1470
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1471
		return Jetpack_Plan::get();
1472
	}
1473
1474
	/**
1475
	 * Determine whether the active plan supports a particular feature
1476
	 *
1477
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1478
	 * @return bool True if plan supports feature, false if not.
1479
	 */
1480
	public static function active_plan_supports( $feature ) {
1481
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1482
		return Jetpack_Plan::supports( $feature );
1483
	}
1484
1485
	/**
1486
	 * Is Jetpack in development (offline) mode?
1487
	 */
1488 View Code Duplication
	public static function is_development_mode() {
1489
		$development_mode = false;
1490
1491
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1492
			$development_mode = JETPACK_DEV_DEBUG;
1493
		} elseif ( $site_url = site_url() ) {
1494
			$development_mode = false === strpos( $site_url, '.' );
1495
		}
1496
1497
		/**
1498
		 * Filters Jetpack's development mode.
1499
		 *
1500
		 * @see https://jetpack.com/support/development-mode/
1501
		 *
1502
		 * @since 2.2.1
1503
		 *
1504
		 * @param bool $development_mode Is Jetpack's development mode active.
1505
		 */
1506
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1507
		return $development_mode;
1508
	}
1509
1510
	/**
1511
	 * Whether the site is currently onboarding or not.
1512
	 * A site is considered as being onboarded if it currently has an onboarding token.
1513
	 *
1514
	 * @since 5.8
1515
	 *
1516
	 * @access public
1517
	 * @static
1518
	 *
1519
	 * @return bool True if the site is currently onboarding, false otherwise
1520
	 */
1521
	public static function is_onboarding() {
1522
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1523
	}
1524
1525
	/**
1526
	 * Determines reason for Jetpack development mode.
1527
	 */
1528
	public static function development_mode_trigger_text() {
1529
		if ( ! Jetpack::is_development_mode() ) {
1530
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1531
		}
1532
1533
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1534
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1535
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1536
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1537
		} else {
1538
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1539
		}
1540
1541
		return $notice;
1542
1543
	}
1544
	/**
1545
	* Get Jetpack development mode notice text and notice class.
1546
	*
1547
	* Mirrors the checks made in Jetpack::is_development_mode
1548
	*
1549
	*/
1550
	public static function show_development_mode_notice() {
1551 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1552
			$notice = sprintf(
1553
			/* translators: %s is a URL */
1554
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1555
				'https://jetpack.com/support/development-mode/'
1556
			);
1557
1558
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1559
1560
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1561
		}
1562
1563
		// Throw up a notice if using a development version and as for feedback.
1564
		if ( Jetpack::is_development_version() ) {
1565
			/* translators: %s is a URL */
1566
			$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/' );
1567
1568
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1569
		}
1570
		// Throw up a notice if using staging mode
1571
		if ( Jetpack::is_staging_site() ) {
1572
			/* translators: %s is a URL */
1573
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1574
1575
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1576
		}
1577
	}
1578
1579
	/**
1580
	 * Whether Jetpack's version maps to a public release, or a development version.
1581
	 */
1582
	public static function is_development_version() {
1583
		/**
1584
		 * Allows filtering whether this is a development version of Jetpack.
1585
		 *
1586
		 * This filter is especially useful for tests.
1587
		 *
1588
		 * @since 4.3.0
1589
		 *
1590
		 * @param bool $development_version Is this a develoment version of Jetpack?
1591
		 */
1592
		return (bool) apply_filters(
1593
			'jetpack_development_version',
1594
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1595
		);
1596
	}
1597
1598
	/**
1599
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1600
	 */
1601
	public static function is_user_connected( $user_id = false ) {
1602
		return self::connection()->is_user_connected( $user_id );
1603
	}
1604
1605
	/**
1606
	 * Get the wpcom user data of the current|specified connected user.
1607
	 */
1608 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1609
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1610
		if ( ! $user_id ) {
1611
			$user_id = get_current_user_id();
1612
		}
1613
1614
		$transient_key = "jetpack_connected_user_data_$user_id";
1615
1616
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1617
			return $cached_user_data;
1618
		}
1619
1620
		Jetpack::load_xml_rpc_client();
1621
		$xml = new Jetpack_IXR_Client( array(
1622
			'user_id' => $user_id,
1623
		) );
1624
		$xml->query( 'wpcom.getUser' );
1625
		if ( ! $xml->isError() ) {
1626
			$user_data = $xml->getResponse();
1627
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1628
			return $user_data;
1629
		}
1630
1631
		return false;
1632
	}
1633
1634
	/**
1635
	 * Get the wpcom email of the current|specified connected user.
1636
	 */
1637 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1638
		if ( ! $user_id ) {
1639
			$user_id = get_current_user_id();
1640
		}
1641
		Jetpack::load_xml_rpc_client();
1642
		$xml = new Jetpack_IXR_Client( array(
1643
			'user_id' => $user_id,
1644
		) );
1645
		$xml->query( 'wpcom.getUserEmail' );
1646
		if ( ! $xml->isError() ) {
1647
			return $xml->getResponse();
1648
		}
1649
		return false;
1650
	}
1651
1652
	/**
1653
	 * Get the wpcom email of the master user.
1654
	 */
1655
	public static function get_master_user_email() {
1656
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1657
		if ( $master_user_id ) {
1658
			return self::get_connected_user_email( $master_user_id );
1659
		}
1660
		return '';
1661
	}
1662
1663
	function current_user_is_connection_owner() {
1664
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1665
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1666
	}
1667
1668
	/**
1669
	 * Gets current user IP address.
1670
	 *
1671
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1672
	 *
1673
	 * @return string                  Current user IP address.
1674
	 */
1675
	public static function current_user_ip( $check_all_headers = false ) {
1676
		if ( $check_all_headers ) {
1677
			foreach ( array(
1678
				'HTTP_CF_CONNECTING_IP',
1679
				'HTTP_CLIENT_IP',
1680
				'HTTP_X_FORWARDED_FOR',
1681
				'HTTP_X_FORWARDED',
1682
				'HTTP_X_CLUSTER_CLIENT_IP',
1683
				'HTTP_FORWARDED_FOR',
1684
				'HTTP_FORWARDED',
1685
				'HTTP_VIA',
1686
			) as $key ) {
1687
				if ( ! empty( $_SERVER[ $key ] ) ) {
1688
					return $_SERVER[ $key ];
1689
				}
1690
			}
1691
		}
1692
1693
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1694
	}
1695
1696
	/**
1697
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1698
	 */
1699
	function extra_oembed_providers() {
1700
		// Cloudup: https://dev.cloudup.com/#oembed
1701
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1702
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1703
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1704
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1705
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1706
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1707
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1708
	}
1709
1710
	/**
1711
	 * Synchronize connected user role changes
1712
	 */
1713
	function user_role_change( $user_id ) {
1714
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1715
		Users::user_role_change( $user_id );
1716
	}
1717
1718
	/**
1719
	 * Loads the currently active modules.
1720
	 */
1721
	public static function load_modules() {
1722
		if (
1723
			! self::is_active()
1724
			&& ! self::is_development_mode()
1725
			&& ! self::is_onboarding()
1726
			&& (
1727
				! is_multisite()
1728
				|| ! get_site_option( 'jetpack_protect_active' )
1729
			)
1730
		) {
1731
			return;
1732
		}
1733
1734
		$version = Jetpack_Options::get_option( 'version' );
1735 View Code Duplication
		if ( ! $version ) {
1736
			$version = $old_version = JETPACK__VERSION . ':' . time();
1737
			/** This action is documented in class.jetpack.php */
1738
			do_action( 'updating_jetpack_version', $version, false );
1739
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1740
		}
1741
		list( $version ) = explode( ':', $version );
1742
1743
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1744
1745
		$modules_data = array();
1746
1747
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1748
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1749
			$updated_modules = array();
1750
			foreach ( $modules as $module ) {
1751
				$modules_data[ $module ] = Jetpack::get_module( $module );
1752
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1753
					continue;
1754
				}
1755
1756
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1757
					continue;
1758
				}
1759
1760
				$updated_modules[] = $module;
1761
			}
1762
1763
			$modules = array_diff( $modules, $updated_modules );
1764
		}
1765
1766
		$is_development_mode = Jetpack::is_development_mode();
1767
1768
		foreach ( $modules as $index => $module ) {
1769
			// If we're in dev mode, disable modules requiring a connection
1770
			if ( $is_development_mode ) {
1771
				// Prime the pump if we need to
1772
				if ( empty( $modules_data[ $module ] ) ) {
1773
					$modules_data[ $module ] = Jetpack::get_module( $module );
1774
				}
1775
				// If the module requires a connection, but we're in local mode, don't include it.
1776
				if ( $modules_data[ $module ]['requires_connection'] ) {
1777
					continue;
1778
				}
1779
			}
1780
1781
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1782
				continue;
1783
			}
1784
1785
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1786
				unset( $modules[ $index ] );
1787
				self::update_active_modules( array_values( $modules ) );
1788
				continue;
1789
			}
1790
1791
			/**
1792
			 * Fires when a specific module is loaded.
1793
			 * The dynamic part of the hook, $module, is the module slug.
1794
			 *
1795
			 * @since 1.1.0
1796
			 */
1797
			do_action( 'jetpack_module_loaded_' . $module );
1798
		}
1799
1800
		/**
1801
		 * Fires when all the modules are loaded.
1802
		 *
1803
		 * @since 1.1.0
1804
		 */
1805
		do_action( 'jetpack_modules_loaded' );
1806
1807
		// 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.
1808
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1809
	}
1810
1811
	/**
1812
	 * Check if Jetpack's REST API compat file should be included
1813
	 * @action plugins_loaded
1814
	 * @return null
1815
	 */
1816
	public function check_rest_api_compat() {
1817
		/**
1818
		 * Filters the list of REST API compat files to be included.
1819
		 *
1820
		 * @since 2.2.5
1821
		 *
1822
		 * @param array $args Array of REST API compat files to include.
1823
		 */
1824
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1825
1826
		if ( function_exists( 'bbpress' ) )
1827
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1828
1829
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1830
			require_once $_jetpack_rest_api_compat_include;
1831
	}
1832
1833
	/**
1834
	 * Gets all plugins currently active in values, regardless of whether they're
1835
	 * traditionally activated or network activated.
1836
	 *
1837
	 * @todo Store the result in core's object cache maybe?
1838
	 */
1839
	public static function get_active_plugins() {
1840
		$active_plugins = (array) get_option( 'active_plugins', array() );
1841
1842
		if ( is_multisite() ) {
1843
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1844
			// whereas active_plugins stores them in the values.
1845
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1846
			if ( $network_plugins ) {
1847
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1848
			}
1849
		}
1850
1851
		sort( $active_plugins );
1852
1853
		return array_unique( $active_plugins );
1854
	}
1855
1856
	/**
1857
	 * Gets and parses additional plugin data to send with the heartbeat data
1858
	 *
1859
	 * @since 3.8.1
1860
	 *
1861
	 * @return array Array of plugin data
1862
	 */
1863
	public static function get_parsed_plugin_data() {
1864
		if ( ! function_exists( 'get_plugins' ) ) {
1865
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1866
		}
1867
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1868
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1869
		$active_plugins = Jetpack::get_active_plugins();
1870
1871
		$plugins = array();
1872
		foreach ( $all_plugins as $path => $plugin_data ) {
1873
			$plugins[ $path ] = array(
1874
					'is_active' => in_array( $path, $active_plugins ),
1875
					'file'      => $path,
1876
					'name'      => $plugin_data['Name'],
1877
					'version'   => $plugin_data['Version'],
1878
					'author'    => $plugin_data['Author'],
1879
			);
1880
		}
1881
1882
		return $plugins;
1883
	}
1884
1885
	/**
1886
	 * Gets and parses theme data to send with the heartbeat data
1887
	 *
1888
	 * @since 3.8.1
1889
	 *
1890
	 * @return array Array of theme data
1891
	 */
1892
	public static function get_parsed_theme_data() {
1893
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1894
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1895
1896
		$themes = array();
1897
		foreach ( $all_themes as $slug => $theme_data ) {
1898
			$theme_headers = array();
1899
			foreach ( $header_keys as $header_key ) {
1900
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1901
			}
1902
1903
			$themes[ $slug ] = array(
1904
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1905
					'slug' => $slug,
1906
					'theme_root' => $theme_data->get_theme_root_uri(),
1907
					'parent' => $theme_data->parent(),
1908
					'headers' => $theme_headers
1909
			);
1910
		}
1911
1912
		return $themes;
1913
	}
1914
1915
	/**
1916
	 * Checks whether a specific plugin is active.
1917
	 *
1918
	 * We don't want to store these in a static variable, in case
1919
	 * there are switch_to_blog() calls involved.
1920
	 */
1921
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1922
		return in_array( $plugin, self::get_active_plugins() );
1923
	}
1924
1925
	/**
1926
	 * Check if Jetpack's Open Graph tags should be used.
1927
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1928
	 *
1929
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1930
	 * @action plugins_loaded
1931
	 * @return null
1932
	 */
1933
	public function check_open_graph() {
1934
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1935
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1936
		}
1937
1938
		$active_plugins = self::get_active_plugins();
1939
1940
		if ( ! empty( $active_plugins ) ) {
1941
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1942
				if ( in_array( $plugin, $active_plugins ) ) {
1943
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1944
					break;
1945
				}
1946
			}
1947
		}
1948
1949
		/**
1950
		 * Allow the addition of Open Graph Meta Tags to all pages.
1951
		 *
1952
		 * @since 2.0.3
1953
		 *
1954
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1955
		 */
1956
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1957
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1958
		}
1959
	}
1960
1961
	/**
1962
	 * Check if Jetpack's Twitter tags should be used.
1963
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1964
	 *
1965
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1966
	 * @action plugins_loaded
1967
	 * @return null
1968
	 */
1969
	public function check_twitter_tags() {
1970
1971
		$active_plugins = self::get_active_plugins();
1972
1973
		if ( ! empty( $active_plugins ) ) {
1974
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1975
				if ( in_array( $plugin, $active_plugins ) ) {
1976
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1977
					break;
1978
				}
1979
			}
1980
		}
1981
1982
		/**
1983
		 * Allow Twitter Card Meta tags to be disabled.
1984
		 *
1985
		 * @since 2.6.0
1986
		 *
1987
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1988
		 */
1989
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1990
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1991
		}
1992
	}
1993
1994
	/**
1995
	 * Allows plugins to submit security reports.
1996
 	 *
1997
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1998
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1999
	 * @param array   $args         See definitions above
2000
	 */
2001
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2002
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2003
	}
2004
2005
/* Jetpack Options API */
2006
2007
	public static function get_option_names( $type = 'compact' ) {
2008
		return Jetpack_Options::get_option_names( $type );
2009
	}
2010
2011
	/**
2012
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2013
 	 *
2014
	 * @param string $name    Option name
2015
	 * @param mixed  $default (optional)
2016
	 */
2017
	public static function get_option( $name, $default = false ) {
2018
		return Jetpack_Options::get_option( $name, $default );
2019
	}
2020
2021
	/**
2022
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2023
 	 *
2024
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2025
	 * @param string $name  Option name
2026
	 * @param mixed  $value Option value
2027
	 */
2028
	public static function update_option( $name, $value ) {
2029
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2030
		return Jetpack_Options::update_option( $name, $value );
2031
	}
2032
2033
	/**
2034
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2035
 	 *
2036
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2037
	 * @param array $array array( option name => option value, ... )
2038
	 */
2039
	public static function update_options( $array ) {
2040
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2041
		return Jetpack_Options::update_options( $array );
2042
	}
2043
2044
	/**
2045
	 * Deletes the given option.  May be passed multiple option names as an array.
2046
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2047
	 *
2048
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2049
	 * @param string|array $names
2050
	 */
2051
	public static function delete_option( $names ) {
2052
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2053
		return Jetpack_Options::delete_option( $names );
2054
	}
2055
2056
	/**
2057
	 * Enters a user token into the user_tokens option
2058
	 *
2059
	 * @param int $user_id
2060
	 * @param string $token
2061
	 * return bool
2062
	 */
2063
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2064
		// not designed for concurrent updates
2065
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2066
		if ( ! is_array( $user_tokens ) )
2067
			$user_tokens = array();
2068
		$user_tokens[$user_id] = $token;
2069
		if ( $is_master_user ) {
2070
			$master_user = $user_id;
2071
			$options     = compact( 'user_tokens', 'master_user' );
2072
		} else {
2073
			$options = compact( 'user_tokens' );
2074
		}
2075
		return Jetpack_Options::update_options( $options );
2076
	}
2077
2078
	/**
2079
	 * Returns an array of all PHP files in the specified absolute path.
2080
	 * Equivalent to glob( "$absolute_path/*.php" ).
2081
	 *
2082
	 * @param string $absolute_path The absolute path of the directory to search.
2083
	 * @return array Array of absolute paths to the PHP files.
2084
	 */
2085
	public static function glob_php( $absolute_path ) {
2086
		if ( function_exists( 'glob' ) ) {
2087
			return glob( "$absolute_path/*.php" );
2088
		}
2089
2090
		$absolute_path = untrailingslashit( $absolute_path );
2091
		$files = array();
2092
		if ( ! $dir = @opendir( $absolute_path ) ) {
2093
			return $files;
2094
		}
2095
2096
		while ( false !== $file = readdir( $dir ) ) {
2097
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2098
				continue;
2099
			}
2100
2101
			$file = "$absolute_path/$file";
2102
2103
			if ( ! is_file( $file ) ) {
2104
				continue;
2105
			}
2106
2107
			$files[] = $file;
2108
		}
2109
2110
		closedir( $dir );
2111
2112
		return $files;
2113
	}
2114
2115
	public static function activate_new_modules( $redirect = false ) {
2116
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2117
			return;
2118
		}
2119
2120
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2121 View Code Duplication
		if ( ! $jetpack_old_version ) {
2122
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2123
			/** This action is documented in class.jetpack.php */
2124
			do_action( 'updating_jetpack_version', $version, false );
2125
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2126
		}
2127
2128
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2129
2130
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2131
			return;
2132
		}
2133
2134
		$active_modules     = Jetpack::get_active_modules();
2135
		$reactivate_modules = array();
2136
		foreach ( $active_modules as $active_module ) {
2137
			$module = Jetpack::get_module( $active_module );
2138
			if ( ! isset( $module['changed'] ) ) {
2139
				continue;
2140
			}
2141
2142
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2143
				continue;
2144
			}
2145
2146
			$reactivate_modules[] = $active_module;
2147
			Jetpack::deactivate_module( $active_module );
2148
		}
2149
2150
		$new_version = JETPACK__VERSION . ':' . time();
2151
		/** This action is documented in class.jetpack.php */
2152
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2153
		Jetpack_Options::update_options(
2154
			array(
2155
				'version'     => $new_version,
2156
				'old_version' => $jetpack_old_version,
2157
			)
2158
		);
2159
2160
		Jetpack::state( 'message', 'modules_activated' );
2161
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2162
2163
		if ( $redirect ) {
2164
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2165
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2166
				$page = $_GET['page'];
2167
			}
2168
2169
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2170
			exit;
2171
		}
2172
	}
2173
2174
	/**
2175
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2176
	 * Make sure to tuck away module "library" files in a sub-directory.
2177
	 */
2178
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2179
		static $modules = null;
2180
2181
		if ( ! isset( $modules ) ) {
2182
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2183
			// Use the cache if we're on the front-end and it's available...
2184
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2185
				$modules = $available_modules_option[ JETPACK__VERSION ];
2186
			} else {
2187
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2188
2189
				$modules = array();
2190
2191
				foreach ( $files as $file ) {
2192
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2193
						continue;
2194
					}
2195
2196
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2197
				}
2198
2199
				Jetpack_Options::update_option( 'available_modules', array(
2200
					JETPACK__VERSION => $modules,
2201
				) );
2202
			}
2203
		}
2204
2205
		/**
2206
		 * Filters the array of modules available to be activated.
2207
		 *
2208
		 * @since 2.4.0
2209
		 *
2210
		 * @param array $modules Array of available modules.
2211
		 * @param string $min_version Minimum version number required to use modules.
2212
		 * @param string $max_version Maximum version number required to use modules.
2213
		 */
2214
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2215
2216
		if ( ! $min_version && ! $max_version ) {
2217
			return array_keys( $mods );
2218
		}
2219
2220
		$r = array();
2221
		foreach ( $mods as $slug => $introduced ) {
2222
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2223
				continue;
2224
			}
2225
2226
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2227
				continue;
2228
			}
2229
2230
			$r[] = $slug;
2231
		}
2232
2233
		return $r;
2234
	}
2235
2236
	/**
2237
	 * Default modules loaded on activation.
2238
	 */
2239
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2240
		$return = array();
2241
2242
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2243
			$module_data = Jetpack::get_module( $module );
2244
2245
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2246
				case 'yes' :
2247
					$return[] = $module;
2248
					break;
2249
				case 'public' :
2250
					if ( Jetpack_Options::get_option( 'public' ) ) {
2251
						$return[] = $module;
2252
					}
2253
					break;
2254
				case 'no' :
2255
				default :
2256
					break;
2257
			}
2258
		}
2259
		/**
2260
		 * Filters the array of default modules.
2261
		 *
2262
		 * @since 2.5.0
2263
		 *
2264
		 * @param array $return Array of default modules.
2265
		 * @param string $min_version Minimum version number required to use modules.
2266
		 * @param string $max_version Maximum version number required to use modules.
2267
		 */
2268
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2269
	}
2270
2271
	/**
2272
	 * Checks activated modules during auto-activation to determine
2273
	 * if any of those modules are being deprecated.  If so, close
2274
	 * them out, and add any replacement modules.
2275
	 *
2276
	 * Runs at priority 99 by default.
2277
	 *
2278
	 * This is run late, so that it can still activate a module if
2279
	 * the new module is a replacement for another that the user
2280
	 * currently has active, even if something at the normal priority
2281
	 * would kibosh everything.
2282
	 *
2283
	 * @since 2.6
2284
	 * @uses jetpack_get_default_modules filter
2285
	 * @param array $modules
2286
	 * @return array
2287
	 */
2288
	function handle_deprecated_modules( $modules ) {
2289
		$deprecated_modules = array(
2290
			'debug'            => null,  // Closed out and moved to the debugger library.
2291
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2292
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2293
		);
2294
2295
		// Don't activate SSO if they never completed activating WPCC.
2296
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2297
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2298
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2299
				$deprecated_modules['wpcc'] = null;
2300
			}
2301
		}
2302
2303
		foreach ( $deprecated_modules as $module => $replacement ) {
2304
			if ( Jetpack::is_module_active( $module ) ) {
2305
				self::deactivate_module( $module );
2306
				if ( $replacement ) {
2307
					$modules[] = $replacement;
2308
				}
2309
			}
2310
		}
2311
2312
		return array_unique( $modules );
2313
	}
2314
2315
	/**
2316
	 * Checks activated plugins during auto-activation to determine
2317
	 * if any of those plugins are in the list with a corresponding module
2318
	 * that is not compatible with the plugin. The module will not be allowed
2319
	 * to auto-activate.
2320
	 *
2321
	 * @since 2.6
2322
	 * @uses jetpack_get_default_modules filter
2323
	 * @param array $modules
2324
	 * @return array
2325
	 */
2326
	function filter_default_modules( $modules ) {
2327
2328
		$active_plugins = self::get_active_plugins();
2329
2330
		if ( ! empty( $active_plugins ) ) {
2331
2332
			// For each module we'd like to auto-activate...
2333
			foreach ( $modules as $key => $module ) {
2334
				// If there are potential conflicts for it...
2335
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2336
					// For each potential conflict...
2337
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2338
						// If that conflicting plugin is active...
2339
						if ( in_array( $plugin, $active_plugins ) ) {
2340
							// Remove that item from being auto-activated.
2341
							unset( $modules[ $key ] );
2342
						}
2343
					}
2344
				}
2345
			}
2346
		}
2347
2348
		return $modules;
2349
	}
2350
2351
	/**
2352
	 * Extract a module's slug from its full path.
2353
	 */
2354
	public static function get_module_slug( $file ) {
2355
		return str_replace( '.php', '', basename( $file ) );
2356
	}
2357
2358
	/**
2359
	 * Generate a module's path from its slug.
2360
	 */
2361
	public static function get_module_path( $slug ) {
2362
		/**
2363
		 * Filters the path of a modules.
2364
		 *
2365
		 * @since 7.4.0
2366
		 *
2367
		 * @param array $return The absolute path to a module's root php file
2368
		 * @param string $slug The module slug
2369
		 */
2370
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2371
	}
2372
2373
	/**
2374
	 * Load module data from module file. Headers differ from WordPress
2375
	 * plugin headers to avoid them being identified as standalone
2376
	 * plugins on the WordPress plugins page.
2377
	 */
2378
	public static function get_module( $module ) {
2379
		$headers = array(
2380
			'name'                      => 'Module Name',
2381
			'description'               => 'Module Description',
2382
			'sort'                      => 'Sort Order',
2383
			'recommendation_order'      => 'Recommendation Order',
2384
			'introduced'                => 'First Introduced',
2385
			'changed'                   => 'Major Changes In',
2386
			'deactivate'                => 'Deactivate',
2387
			'free'                      => 'Free',
2388
			'requires_connection'       => 'Requires Connection',
2389
			'auto_activate'             => 'Auto Activate',
2390
			'module_tags'               => 'Module Tags',
2391
			'feature'                   => 'Feature',
2392
			'additional_search_queries' => 'Additional Search Queries',
2393
			'plan_classes'              => 'Plans',
2394
		);
2395
2396
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2397
2398
		$mod = Jetpack::get_file_data( $file, $headers );
2399
		if ( empty( $mod['name'] ) ) {
2400
			return false;
2401
		}
2402
2403
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2404
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2405
		$mod['deactivate']              = empty( $mod['deactivate'] );
2406
		$mod['free']                    = empty( $mod['free'] );
2407
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2408
2409
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2410
			$mod['auto_activate'] = 'No';
2411
		} else {
2412
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2413
		}
2414
2415
		if ( $mod['module_tags'] ) {
2416
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2417
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2418
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2419
		} else {
2420
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2421
		}
2422
2423 View Code Duplication
		if ( $mod['plan_classes'] ) {
2424
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2425
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2426
		} else {
2427
			$mod['plan_classes'] = array( 'free' );
2428
		}
2429
2430 View Code Duplication
		if ( $mod['feature'] ) {
2431
			$mod['feature'] = explode( ',', $mod['feature'] );
2432
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2433
		} else {
2434
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2435
		}
2436
2437
		/**
2438
		 * Filters the feature array on a module.
2439
		 *
2440
		 * This filter allows you to control where each module is filtered: Recommended,
2441
		 * and the default "Other" listing.
2442
		 *
2443
		 * @since 3.5.0
2444
		 *
2445
		 * @param array   $mod['feature'] The areas to feature this module:
2446
		 *     'Recommended' shows on the main Jetpack admin screen.
2447
		 *     'Other' should be the default if no other value is in the array.
2448
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2449
		 * @param array   $mod All the currently assembled module data.
2450
		 */
2451
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2452
2453
		/**
2454
		 * Filter the returned data about a module.
2455
		 *
2456
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2457
		 * so please be careful.
2458
		 *
2459
		 * @since 3.6.0
2460
		 *
2461
		 * @param array   $mod    The details of the requested module.
2462
		 * @param string  $module The slug of the module, e.g. sharedaddy
2463
		 * @param string  $file   The path to the module source file.
2464
		 */
2465
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2466
	}
2467
2468
	/**
2469
	 * Like core's get_file_data implementation, but caches the result.
2470
	 */
2471
	public static function get_file_data( $file, $headers ) {
2472
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2473
		$file_name = basename( $file );
2474
2475
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2476
2477
		$file_data_option = get_transient( $cache_key );
2478
2479
		if ( false === $file_data_option ) {
2480
			$file_data_option = array();
2481
		}
2482
2483
		$key           = md5( $file_name . serialize( $headers ) );
2484
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2485
2486
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2487
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2488
			return $file_data_option[ $key ];
2489
		}
2490
2491
		$data = get_file_data( $file, $headers );
2492
2493
		$file_data_option[ $key ] = $data;
2494
2495
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2496
2497
		return $data;
2498
	}
2499
2500
2501
	/**
2502
	 * Return translated module tag.
2503
	 *
2504
	 * @param string $tag Tag as it appears in each module heading.
2505
	 *
2506
	 * @return mixed
2507
	 */
2508
	public static function translate_module_tag( $tag ) {
2509
		return jetpack_get_module_i18n_tag( $tag );
2510
	}
2511
2512
	/**
2513
	 * Get i18n strings as a JSON-encoded string
2514
	 *
2515
	 * @return string The locale as JSON
2516
	 */
2517
	public static function get_i18n_data_json() {
2518
2519
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2520
		// JSON files with the file they should be included for. This is an md5
2521
		// of '_inc/build/admin.js'.
2522
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2523
2524
		$i18n_json =
2525
				   JETPACK__PLUGIN_DIR
2526
				   . 'languages/json/jetpack-'
2527
				   . get_user_locale()
2528
				   . '-'
2529
				   . $path_md5
2530
				   . '.json';
2531
2532
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2533
			$locale_data = @file_get_contents( $i18n_json );
2534
			if ( $locale_data ) {
2535
				return $locale_data;
2536
			}
2537
		}
2538
2539
		// Return valid empty Jed locale
2540
		return '{ "locale_data": { "messages": { "": {} } } }';
2541
	}
2542
2543
	/**
2544
	 * Add locale data setup to wp-i18n
2545
	 *
2546
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2547
	 *
2548
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2549
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2550
	 *
2551
	 * This method provides a safe way to request the setup multiple times but add the script at
2552
	 * most once.
2553
	 *
2554
	 * @since 6.7.0
2555
	 *
2556
	 * @return void
2557
	 */
2558
	public static function setup_wp_i18n_locale_data() {
2559
		static $script_added = false;
2560
		if ( ! $script_added ) {
2561
			$script_added = true;
2562
			wp_add_inline_script(
2563
				'wp-i18n',
2564
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2565
			);
2566
		}
2567
	}
2568
2569
	/**
2570
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2571
	 *
2572
	 * @since 3.9.2
2573
	 *
2574
	 * @param array $modules
2575
	 *
2576
	 * @return string|void
2577
	 */
2578
	public static function get_translated_modules( $modules ) {
2579
		foreach ( $modules as $index => $module ) {
2580
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2581
			if ( isset( $module['name'] ) ) {
2582
				$modules[ $index ]['name'] = $i18n_module['name'];
2583
			}
2584
			if ( isset( $module['description'] ) ) {
2585
				$modules[ $index ]['description'] = $i18n_module['description'];
2586
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2587
			}
2588
		}
2589
		return $modules;
2590
	}
2591
2592
	/**
2593
	 * Get a list of activated modules as an array of module slugs.
2594
	 */
2595
	public static function get_active_modules() {
2596
		$active = Jetpack_Options::get_option( 'active_modules' );
2597
2598
		if ( ! is_array( $active ) ) {
2599
			$active = array();
2600
		}
2601
2602
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2603
			$active[] = 'vaultpress';
2604
		} else {
2605
			$active = array_diff( $active, array( 'vaultpress' ) );
2606
		}
2607
2608
		//If protect is active on the main site of a multisite, it should be active on all sites.
2609
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2610
			$active[] = 'protect';
2611
		}
2612
2613
		/**
2614
		 * Allow filtering of the active modules.
2615
		 *
2616
		 * Gives theme and plugin developers the power to alter the modules that
2617
		 * are activated on the fly.
2618
		 *
2619
		 * @since 5.8.0
2620
		 *
2621
		 * @param array $active Array of active module slugs.
2622
		 */
2623
		$active = apply_filters( 'jetpack_active_modules', $active );
2624
2625
		return array_unique( $active );
2626
	}
2627
2628
	/**
2629
	 * Check whether or not a Jetpack module is active.
2630
	 *
2631
	 * @param string $module The slug of a Jetpack module.
2632
	 * @return bool
2633
	 *
2634
	 * @static
2635
	 */
2636
	public static function is_module_active( $module ) {
2637
		return in_array( $module, self::get_active_modules() );
2638
	}
2639
2640
	public static function is_module( $module ) {
2641
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2642
	}
2643
2644
	/**
2645
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2646
	 *
2647
	 * @param bool $catch True to start catching, False to stop.
2648
	 *
2649
	 * @static
2650
	 */
2651
	public static function catch_errors( $catch ) {
2652
		static $display_errors, $error_reporting;
2653
2654
		if ( $catch ) {
2655
			$display_errors  = @ini_set( 'display_errors', 1 );
2656
			$error_reporting = @error_reporting( E_ALL );
2657
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2658
		} else {
2659
			@ini_set( 'display_errors', $display_errors );
2660
			@error_reporting( $error_reporting );
2661
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2662
		}
2663
	}
2664
2665
	/**
2666
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2667
	 */
2668
	public static function catch_errors_on_shutdown() {
2669
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2670
	}
2671
2672
	/**
2673
	 * Rewrite any string to make paths easier to read.
2674
	 *
2675
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2676
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2677
	 *
2678
	 * @param $string
2679
	 * @return mixed
2680
	 */
2681
	public static function alias_directories( $string ) {
2682
		// ABSPATH has a trailing slash.
2683
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2684
		// WP_CONTENT_DIR does not have a trailing slash.
2685
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2686
2687
		return $string;
2688
	}
2689
2690
	public static function activate_default_modules(
2691
		$min_version = false,
2692
		$max_version = false,
2693
		$other_modules = array(),
2694
		$redirect = true,
2695
		$send_state_messages = true
2696
	) {
2697
		$jetpack = Jetpack::init();
2698
2699
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2700
		$modules = array_merge( $other_modules, $modules );
2701
2702
		// Look for standalone plugins and disable if active.
2703
2704
		$to_deactivate = array();
2705
		foreach ( $modules as $module ) {
2706
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2707
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2708
			}
2709
		}
2710
2711
		$deactivated = array();
2712
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2713
			list( $probable_file, $probable_title ) = $deactivate_me;
2714
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2715
				$deactivated[] = $module;
2716
			}
2717
		}
2718
2719
		if ( $deactivated && $redirect ) {
2720
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2721
2722
			$url = add_query_arg(
2723
				array(
2724
					'action'   => 'activate_default_modules',
2725
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2726
				),
2727
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2728
			);
2729
			wp_safe_redirect( $url );
2730
			exit;
2731
		}
2732
2733
		/**
2734
		 * Fires before default modules are activated.
2735
		 *
2736
		 * @since 1.9.0
2737
		 *
2738
		 * @param string $min_version Minimum version number required to use modules.
2739
		 * @param string $max_version Maximum version number required to use modules.
2740
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2741
		 */
2742
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2743
2744
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2745
		if ( $send_state_messages ) {
2746
			Jetpack::restate();
2747
			Jetpack::catch_errors( true );
2748
		}
2749
2750
		$active = Jetpack::get_active_modules();
2751
2752
		foreach ( $modules as $module ) {
2753
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2754
				$active[] = $module;
2755
				self::update_active_modules( $active );
2756
				continue;
2757
			}
2758
2759
			if ( $send_state_messages && in_array( $module, $active ) ) {
2760
				$module_info = Jetpack::get_module( $module );
2761 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2762
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2763
					if ( $active_state = Jetpack::state( $state ) ) {
2764
						$active_state = explode( ',', $active_state );
2765
					} else {
2766
						$active_state = array();
2767
					}
2768
					$active_state[] = $module;
2769
					Jetpack::state( $state, implode( ',', $active_state ) );
2770
				}
2771
				continue;
2772
			}
2773
2774
			$file = Jetpack::get_module_path( $module );
2775
			if ( ! file_exists( $file ) ) {
2776
				continue;
2777
			}
2778
2779
			// we'll override this later if the plugin can be included without fatal error
2780
			if ( $redirect ) {
2781
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2782
			}
2783
2784
			if ( $send_state_messages ) {
2785
				Jetpack::state( 'error', 'module_activation_failed' );
2786
				Jetpack::state( 'module', $module );
2787
			}
2788
2789
			ob_start();
2790
			require_once $file;
2791
2792
			$active[] = $module;
2793
2794 View Code Duplication
			if ( $send_state_messages ) {
2795
2796
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2797
				if ( $active_state = Jetpack::state( $state ) ) {
2798
					$active_state = explode( ',', $active_state );
2799
				} else {
2800
					$active_state = array();
2801
				}
2802
				$active_state[] = $module;
2803
				Jetpack::state( $state, implode( ',', $active_state ) );
2804
			}
2805
2806
			Jetpack::update_active_modules( $active );
2807
2808
			ob_end_clean();
2809
		}
2810
2811
		if ( $send_state_messages ) {
2812
			Jetpack::state( 'error', false );
2813
			Jetpack::state( 'module', false );
2814
		}
2815
2816
		Jetpack::catch_errors( false );
2817
		/**
2818
		 * Fires when default modules are activated.
2819
		 *
2820
		 * @since 1.9.0
2821
		 *
2822
		 * @param string $min_version Minimum version number required to use modules.
2823
		 * @param string $max_version Maximum version number required to use modules.
2824
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2825
		 */
2826
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2827
	}
2828
2829
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2830
		/**
2831
		 * Fires before a module is activated.
2832
		 *
2833
		 * @since 2.6.0
2834
		 *
2835
		 * @param string $module Module slug.
2836
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2837
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2838
		 */
2839
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2840
2841
		$jetpack = Jetpack::init();
2842
2843
		if ( ! strlen( $module ) )
2844
			return false;
2845
2846
		if ( ! Jetpack::is_module( $module ) )
2847
			return false;
2848
2849
		// If it's already active, then don't do it again
2850
		$active = Jetpack::get_active_modules();
2851
		foreach ( $active as $act ) {
2852
			if ( $act == $module )
2853
				return true;
2854
		}
2855
2856
		$module_data = Jetpack::get_module( $module );
2857
2858
		if ( ! Jetpack::is_active() ) {
2859
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2860
				return false;
2861
2862
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2863
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2864
				return false;
2865
		}
2866
2867
		// Check and see if the old plugin is active
2868
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2869
			// Deactivate the old plugin
2870
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2871
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2872
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2873
				Jetpack::state( 'deactivated_plugins', $module );
2874
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2875
				exit;
2876
			}
2877
		}
2878
2879
		// Protect won't work with mis-configured IPs
2880
		if ( 'protect' === $module ) {
2881
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2882
			if ( ! jetpack_protect_get_ip() ) {
2883
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2884
				return false;
2885
			}
2886
		}
2887
2888
		if ( ! Jetpack_Plan::supports( $module ) ) {
2889
			return false;
2890
		}
2891
2892
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2893
		Jetpack::state( 'module', $module );
2894
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2895
2896
		Jetpack::catch_errors( true );
2897
		ob_start();
2898
		require Jetpack::get_module_path( $module );
2899
		/** This action is documented in class.jetpack.php */
2900
		do_action( 'jetpack_activate_module', $module );
2901
		$active[] = $module;
2902
		Jetpack::update_active_modules( $active );
2903
2904
		Jetpack::state( 'error', false ); // the override
2905
		ob_end_clean();
2906
		Jetpack::catch_errors( false );
2907
2908
		if ( $redirect ) {
2909
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2910
		}
2911
		if ( $exit ) {
2912
			exit;
2913
		}
2914
		return true;
2915
	}
2916
2917
	function activate_module_actions( $module ) {
2918
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2919
	}
2920
2921
	public static function deactivate_module( $module ) {
2922
		/**
2923
		 * Fires when a module is deactivated.
2924
		 *
2925
		 * @since 1.9.0
2926
		 *
2927
		 * @param string $module Module slug.
2928
		 */
2929
		do_action( 'jetpack_pre_deactivate_module', $module );
2930
2931
		$jetpack = Jetpack::init();
2932
2933
		$active = Jetpack::get_active_modules();
2934
		$new    = array_filter( array_diff( $active, (array) $module ) );
2935
2936
		return self::update_active_modules( $new );
2937
	}
2938
2939
	public static function enable_module_configurable( $module ) {
2940
		$module = Jetpack::get_module_slug( $module );
2941
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2942
	}
2943
2944
	/**
2945
	 * Composes a module configure URL. It uses Jetpack settings search as default value
2946
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2947
	 *
2948
	 * @param string $module Module slug
2949
	 * @return string $url module configuration URL
2950
	 */
2951
	public static function module_configuration_url( $module ) {
2952
		$module = Jetpack::get_module_slug( $module );
2953
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
2954
		/**
2955
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2956
		 *
2957
		 * @since 6.9.0
2958
		 *
2959
		 * @param string $default_url Default url, which redirects to jetpack settings page.
2960
		 */
2961
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2962
2963
		return $url;
2964
	}
2965
2966
/* Installation */
2967
	public static function bail_on_activation( $message, $deactivate = true ) {
2968
?>
2969
<!doctype html>
2970
<html>
2971
<head>
2972
<meta charset="<?php bloginfo( 'charset' ); ?>">
2973
<style>
2974
* {
2975
	text-align: center;
2976
	margin: 0;
2977
	padding: 0;
2978
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2979
}
2980
p {
2981
	margin-top: 1em;
2982
	font-size: 18px;
2983
}
2984
</style>
2985
<body>
2986
<p><?php echo esc_html( $message ); ?></p>
2987
</body>
2988
</html>
2989
<?php
2990
		if ( $deactivate ) {
2991
			$plugins = get_option( 'active_plugins' );
2992
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2993
			$update  = false;
2994
			foreach ( $plugins as $i => $plugin ) {
2995
				if ( $plugin === $jetpack ) {
2996
					$plugins[$i] = false;
2997
					$update = true;
2998
				}
2999
			}
3000
3001
			if ( $update ) {
3002
				update_option( 'active_plugins', array_filter( $plugins ) );
3003
			}
3004
		}
3005
		exit;
3006
	}
3007
3008
	/**
3009
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3010
	 * @static
3011
	 */
3012
	public static function plugin_activation( $network_wide ) {
3013
		Jetpack_Options::update_option( 'activated', 1 );
3014
3015
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3016
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3017
		}
3018
3019
		if ( $network_wide )
3020
			Jetpack::state( 'network_nag', true );
3021
3022
		// For firing one-off events (notices) immediately after activation
3023
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3024
3025
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3026
3027
		Jetpack::plugin_initialize();
3028
	}
3029
3030
	public static function get_activation_source( $referer_url ) {
3031
3032
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3033
			return array( 'wp-cli', null );
3034
		}
3035
3036
		$referer = parse_url( $referer_url );
3037
3038
		$source_type = 'unknown';
3039
		$source_query = null;
3040
3041
		if ( ! is_array( $referer ) ) {
3042
			return array( $source_type, $source_query );
3043
		}
3044
3045
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3046
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3047
3048
		if ( isset( $referer['query'] ) ) {
3049
			parse_str( $referer['query'], $query_parts );
3050
		} else {
3051
			$query_parts = array();
3052
		}
3053
3054
		if ( $plugins_path === $referer['path'] ) {
3055
			$source_type = 'list';
3056
		} elseif ( $plugins_install_path === $referer['path'] ) {
3057
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3058
			switch( $tab ) {
3059
				case 'popular':
3060
					$source_type = 'popular';
3061
					break;
3062
				case 'recommended':
3063
					$source_type = 'recommended';
3064
					break;
3065
				case 'favorites':
3066
					$source_type = 'favorites';
3067
					break;
3068
				case 'search':
3069
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3070
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3071
					break;
3072
				default:
3073
					$source_type = 'featured';
3074
			}
3075
		}
3076
3077
		return array( $source_type, $source_query );
3078
	}
3079
3080
	/**
3081
	 * Runs before bumping version numbers up to a new version
3082
	 * @param  string $version    Version:timestamp
3083
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3084
	 * @return null              [description]
3085
	 */
3086
	public static function do_version_bump( $version, $old_version ) {
3087
		if ( ! $old_version ) { // For new sites
3088
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3089
		}
3090
	}
3091
3092
	/**
3093
	 * Sets the internal version number and activation state.
3094
	 * @static
3095
	 */
3096
	public static function plugin_initialize() {
3097
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3098
			Jetpack_Options::update_option( 'activated', 2 );
3099
		}
3100
3101 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3102
			$version = $old_version = JETPACK__VERSION . ':' . time();
3103
			/** This action is documented in class.jetpack.php */
3104
			do_action( 'updating_jetpack_version', $version, false );
3105
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3106
		}
3107
3108
		Jetpack::load_modules();
3109
3110
		Jetpack_Options::delete_option( 'do_activate' );
3111
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3112
	}
3113
3114
	/**
3115
	 * Removes all connection options
3116
	 * @static
3117
	 */
3118
	public static function plugin_deactivation( ) {
3119
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3120
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3121
			Jetpack_Network::init()->deactivate();
3122
		} else {
3123
			Jetpack::disconnect( false );
3124
			//Jetpack_Heartbeat::init()->deactivate();
3125
		}
3126
	}
3127
3128
	/**
3129
	 * Disconnects from the Jetpack servers.
3130
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3131
	 * @static
3132
	 */
3133
	public static function disconnect( $update_activated_state = true ) {
3134
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3135
		$connection = self::connection();
3136
		$connection->clean_nonces( true );
3137
3138
		// If the site is in an IDC because sync is not allowed,
3139
		// let's make sure to not disconnect the production site.
3140
		if ( ! self::validate_sync_error_idc_option() ) {
3141
			$tracking = new Tracking();
3142
			$tracking->record_user_event( 'disconnect_site', array() );
3143
			Jetpack::load_xml_rpc_client();
3144
			$xml = new Jetpack_IXR_Client();
3145
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3146
		}
3147
3148
		Jetpack_Options::delete_option(
3149
			array(
3150
				'blog_token',
3151
				'user_token',
3152
				'user_tokens',
3153
				'master_user',
3154
				'time_diff',
3155
				'fallback_no_verify_ssl_certs',
3156
			)
3157
		);
3158
3159
		Jetpack_IDC::clear_all_idc_options();
3160
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3161
3162
		if ( $update_activated_state ) {
3163
			Jetpack_Options::update_option( 'activated', 4 );
3164
		}
3165
3166
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3167
			// Check then record unique disconnection if site has never been disconnected previously
3168
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3169
				$jetpack_unique_connection['disconnected'] = 1;
3170
			} else {
3171
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3172
					//track unique disconnect
3173
					$jetpack = Jetpack::init();
3174
3175
					$jetpack->stat( 'connections', 'unique-disconnect' );
3176
					$jetpack->do_stats( 'server_side' );
3177
				}
3178
				// increment number of times disconnected
3179
				$jetpack_unique_connection['disconnected'] += 1;
3180
			}
3181
3182
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3183
		}
3184
3185
		// Delete cached connected user data
3186
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3187
		delete_transient( $transient_key );
3188
3189
		// Delete all the sync related data. Since it could be taking up space.
3190
		Sender::get_instance()->uninstall();
3191
3192
		// Disable the Heartbeat cron
3193
		Jetpack_Heartbeat::init()->deactivate();
3194
	}
3195
3196
	/**
3197
	 * Unlinks the current user from the linked WordPress.com user
3198
	 */
3199
	public static function unlink_user( $user_id = null ) {
3200
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3201
			return false;
3202
3203
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3204
3205
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3206
			return false;
3207
3208
		if ( ! isset( $tokens[ $user_id ] ) )
3209
			return false;
3210
3211
		Jetpack::load_xml_rpc_client();
3212
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3213
		$xml->query( 'jetpack.unlink_user', $user_id );
3214
3215
		unset( $tokens[ $user_id ] );
3216
3217
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3218
3219
		/**
3220
		 * Fires after the current user has been unlinked from WordPress.com.
3221
		 *
3222
		 * @since 4.1.0
3223
		 *
3224
		 * @param int $user_id The current user's ID.
3225
		 */
3226
		do_action( 'jetpack_unlinked_user', $user_id );
3227
3228
		return true;
3229
	}
3230
3231
	/**
3232
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3233
	 */
3234
	public static function try_registration() {
3235
		// The user has agreed to the TOS at some point by now.
3236
		Jetpack_Options::update_option( 'tos_agreed', true );
3237
3238
		// Let's get some testing in beta versions and such.
3239
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3240
			// Before attempting to connect, let's make sure that the domains are viable.
3241
			$domains_to_check = array_unique( array(
3242
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3243
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3244
			) );
3245
			foreach ( $domains_to_check as $domain ) {
3246
				$result = self::connection()->is_usable_domain( $domain );
3247
				if ( is_wp_error( $result ) ) {
3248
					return $result;
3249
				}
3250
			}
3251
		}
3252
3253
		$result = Jetpack::register();
3254
3255
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3256
		if ( ! $result || is_wp_error( $result ) ) {
3257
			return $result;
3258
		} else {
3259
			return true;
3260
		}
3261
	}
3262
3263
	/**
3264
	 * Tracking an internal event log. Try not to put too much chaff in here.
3265
	 *
3266
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3267
	 */
3268
	public static function log( $code, $data = null ) {
3269
		// only grab the latest 200 entries
3270
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3271
3272
		// Append our event to the log
3273
		$log_entry = array(
3274
			'time'    => time(),
3275
			'user_id' => get_current_user_id(),
3276
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3277
			'code'    => $code,
3278
		);
3279
		// Don't bother storing it unless we've got some.
3280
		if ( ! is_null( $data ) ) {
3281
			$log_entry['data'] = $data;
3282
		}
3283
		$log[] = $log_entry;
3284
3285
		// Try add_option first, to make sure it's not autoloaded.
3286
		// @todo: Add an add_option method to Jetpack_Options
3287
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3288
			Jetpack_Options::update_option( 'log', $log );
3289
		}
3290
3291
		/**
3292
		 * Fires when Jetpack logs an internal event.
3293
		 *
3294
		 * @since 3.0.0
3295
		 *
3296
		 * @param array $log_entry {
3297
		 *	Array of details about the log entry.
3298
		 *
3299
		 *	@param string time Time of the event.
3300
		 *	@param int user_id ID of the user who trigerred the event.
3301
		 *	@param int blog_id Jetpack Blog ID.
3302
		 *	@param string code Unique name for the event.
3303
		 *	@param string data Data about the event.
3304
		 * }
3305
		 */
3306
		do_action( 'jetpack_log_entry', $log_entry );
3307
	}
3308
3309
	/**
3310
	 * Get the internal event log.
3311
	 *
3312
	 * @param $event (string) - only return the specific log events
3313
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3314
	 *
3315
	 * @return array of log events || WP_Error for invalid params
3316
	 */
3317
	public static function get_log( $event = false, $num = false ) {
3318
		if ( $event && ! is_string( $event ) ) {
3319
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3320
		}
3321
3322
		if ( $num && ! is_numeric( $num ) ) {
3323
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3324
		}
3325
3326
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3327
3328
		// If nothing set - act as it did before, otherwise let's start customizing the output
3329
		if ( ! $num && ! $event ) {
3330
			return $entire_log;
3331
		} else {
3332
			$entire_log = array_reverse( $entire_log );
3333
		}
3334
3335
		$custom_log_output = array();
3336
3337
		if ( $event ) {
3338
			foreach ( $entire_log as $log_event ) {
3339
				if ( $event == $log_event[ 'code' ] ) {
3340
					$custom_log_output[] = $log_event;
3341
				}
3342
			}
3343
		} else {
3344
			$custom_log_output = $entire_log;
3345
		}
3346
3347
		if ( $num ) {
3348
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3349
		}
3350
3351
		return $custom_log_output;
3352
	}
3353
3354
	/**
3355
	 * Log modification of important settings.
3356
	 */
3357
	public static function log_settings_change( $option, $old_value, $value ) {
3358
		switch( $option ) {
3359
			case 'jetpack_sync_non_public_post_stati':
3360
				self::log( $option, $value );
3361
				break;
3362
		}
3363
	}
3364
3365
	/**
3366
	 * Return stat data for WPCOM sync
3367
	 */
3368
	public static function get_stat_data( $encode = true, $extended = true ) {
3369
		$data = Jetpack_Heartbeat::generate_stats_array();
3370
3371
		if ( $extended ) {
3372
			$additional_data = self::get_additional_stat_data();
3373
			$data = array_merge( $data, $additional_data );
3374
		}
3375
3376
		if ( $encode ) {
3377
			return json_encode( $data );
3378
		}
3379
3380
		return $data;
3381
	}
3382
3383
	/**
3384
	 * Get additional stat data to sync to WPCOM
3385
	 */
3386
	public static function get_additional_stat_data( $prefix = '' ) {
3387
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3388
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3389
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3390
		$return["{$prefix}site-count"]     = 0;
3391
3392
		if ( function_exists( 'get_blog_count' ) ) {
3393
			$return["{$prefix}site-count"] = get_blog_count();
3394
		}
3395
		return $return;
3396
	}
3397
3398
	private static function get_site_user_count() {
3399
		global $wpdb;
3400
3401
		if ( function_exists( 'wp_is_large_network' ) ) {
3402
			if ( wp_is_large_network( 'users' ) ) {
3403
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3404
			}
3405
		}
3406
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3407
			// It wasn't there, so regenerate the data and save the transient
3408
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3409
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3410
		}
3411
		return $user_count;
3412
	}
3413
3414
	/* Admin Pages */
3415
3416
	function admin_init() {
3417
		// If the plugin is not connected, display a connect message.
3418
		if (
3419
			// the plugin was auto-activated and needs its candy
3420
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3421
		||
3422
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3423
			! Jetpack_Options::get_option( 'activated' )
3424
		) {
3425
			Jetpack::plugin_initialize();
3426
		}
3427
3428
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3429
			Jetpack_Connection_Banner::init();
3430
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3431
			// Upgrade: 1.1 -> 1.1.1
3432
			// Check and see if host can verify the Jetpack servers' SSL certificate
3433
			$args = array();
3434
			$connection = self::connection();
3435
			Client::_wp_remote_request(
3436
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3437
				$args,
3438
				true
3439
			);
3440
		}
3441
3442
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3443
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3444
		}
3445
3446
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3447
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3448
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3449
3450
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3451
			// Artificially throw errors in certain whitelisted cases during plugin activation
3452
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3453
		}
3454
3455
		// Add custom column in wp-admin/users.php to show whether user is linked.
3456
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3457
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3458
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3459
	}
3460
3461
	function admin_body_class( $admin_body_class = '' ) {
3462
		$classes = explode( ' ', trim( $admin_body_class ) );
3463
3464
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3465
3466
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3467
		return " $admin_body_class ";
3468
	}
3469
3470
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3471
		return $admin_body_class . ' jetpack-pagestyles ';
3472
	}
3473
3474
	/**
3475
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3476
	 * This function artificially throws errors for such cases (whitelisted).
3477
	 *
3478
	 * @param string $plugin The activated plugin.
3479
	 */
3480
	function throw_error_on_activate_plugin( $plugin ) {
3481
		$active_modules = Jetpack::get_active_modules();
3482
3483
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3484
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3485
			$throw = false;
3486
3487
			// Try and make sure it really was the stats plugin
3488
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3489
				if ( 'stats.php' == basename( $plugin ) ) {
3490
					$throw = true;
3491
				}
3492
			} else {
3493
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3494
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3495
					$throw = true;
3496
				}
3497
			}
3498
3499
			if ( $throw ) {
3500
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3501
			}
3502
		}
3503
	}
3504
3505
	function intercept_plugin_error_scrape_init() {
3506
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3507
	}
3508
3509
	function intercept_plugin_error_scrape( $action, $result ) {
3510
		if ( ! $result ) {
3511
			return;
3512
		}
3513
3514
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3515
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3516
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3517
			}
3518
		}
3519
	}
3520
3521
	function add_remote_request_handlers() {
3522
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3523
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3524
	}
3525
3526
	function remote_request_handlers() {
3527
		$action = current_filter();
3528
3529
		switch ( current_filter() ) {
3530
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3531
			$response = $this->upload_handler();
3532
			break;
3533
3534
		case 'wp_ajax_nopriv_jetpack_update_file' :
3535
			$response = $this->upload_handler( true );
3536
			break;
3537
		default :
3538
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3539
			break;
3540
		}
3541
3542
		if ( ! $response ) {
3543
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3544
		}
3545
3546
		if ( is_wp_error( $response ) ) {
3547
			$status_code       = $response->get_error_data();
3548
			$error             = $response->get_error_code();
3549
			$error_description = $response->get_error_message();
3550
3551
			if ( ! is_int( $status_code ) ) {
3552
				$status_code = 400;
3553
			}
3554
3555
			status_header( $status_code );
3556
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3557
		}
3558
3559
		status_header( 200 );
3560
		if ( true === $response ) {
3561
			exit;
3562
		}
3563
3564
		die( json_encode( (object) $response ) );
3565
	}
3566
3567
	/**
3568
	 * Uploads a file gotten from the global $_FILES.
3569
	 * If `$update_media_item` is true and `post_id` is defined
3570
	 * the attachment file of the media item (gotten through of the post_id)
3571
	 * will be updated instead of add a new one.
3572
	 *
3573
	 * @param  boolean $update_media_item - update media attachment
3574
	 * @return array - An array describing the uploadind files process
3575
	 */
3576
	function upload_handler( $update_media_item = false ) {
3577
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3578
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3579
		}
3580
3581
		$user = wp_authenticate( '', '' );
3582
		if ( ! $user || is_wp_error( $user ) ) {
3583
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3584
		}
3585
3586
		wp_set_current_user( $user->ID );
3587
3588
		if ( ! current_user_can( 'upload_files' ) ) {
3589
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3590
		}
3591
3592
		if ( empty( $_FILES ) ) {
3593
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3594
		}
3595
3596
		foreach ( array_keys( $_FILES ) as $files_key ) {
3597
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3598
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3599
			}
3600
		}
3601
3602
		$media_keys = array_keys( $_FILES['media'] );
3603
3604
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3605
		if ( ! $token || is_wp_error( $token ) ) {
3606
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3607
		}
3608
3609
		$uploaded_files = array();
3610
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3611
		unset( $GLOBALS['post'] );
3612
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3613
			$file = array();
3614
			foreach ( $media_keys as $media_key ) {
3615
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3616
			}
3617
3618
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3619
3620
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3621
			if ( $hmac_provided !== $hmac_file ) {
3622
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3623
				continue;
3624
			}
3625
3626
			$_FILES['.jetpack.upload.'] = $file;
3627
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3628
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3629
				$post_id = 0;
3630
			}
3631
3632
			if ( $update_media_item ) {
3633
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3634
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3635
				}
3636
3637
				$media_array = $_FILES['media'];
3638
3639
				$file_array['name'] = $media_array['name'][0];
3640
				$file_array['type'] = $media_array['type'][0];
3641
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3642
				$file_array['error'] = $media_array['error'][0];
3643
				$file_array['size'] = $media_array['size'][0];
3644
3645
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3646
3647
				if ( is_wp_error( $edited_media_item ) ) {
3648
					return $edited_media_item;
3649
				}
3650
3651
				$response = (object) array(
3652
					'id'   => (string) $post_id,
3653
					'file' => (string) $edited_media_item->post_title,
3654
					'url'  => (string) wp_get_attachment_url( $post_id ),
3655
					'type' => (string) $edited_media_item->post_mime_type,
3656
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3657
				);
3658
3659
				return (array) array( $response );
3660
			}
3661
3662
			$attachment_id = media_handle_upload(
3663
				'.jetpack.upload.',
3664
				$post_id,
3665
				array(),
3666
				array(
3667
					'action' => 'jetpack_upload_file',
3668
				)
3669
			);
3670
3671
			if ( ! $attachment_id ) {
3672
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3673
			} elseif ( is_wp_error( $attachment_id ) ) {
3674
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3675
			} else {
3676
				$attachment = get_post( $attachment_id );
3677
				$uploaded_files[$index] = (object) array(
3678
					'id'   => (string) $attachment_id,
3679
					'file' => $attachment->post_title,
3680
					'url'  => wp_get_attachment_url( $attachment_id ),
3681
					'type' => $attachment->post_mime_type,
3682
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3683
				);
3684
				// Zip files uploads are not supported unless they are done for installation purposed
3685
				// lets delete them in case something goes wrong in this whole process
3686
				if ( 'application/zip' === $attachment->post_mime_type ) {
3687
					// Schedule a cleanup for 2 hours from now in case of failed install.
3688
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3689
				}
3690
			}
3691
		}
3692
		if ( ! is_null( $global_post ) ) {
3693
			$GLOBALS['post'] = $global_post;
3694
		}
3695
3696
		return $uploaded_files;
3697
	}
3698
3699
	/**
3700
	 * Add help to the Jetpack page
3701
	 *
3702
	 * @since Jetpack (1.2.3)
3703
	 * @return false if not the Jetpack page
3704
	 */
3705
	function admin_help() {
3706
		$current_screen = get_current_screen();
3707
3708
		// Overview
3709
		$current_screen->add_help_tab(
3710
			array(
3711
				'id'		=> 'home',
3712
				'title'		=> __( 'Home', 'jetpack' ),
3713
				'content'	=>
3714
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3715
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3716
					'<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>',
3717
			)
3718
		);
3719
3720
		// Screen Content
3721
		if ( current_user_can( 'manage_options' ) ) {
3722
			$current_screen->add_help_tab(
3723
				array(
3724
					'id'		=> 'settings',
3725
					'title'		=> __( 'Settings', 'jetpack' ),
3726
					'content'	=>
3727
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3728
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3729
						'<ol>' .
3730
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3731
							'<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>' .
3732
						'</ol>' .
3733
						'<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>'
3734
				)
3735
			);
3736
		}
3737
3738
		// Help Sidebar
3739
		$current_screen->set_help_sidebar(
3740
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3741
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3742
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3743
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3744
		);
3745
	}
3746
3747
	function admin_menu_css() {
3748
		wp_enqueue_style( 'jetpack-icons' );
3749
	}
3750
3751
	function admin_menu_order() {
3752
		return true;
3753
	}
3754
3755 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3756
		$jp_menu_order = array();
3757
3758
		foreach ( $menu_order as $index => $item ) {
3759
			if ( $item != 'jetpack' ) {
3760
				$jp_menu_order[] = $item;
3761
			}
3762
3763
			if ( $index == 0 ) {
3764
				$jp_menu_order[] = 'jetpack';
3765
			}
3766
		}
3767
3768
		return $jp_menu_order;
3769
	}
3770
3771
	function admin_banner_styles() {
3772
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3773
3774
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3775
			wp_register_style(
3776
				'jetpack-dops-style',
3777
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3778
				array(),
3779
				JETPACK__VERSION
3780
			);
3781
		}
3782
3783
		wp_enqueue_style(
3784
			'jetpack',
3785
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3786
			array( 'jetpack-dops-style' ),
3787
			 JETPACK__VERSION . '-20121016'
3788
		);
3789
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3790
		wp_style_add_data( 'jetpack', 'suffix', $min );
3791
	}
3792
3793
	function plugin_action_links( $actions ) {
3794
3795
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3796
3797
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3798
			return array_merge(
3799
				$jetpack_home,
3800
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3801
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3802
				$actions
3803
				);
3804
			}
3805
3806
		return array_merge( $jetpack_home, $actions );
3807
	}
3808
3809
	/*
3810
	 * Registration flow:
3811
	 * 1 - ::admin_page_load() action=register
3812
	 * 2 - ::try_registration()
3813
	 * 3 - ::register()
3814
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3815
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3816
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3817
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3818
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3819
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3820
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3821
	 *       jetpack_id, jetpack_secret, jetpack_public
3822
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3823
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3824
	 * 5 - user logs in with WP.com account
3825
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3826
	 *		- Jetpack_Client_Server::authorize()
3827
	 *		- Jetpack_Client_Server::get_token()
3828
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3829
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3830
	 *			- which responds with access_token, token_type, scope
3831
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3832
	 *		- Jetpack::activate_default_modules()
3833
	 *     		- Deactivates deprecated plugins
3834
	 *     		- Activates all default modules
3835
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3836
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3837
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3838
	 *     Done!
3839
	 */
3840
3841
	/**
3842
	 * Handles the page load events for the Jetpack admin page
3843
	 */
3844
	function admin_page_load() {
3845
		$error = false;
3846
3847
		// Make sure we have the right body class to hook stylings for subpages off of.
3848
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3849
3850
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3851
			// Should only be used in intermediate redirects to preserve state across redirects
3852
			Jetpack::restate();
3853
		}
3854
3855
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3856
			// @todo: Add validation against a known whitelist
3857
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3858
			// User clicked in the iframe to link their accounts
3859
			if ( ! Jetpack::is_user_connected() ) {
3860
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3861
3862
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3863
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3864
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3865
3866
				if ( isset( $_GET['notes_iframe'] ) )
3867
					$connect_url .= '&notes_iframe';
3868
				wp_redirect( $connect_url );
3869
				exit;
3870
			} else {
3871
				if ( ! isset( $_GET['calypso_env'] ) ) {
3872
					Jetpack::state( 'message', 'already_authorized' );
3873
					wp_safe_redirect( Jetpack::admin_url() );
3874
					exit;
3875
				} else {
3876
					$connect_url = $this->build_connect_url( true, false, $from );
3877
					$connect_url .= '&already_authorized=true';
3878
					wp_redirect( $connect_url );
3879
					exit;
3880
				}
3881
			}
3882
		}
3883
3884
3885
		if ( isset( $_GET['action'] ) ) {
3886
			switch ( $_GET['action'] ) {
3887
			case 'authorize':
3888
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3889
					Jetpack::state( 'message', 'already_authorized' );
3890
					wp_safe_redirect( Jetpack::admin_url() );
3891
					exit;
3892
				}
3893
				Jetpack::log( 'authorize' );
3894
				$client_server = new Jetpack_Client_Server;
3895
				$client_server->client_authorize();
3896
				exit;
3897
			case 'register' :
3898
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3899
					$error = 'cheatin';
3900
					break;
3901
				}
3902
				check_admin_referer( 'jetpack-register' );
3903
				Jetpack::log( 'register' );
3904
				Jetpack::maybe_set_version_option();
3905
				$registered = Jetpack::try_registration();
3906
				if ( is_wp_error( $registered ) ) {
3907
					$error = $registered->get_error_code();
3908
					Jetpack::state( 'error', $error );
3909
					Jetpack::state( 'error', $registered->get_error_message() );
3910
3911
					/**
3912
					 * Jetpack registration Error.
3913
					 *
3914
					 * @since 7.5.0
3915
					 *
3916
					 * @param string|int $error The error code.
3917
					 * @param \WP_Error $registered The error object.
3918
					 */
3919
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3920
					break;
3921
				}
3922
3923
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3924
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3925
3926
				/**
3927
				 * Jetpack registration Success.
3928
				 *
3929
				 * @since 7.5.0
3930
				 *
3931
				 * @param string $from 'from' GET parameter;
3932
				 */
3933
				do_action( 'jetpack_connection_register_success', $from );
3934
3935
				$url = $this->build_connect_url( true, $redirect, $from );
3936
3937
				if ( ! empty( $_GET['onboarding'] ) ) {
3938
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3939
				}
3940
3941
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3942
					$url = add_query_arg( 'auth_approved', 'true', $url );
3943
				}
3944
3945
				wp_redirect( $url );
3946
				exit;
3947
			case 'activate' :
3948
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3949
					$error = 'cheatin';
3950
					break;
3951
				}
3952
3953
				$module = stripslashes( $_GET['module'] );
3954
				check_admin_referer( "jetpack_activate-$module" );
3955
				Jetpack::log( 'activate', $module );
3956
				if ( ! Jetpack::activate_module( $module ) ) {
3957
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
3958
				}
3959
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3960
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3961
				exit;
3962
			case 'activate_default_modules' :
3963
				check_admin_referer( 'activate_default_modules' );
3964
				Jetpack::log( 'activate_default_modules' );
3965
				Jetpack::restate();
3966
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3967
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3968
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3969
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3970
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3971
				exit;
3972
			case 'disconnect' :
3973
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3974
					$error = 'cheatin';
3975
					break;
3976
				}
3977
3978
				check_admin_referer( 'jetpack-disconnect' );
3979
				Jetpack::log( 'disconnect' );
3980
				Jetpack::disconnect();
3981
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3982
				exit;
3983
			case 'reconnect' :
3984
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3985
					$error = 'cheatin';
3986
					break;
3987
				}
3988
3989
				check_admin_referer( 'jetpack-reconnect' );
3990
				Jetpack::log( 'reconnect' );
3991
				$this->disconnect();
3992
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3993
				exit;
3994 View Code Duplication
			case 'deactivate' :
3995
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3996
					$error = 'cheatin';
3997
					break;
3998
				}
3999
4000
				$modules = stripslashes( $_GET['module'] );
4001
				check_admin_referer( "jetpack_deactivate-$modules" );
4002
				foreach ( explode( ',', $modules ) as $module ) {
4003
					Jetpack::log( 'deactivate', $module );
4004
					Jetpack::deactivate_module( $module );
4005
					Jetpack::state( 'message', 'module_deactivated' );
4006
				}
4007
				Jetpack::state( 'module', $modules );
4008
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4009
				exit;
4010
			case 'unlink' :
4011
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4012
				check_admin_referer( 'jetpack-unlink' );
4013
				Jetpack::log( 'unlink' );
4014
				$this->unlink_user();
4015
				Jetpack::state( 'message', 'unlinked' );
4016
				if ( 'sub-unlink' == $redirect ) {
4017
					wp_safe_redirect( admin_url() );
4018
				} else {
4019
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4020
				}
4021
				exit;
4022
			case 'onboard' :
4023
				if ( ! current_user_can( 'manage_options' ) ) {
4024
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4025
				} else {
4026
					Jetpack::create_onboarding_token();
4027
					$url = $this->build_connect_url( true );
4028
4029
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4030
						$url = add_query_arg( 'onboarding', $token, $url );
4031
					}
4032
4033
					$calypso_env = $this->get_calypso_env();
4034
					if ( ! empty( $calypso_env ) ) {
4035
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4036
					}
4037
4038
					wp_redirect( $url );
4039
					exit;
4040
				}
4041
				exit;
4042
			default:
4043
				/**
4044
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4045
				 *
4046
				 * @since 2.6.0
4047
				 *
4048
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4049
				 */
4050
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4051
			}
4052
		}
4053
4054
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4055
			self::activate_new_modules( true );
4056
		}
4057
4058
		$message_code = Jetpack::state( 'message' );
4059
		if ( Jetpack::state( 'optin-manage' ) ) {
4060
			$activated_manage = $message_code;
4061
			$message_code = 'jetpack-manage';
4062
		}
4063
4064
		switch ( $message_code ) {
4065
		case 'jetpack-manage':
4066
			$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>';
4067
			if ( $activated_manage ) {
4068
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4069
			}
4070
			break;
4071
4072
		}
4073
4074
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4075
4076
		if ( ! empty( $deactivated_plugins ) ) {
4077
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4078
			$deactivated_titles  = array();
4079
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4080
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4081
					continue;
4082
				}
4083
4084
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4085
			}
4086
4087
			if ( $deactivated_titles ) {
4088
				if ( $this->message ) {
4089
					$this->message .= "<br /><br />\n";
4090
				}
4091
4092
				$this->message .= wp_sprintf(
4093
					_n(
4094
						'Jetpack contains the most recent version of the old %l plugin.',
4095
						'Jetpack contains the most recent versions of the old %l plugins.',
4096
						count( $deactivated_titles ),
4097
						'jetpack'
4098
					),
4099
					$deactivated_titles
4100
				);
4101
4102
				$this->message .= "<br />\n";
4103
4104
				$this->message .= _n(
4105
					'The old version has been deactivated and can be removed from your site.',
4106
					'The old versions have been deactivated and can be removed from your site.',
4107
					count( $deactivated_titles ),
4108
					'jetpack'
4109
				);
4110
			}
4111
		}
4112
4113
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4114
4115
		if ( $this->message || $this->error || $this->privacy_checks ) {
4116
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4117
		}
4118
4119
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4120
	}
4121
4122
	function admin_notices() {
4123
4124
		if ( $this->error ) {
4125
?>
4126
<div id="message" class="jetpack-message jetpack-err">
4127
	<div class="squeezer">
4128
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4129
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4130
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4131
<?php	endif; ?>
4132
	</div>
4133
</div>
4134
<?php
4135
		}
4136
4137
		if ( $this->message ) {
4138
?>
4139
<div id="message" class="jetpack-message">
4140
	<div class="squeezer">
4141
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4142
	</div>
4143
</div>
4144
<?php
4145
		}
4146
4147
		if ( $this->privacy_checks ) :
4148
			$module_names = $module_slugs = array();
4149
4150
			$privacy_checks = explode( ',', $this->privacy_checks );
4151
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4152
			foreach ( $privacy_checks as $module_slug ) {
4153
				$module = Jetpack::get_module( $module_slug );
4154
				if ( ! $module ) {
4155
					continue;
4156
				}
4157
4158
				$module_slugs[] = $module_slug;
4159
				$module_names[] = "<strong>{$module['name']}</strong>";
4160
			}
4161
4162
			$module_slugs = join( ',', $module_slugs );
4163
?>
4164
<div id="message" class="jetpack-message jetpack-err">
4165
	<div class="squeezer">
4166
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4167
		<p><?php
4168
			echo wp_kses(
4169
				wptexturize(
4170
					wp_sprintf(
4171
						_nx(
4172
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4173
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4174
							count( $privacy_checks ),
4175
							'%l = list of Jetpack module/feature names',
4176
							'jetpack'
4177
						),
4178
						$module_names
4179
					)
4180
				),
4181
				array( 'strong' => true )
4182
			);
4183
4184
			echo "\n<br />\n";
4185
4186
			echo wp_kses(
4187
				sprintf(
4188
					_nx(
4189
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4190
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4191
						count( $privacy_checks ),
4192
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4193
						'jetpack'
4194
					),
4195
					wp_nonce_url(
4196
						Jetpack::admin_url(
4197
							array(
4198
								'page'   => 'jetpack',
4199
								'action' => 'deactivate',
4200
								'module' => urlencode( $module_slugs ),
4201
							)
4202
						),
4203
						"jetpack_deactivate-$module_slugs"
4204
					),
4205
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4206
				),
4207
				array( 'a' => array( 'href' => true, 'title' => true ) )
4208
			);
4209
		?></p>
4210
	</div>
4211
</div>
4212
<?php endif;
4213
	}
4214
4215
	/**
4216
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4217
	 */
4218
	function stat( $group, $detail ) {
4219
		if ( ! isset( $this->stats[ $group ] ) )
4220
			$this->stats[ $group ] = array();
4221
		$this->stats[ $group ][] = $detail;
4222
	}
4223
4224
	/**
4225
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4226
	 */
4227
	function do_stats( $method = '' ) {
4228
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4229
			foreach ( $this->stats as $group => $stats ) {
4230
				if ( is_array( $stats ) && count( $stats ) ) {
4231
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4232
					if ( 'server_side' === $method ) {
4233
						self::do_server_side_stat( $args );
4234
					} else {
4235
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4236
					}
4237
				}
4238
				unset( $this->stats[ $group ] );
4239
			}
4240
		}
4241
	}
4242
4243
	/**
4244
	 * Runs stats code for a one-off, server-side.
4245
	 *
4246
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4247
	 *
4248
	 * @return bool If it worked.
4249
	 */
4250
	static function do_server_side_stat( $args ) {
4251
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4252
		if ( is_wp_error( $response ) )
4253
			return false;
4254
4255
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4256
			return false;
4257
4258
		return true;
4259
	}
4260
4261
	/**
4262
	 * Builds the stats url.
4263
	 *
4264
	 * @param $args array|string The arguments to append to the URL.
4265
	 *
4266
	 * @return string The URL to be pinged.
4267
	 */
4268
	static function build_stats_url( $args ) {
4269
		$defaults = array(
4270
			'v'    => 'wpcom2',
4271
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4272
		);
4273
		$args     = wp_parse_args( $args, $defaults );
4274
		/**
4275
		 * Filter the URL used as the Stats tracking pixel.
4276
		 *
4277
		 * @since 2.3.2
4278
		 *
4279
		 * @param string $url Base URL used as the Stats tracking pixel.
4280
		 */
4281
		$base_url = apply_filters(
4282
			'jetpack_stats_base_url',
4283
			'https://pixel.wp.com/g.gif'
4284
		);
4285
		$url      = add_query_arg( $args, $base_url );
4286
		return $url;
4287
	}
4288
4289
	/**
4290
	 * Get the role of the current user.
4291
	 *
4292
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4293
	 *
4294
	 * @access public
4295
	 * @static
4296
	 *
4297
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4298
	 */
4299
	public static function translate_current_user_to_role() {
4300
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4301
4302
		$roles = new Roles();
4303
		return $roles->translate_current_user_to_role();
4304
	}
4305
4306
	/**
4307
	 * Get the role of a particular user.
4308
	 *
4309
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4310
	 *
4311
	 * @access public
4312
	 * @static
4313
	 *
4314
	 * @param \WP_User $user User object.
4315
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4316
	 */
4317
	public static function translate_user_to_role( $user ) {
4318
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4319
4320
		$roles = new Roles();
4321
		return $roles->translate_user_to_role( $user );
4322
	}
4323
4324
	/**
4325
	 * Get the minimum capability for a role.
4326
	 *
4327
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4328
	 *
4329
	 * @access public
4330
	 * @static
4331
	 *
4332
	 * @param string $role Role name.
4333
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4334
	 */
4335
	public static function translate_role_to_cap( $role ) {
4336
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4337
4338
		$roles = new Roles();
4339
		return $roles->translate_role_to_cap( $role );
4340
	}
4341
4342
	static function sign_role( $role, $user_id = null ) {
4343
		if ( empty( $user_id ) ) {
4344
			$user_id = (int) get_current_user_id();
4345
		}
4346
4347
		if ( ! $user_id  ) {
4348
			return false;
4349
		}
4350
4351
		$token = Jetpack_Data::get_access_token();
4352
		if ( ! $token || is_wp_error( $token ) ) {
4353
			return false;
4354
		}
4355
4356
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4357
	}
4358
4359
4360
	/**
4361
	 * Builds a URL to the Jetpack connection auth page
4362
	 *
4363
	 * @since 3.9.5
4364
	 *
4365
	 * @param bool $raw If true, URL will not be escaped.
4366
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4367
	 *                              If string, will be a custom redirect.
4368
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4369
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4370
	 *
4371
	 * @return string Connect URL
4372
	 */
4373
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4374
		$site_id = Jetpack_Options::get_option( 'id' );
4375
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4376
4377
		if ( $register || ! $blog_token || ! $site_id ) {
4378
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4379
4380
			if ( ! empty( $redirect ) ) {
4381
				$url = add_query_arg(
4382
					'redirect',
4383
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4384
					$url
4385
				);
4386
			}
4387
4388
			if( is_network_admin() ) {
4389
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4390
			}
4391
		} else {
4392
4393
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4394
			// because otherwise this logic can get us in to a loop.
4395
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4396
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4397
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4398
4399
				$response = Client::wpcom_json_api_request_as_blog(
4400
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4401
					'1.1'
4402
				);
4403
4404
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4405
4406
					// Generating a register URL instead to refresh the existing token
4407
					return $this->build_connect_url( $raw, $redirect, $from, true );
4408
				}
4409
			}
4410
4411
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4412
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4413
			}
4414
4415
			$roles       = new Roles();
4416
			$role        = $roles->translate_current_user_to_role();
4417
			$signed_role = self::sign_role( $role );
4418
4419
			$user = wp_get_current_user();
4420
4421
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4422
			$redirect = $redirect
4423
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4424
				: $jetpack_admin_page;
4425
4426
			if( isset( $_REQUEST['is_multisite'] ) ) {
4427
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4428
			}
4429
4430
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4431
4432
			/**
4433
			 * Filter the type of authorization.
4434
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4435
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4436
			 *
4437
			 * @since 4.3.3
4438
			 *
4439
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4440
			 */
4441
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4442
4443
4444
			$tracks = new Tracking();
4445
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4446
4447
			$args = urlencode_deep(
4448
				array(
4449
					'response_type' => 'code',
4450
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4451
					'redirect_uri'  => add_query_arg(
4452
						array(
4453
							'action'   => 'authorize',
4454
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4455
							'redirect' => urlencode( $redirect ),
4456
						),
4457
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4458
					),
4459
					'state'         => $user->ID,
4460
					'scope'         => $signed_role,
4461
					'user_email'    => $user->user_email,
4462
					'user_login'    => $user->user_login,
4463
					'is_active'     => Jetpack::is_active(),
4464
					'jp_version'    => JETPACK__VERSION,
4465
					'auth_type'     => $auth_type,
4466
					'secret'        => $secrets['secret_1'],
4467
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4468
					'blogname'      => get_option( 'blogname' ),
4469
					'site_url'      => site_url(),
4470
					'home_url'      => home_url(),
4471
					'site_icon'     => get_site_icon_url(),
4472
					'site_lang'     => get_locale(),
4473
					'_ui'           => $tracks_identity['_ui'],
4474
					'_ut'           => $tracks_identity['_ut'],
4475
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4476
				)
4477
			);
4478
4479
			self::apply_activation_source_to_args( $args );
4480
4481
			$connection = self::connection();
4482
			$url = add_query_arg( $args, $connection->api_url( 'authorize' ) );
4483
		}
4484
4485
		if ( $from ) {
4486
			$url = add_query_arg( 'from', $from, $url );
4487
		}
4488
4489
		// Ensure that class to get the affiliate code is loaded
4490
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4491
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4492
		}
4493
		// Get affiliate code and add it to the URL
4494
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4495
4496
		$calypso_env = $this->get_calypso_env();
4497
4498
		if ( ! empty( $calypso_env ) ) {
4499
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4500
		}
4501
4502
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4503
	}
4504
4505
	/**
4506
	 * Get our assumed site creation date.
4507
	 * Calculated based on the earlier date of either:
4508
	 * - Earliest admin user registration date.
4509
	 * - Earliest date of post of any post type.
4510
	 *
4511
	 * @since 7.2.0
4512
	 *
4513
	 * @return string Assumed site creation date and time.
4514
	 */
4515 View Code Duplication
	public static function get_assumed_site_creation_date() {
4516
		$earliest_registered_users = get_users( array(
4517
			'role'    => 'administrator',
4518
			'orderby' => 'user_registered',
4519
			'order'   => 'ASC',
4520
			'fields'  => array( 'user_registered' ),
4521
			'number'  => 1,
4522
		) );
4523
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4524
4525
		$earliest_posts = get_posts( array(
4526
			'posts_per_page' => 1,
4527
			'post_type'      => 'any',
4528
			'post_status'    => 'any',
4529
			'orderby'        => 'date',
4530
			'order'          => 'ASC',
4531
		) );
4532
4533
		// If there are no posts at all, we'll count only on user registration date.
4534
		if ( $earliest_posts ) {
4535
			$earliest_post_date = $earliest_posts[0]->post_date;
4536
		} else {
4537
			$earliest_post_date = PHP_INT_MAX;
4538
		}
4539
4540
		return min( $earliest_registration_date, $earliest_post_date );
4541
	}
4542
4543 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4544
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4545
4546
		if ( $activation_source_name ) {
4547
			$args['_as'] = urlencode( $activation_source_name );
4548
		}
4549
4550
		if ( $activation_source_keyword ) {
4551
			$args['_ak'] = urlencode( $activation_source_keyword );
4552
		}
4553
	}
4554
4555
	function build_reconnect_url( $raw = false ) {
4556
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4557
		return $raw ? $url : esc_url( $url );
4558
	}
4559
4560
	public static function admin_url( $args = null ) {
4561
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4562
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4563
		return $url;
4564
	}
4565
4566
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4567
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4568
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4569
	}
4570
4571
	function dismiss_jetpack_notice() {
4572
4573
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4574
			return;
4575
		}
4576
4577
		switch( $_GET['jetpack-notice'] ) {
4578
			case 'dismiss':
4579
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4580
4581
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4582
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4583
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4584
				}
4585
				break;
4586
			case 'jetpack-protect-multisite-opt-out':
4587
4588
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4589
					// Don't show the banner again
4590
4591
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4592
					// redirect back to the page that had the notice
4593
					if ( wp_get_referer() ) {
4594
						wp_safe_redirect( wp_get_referer() );
4595
					} else {
4596
						// Take me to Jetpack
4597
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4598
					}
4599
				}
4600
				break;
4601
		}
4602
	}
4603
4604
	public static function sort_modules( $a, $b ) {
4605
		if ( $a['sort'] == $b['sort'] )
4606
			return 0;
4607
4608
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4609
	}
4610
4611
	function ajax_recheck_ssl() {
4612
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4613
		$result = Jetpack::permit_ssl( true );
4614
		wp_send_json( array(
4615
			'enabled' => $result,
4616
			'message' => get_transient( 'jetpack_https_test_message' )
4617
		) );
4618
	}
4619
4620
/* Client API */
4621
4622
	/**
4623
	 * Returns the requested Jetpack API URL
4624
	 *
4625
	 * @deprecated since 7.6
4626
	 * @return string
4627
	 */
4628
	public static function api_url( $relative_url ) {
4629
		_deprecated_function( __METHOD__, 'jetpack-7.6', '\\Automattic\\Jetpack\\Connection\\Manager::api_url' );
4630
		$connection = self::connection();
4631
		return $connection->api_url( $relative_url );
4632
	}
4633
4634
	/**
4635
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4636
	 */
4637
	public static function fix_url_for_bad_hosts( $url ) {
4638
		if ( 0 !== strpos( $url, 'https://' ) ) {
4639
			return $url;
4640
		}
4641
4642
		switch ( JETPACK_CLIENT__HTTPS ) {
4643
			case 'ALWAYS' :
4644
				return $url;
4645
			case 'NEVER' :
4646
				return set_url_scheme( $url, 'http' );
4647
			// default : case 'AUTO' :
4648
		}
4649
4650
		// we now return the unmodified SSL URL by default, as a security precaution
4651
		return $url;
4652
	}
4653
4654
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4655
		// Default to a blog token.
4656
		$token_type = 'blog';
4657
4658
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4659
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4660
			if ( ! empty( $_GET['onboarding'] ) ) {
4661
				$jpo = $_GET;
4662
			} else {
4663
				$jpo = json_decode( $request_data, true );
4664
			}
4665
4666
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4667
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4668
4669
			if (
4670
				isset( $jpo_user )
4671
				&& isset( $jpo_token )
4672
				&& is_email( $jpo_user )
4673
				&& ctype_alnum( $jpo_token )
4674
				&& isset( $_GET['rest_route'] )
4675
				&& self::validate_onboarding_token_action(
4676
					$jpo_token,
4677
					$_GET['rest_route']
4678
				)
4679
			) {
4680
				$jpUser = get_user_by( 'email', $jpo_user );
4681
				if ( is_a( $jpUser, 'WP_User' ) ) {
4682
					wp_set_current_user( $jpUser->ID );
4683
					$user_can = is_multisite()
4684
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4685
						: current_user_can( 'manage_options' );
4686
					if ( $user_can ) {
4687
						$token_type = 'user';
4688
						$token->external_user_id = $jpUser->ID;
4689
					}
4690
				}
4691
			}
4692
4693
			$token_data['type']    = $token_type;
4694
			$token_data['user_id'] = $token->external_user_id;
4695
		}
4696
4697
		return $token_data;
4698
	}
4699
4700
	/**
4701
	 * Create a random secret for validating onboarding payload
4702
	 *
4703
	 * @return string Secret token
4704
	 */
4705
	public static function create_onboarding_token() {
4706
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4707
			$token = wp_generate_password( 32, false );
4708
			Jetpack_Options::update_option( 'onboarding', $token );
4709
		}
4710
4711
		return $token;
4712
	}
4713
4714
	/**
4715
	 * Remove the onboarding token
4716
	 *
4717
	 * @return bool True on success, false on failure
4718
	 */
4719
	public static function invalidate_onboarding_token() {
4720
		return Jetpack_Options::delete_option( 'onboarding' );
4721
	}
4722
4723
	/**
4724
	 * Validate an onboarding token for a specific action
4725
	 *
4726
	 * @return boolean True if token/action pair is accepted, false if not
4727
	 */
4728
	public static function validate_onboarding_token_action( $token, $action ) {
4729
		// Compare tokens, bail if tokens do not match
4730
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4731
			return false;
4732
		}
4733
4734
		// List of valid actions we can take
4735
		$valid_actions = array(
4736
			'/jetpack/v4/settings',
4737
		);
4738
4739
		// Whitelist the action
4740
		if ( ! in_array( $action, $valid_actions ) ) {
4741
			return false;
4742
		}
4743
4744
		return true;
4745
	}
4746
4747
	/**
4748
	 * Checks to see if the URL is using SSL to connect with Jetpack
4749
	 *
4750
	 * @since 2.3.3
4751
	 * @return boolean
4752
	 */
4753
	public static function permit_ssl( $force_recheck = false ) {
4754
		// Do some fancy tests to see if ssl is being supported
4755
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4756
			$message = '';
4757
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4758
				$ssl = 0;
4759
			} else {
4760
				switch ( JETPACK_CLIENT__HTTPS ) {
4761
					case 'NEVER':
4762
						$ssl = 0;
4763
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4764
						break;
4765
					case 'ALWAYS':
4766
					case 'AUTO':
4767
					default:
4768
						$ssl = 1;
4769
						break;
4770
				}
4771
4772
				// If it's not 'NEVER', test to see
4773
				if ( $ssl ) {
4774
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4775
						$ssl = 0;
4776
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4777
					} else {
4778
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4779
						if ( is_wp_error( $response ) ) {
4780
							$ssl = 0;
4781
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4782
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4783
							$ssl = 0;
4784
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4785
						}
4786
					}
4787
				}
4788
			}
4789
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4790
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4791
		}
4792
4793
		return (bool) $ssl;
4794
	}
4795
4796
	/*
4797
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4798
	 */
4799
	public function alert_auto_ssl_fail() {
4800
		if ( ! current_user_can( 'manage_options' ) )
4801
			return;
4802
4803
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4804
		?>
4805
4806
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4807
			<div class="jp-banner__content">
4808
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4809
				<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>
4810
				<p>
4811
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4812
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4813
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4814
				</p>
4815
				<p>
4816
					<?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4817
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4818
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4819
				</p>
4820
			</div>
4821
		</div>
4822
		<style>
4823
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4824
		</style>
4825
		<script type="text/javascript">
4826
			jQuery( document ).ready( function( $ ) {
4827
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4828
					var $this = $( this );
4829
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4830
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4831
					e.preventDefault();
4832
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4833
					$.post( ajaxurl, data )
4834
					  .done( function( response ) {
4835
					  	if ( response.enabled ) {
4836
					  		$( '#jetpack-ssl-warning' ).hide();
4837
					  	} else {
4838
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4839
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4840
					  	}
4841
					  }.bind( $this ) );
4842
				} );
4843
			} );
4844
		</script>
4845
4846
		<?php
4847
	}
4848
4849
	/**
4850
	 * Returns the Jetpack XML-RPC API
4851
	 *
4852
	 * @return string
4853
	 */
4854
	public static function xmlrpc_api_url() {
4855
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4856
		return untrailingslashit( $base ) . '/xmlrpc.php';
4857
	}
4858
4859
	public static function connection() {
4860
		return self::init()->connection_manager;
4861
	}
4862
4863
	/**
4864
	 * Creates two secret tokens and the end of life timestamp for them.
4865
	 *
4866
	 * Note these tokens are unique per call, NOT static per site for connecting.
4867
	 *
4868
	 * @since 2.6
4869
	 * @return array
4870
	 */
4871
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4872
		if ( false === $user_id ) {
4873
			$user_id = get_current_user_id();
4874
		}
4875
4876
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4877
	}
4878
4879
	public static function get_secrets( $action, $user_id ) {
4880
		$secrets = self::connection()->get_secrets( $action, $user_id );
4881
4882
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4883
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4884
		}
4885
4886
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4887
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4888
		}
4889
4890
		return $secrets;
4891
	}
4892
4893
	/**
4894
	 * @deprecated 7.5 Use Connection_Manager instead.
4895
	 *
4896
	 * @param $action
4897
	 * @param $user_id
4898
	 */
4899
	public static function delete_secrets( $action, $user_id ) {
4900
		return self::connection()->delete_secrets( $action, $user_id );
4901
	}
4902
4903
	/**
4904
	 * Builds the timeout limit for queries talking with the wpcom servers.
4905
	 *
4906
	 * Based on local php max_execution_time in php.ini
4907
	 *
4908
	 * @since 2.6
4909
	 * @return int
4910
	 * @deprecated
4911
	 **/
4912
	public function get_remote_query_timeout_limit() {
4913
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4914
		return Jetpack::get_max_execution_time();
4915
	}
4916
4917
	/**
4918
	 * Builds the timeout limit for queries talking with the wpcom servers.
4919
	 *
4920
	 * Based on local php max_execution_time in php.ini
4921
	 *
4922
	 * @since 5.4
4923
	 * @return int
4924
	 **/
4925
	public static function get_max_execution_time() {
4926
		$timeout = (int) ini_get( 'max_execution_time' );
4927
4928
		// Ensure exec time set in php.ini
4929
		if ( ! $timeout ) {
4930
			$timeout = 30;
4931
		}
4932
		return $timeout;
4933
	}
4934
4935
	/**
4936
	 * Sets a minimum request timeout, and returns the current timeout
4937
	 *
4938
	 * @since 5.4
4939
	 **/
4940 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
4941
		$timeout = self::get_max_execution_time();
4942
		if ( $timeout < $min_timeout ) {
4943
			$timeout = $min_timeout;
4944
			set_time_limit( $timeout );
4945
		}
4946
		return $timeout;
4947
	}
4948
4949
	/**
4950
	 * @return bool|WP_Error
4951
	 */
4952
	public static function register() {
4953
		$tracking = new Tracking();
4954
		$tracking->record_user_event( 'jpc_register_begin' );
4955
4956
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
4957
4958
		$connection = self::connection();
4959
		$registration = $connection->register();
4960
4961
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
4962
4963
		if ( ! $registration || is_wp_error( $registration ) ) {
4964
			return $registration;
4965
		}
4966
4967
		return true;
4968
	}
4969
4970
	/**
4971
	 * Filters the registration request body to include tracking properties.
4972
	 *
4973
	 * @param Array $properties
4974
	 * @return Array amended properties.
4975
	 */
4976
	public static function filter_register_request_body( $properties ) {
4977
		$tracking = new Tracking();
4978
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
4979
4980
		return array_merge(
4981
			$properties,
4982
			array(
4983
				'_ui' => $tracks_identity['_ui'],
4984
				'_ut' => $tracks_identity['_ut'],
4985
			)
4986
		);
4987
	}
4988
4989
	/**
4990
	 * If the db version is showing something other that what we've got now, bump it to current.
4991
	 *
4992
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4993
	 */
4994
	public static function maybe_set_version_option() {
4995
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4996
		if ( JETPACK__VERSION != $version ) {
4997
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4998
4999
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5000
				/** This action is documented in class.jetpack.php */
5001
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5002
			}
5003
5004
			return true;
5005
		}
5006
		return false;
5007
	}
5008
5009
/* Client Server API */
5010
5011
	/**
5012
	 * Loads the Jetpack XML-RPC client
5013
	 */
5014
	public static function load_xml_rpc_client() {
5015
		require_once ABSPATH . WPINC . '/class-IXR.php';
5016
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5017
	}
5018
5019
	/**
5020
	 * Resets the saved authentication state in between testing requests.
5021
	 */
5022
	public function reset_saved_auth_state() {
5023
		$this->rest_authentication_status = null;
5024
		$this->connection_manager->reset_saved_auth_state();
5025
	}
5026
5027
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5028
	// Uses the existing XMLRPC request signing implementation.
5029
	function wp_rest_authenticate( $user ) {
5030
		if ( ! empty( $user ) ) {
5031
			// Another authentication method is in effect.
5032
			return $user;
5033
		}
5034
5035
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5036
			// Nothing to do for this authentication method.
5037
			return null;
5038
		}
5039
5040
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5041
			// Nothing to do for this authentication method.
5042
			return null;
5043
		}
5044
5045
		// Ensure that we always have the request body available.  At this
5046
		// point, the WP REST API code to determine the request body has not
5047
		// run yet.  That code may try to read from 'php://input' later, but
5048
		// this can only be done once per request in PHP versions prior to 5.6.
5049
		// So we will go ahead and perform this read now if needed, and save
5050
		// the request body where both the Jetpack signature verification code
5051
		// and the WP REST API code can see it.
5052
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5053
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5054
		}
5055
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5056
5057
		// Only support specific request parameters that have been tested and
5058
		// are known to work with signature verification.  A different method
5059
		// can be passed to the WP REST API via the '?_method=' parameter if
5060
		// needed.
5061
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5062
			$this->rest_authentication_status = new WP_Error(
5063
				'rest_invalid_request',
5064
				__( 'This request method is not supported.', 'jetpack' ),
5065
				array( 'status' => 400 )
5066
			);
5067
			return null;
5068
		}
5069
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5070
			$this->rest_authentication_status = new WP_Error(
5071
				'rest_invalid_request',
5072
				__( 'This request method does not support body parameters.', 'jetpack' ),
5073
				array( 'status' => 400 )
5074
			);
5075
			return null;
5076
		}
5077
5078
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5079
5080
		if (
5081
			$verified &&
5082
			isset( $verified['type'] ) &&
5083
			'user' === $verified['type'] &&
5084
			! empty( $verified['user_id'] )
5085
		) {
5086
			// Authentication successful.
5087
			$this->rest_authentication_status = true;
5088
			return $verified['user_id'];
5089
		}
5090
5091
		// Something else went wrong.  Probably a signature error.
5092
		$this->rest_authentication_status = new WP_Error(
5093
			'rest_invalid_signature',
5094
			__( 'The request is not signed correctly.', 'jetpack' ),
5095
			array( 'status' => 400 )
5096
		);
5097
		return null;
5098
	}
5099
5100
	/**
5101
	 * Report authentication status to the WP REST API.
5102
	 *
5103
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5104
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5105
	 */
5106
	public function wp_rest_authentication_errors( $value ) {
5107
		if ( $value !== null ) {
5108
			return $value;
5109
		}
5110
		return $this->rest_authentication_status;
5111
	}
5112
5113
	/**
5114
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5115
	 * SET: state( $key, $value );
5116
	 * GET: $value = state( $key );
5117
	 *
5118
	 * @param string $key
5119
	 * @param string $value
5120
	 * @param bool $restate private
5121
	 */
5122
	public static function state( $key = null, $value = null, $restate = false ) {
5123
		static $state = array();
5124
		static $path, $domain;
5125
		if ( ! isset( $path ) ) {
5126
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5127
			$admin_url = Jetpack::admin_url();
5128
			$bits      = wp_parse_url( $admin_url );
5129
5130
			if ( is_array( $bits ) ) {
5131
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5132
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5133
			} else {
5134
				$path = $domain = null;
5135
			}
5136
		}
5137
5138
		// Extract state from cookies and delete cookies
5139
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5140
			$yum = $_COOKIE[ 'jetpackState' ];
5141
			unset( $_COOKIE[ 'jetpackState' ] );
5142
			foreach ( $yum as $k => $v ) {
5143
				if ( strlen( $v ) )
5144
					$state[ $k ] = $v;
5145
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5146
			}
5147
		}
5148
5149
		if ( $restate ) {
5150
			foreach ( $state as $k => $v ) {
5151
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5152
			}
5153
			return;
5154
		}
5155
5156
		// Get a state variable
5157
		if ( isset( $key ) && ! isset( $value ) ) {
5158
			if ( array_key_exists( $key, $state ) )
5159
				return $state[ $key ];
5160
			return null;
5161
		}
5162
5163
		// Set a state variable
5164
		if ( isset ( $key ) && isset( $value ) ) {
5165
			if( is_array( $value ) && isset( $value[0] ) ) {
5166
				$value = $value[0];
5167
			}
5168
			$state[ $key ] = $value;
5169
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5170
		}
5171
	}
5172
5173
	public static function restate() {
5174
		Jetpack::state( null, null, true );
5175
	}
5176
5177
	public static function check_privacy( $file ) {
5178
		static $is_site_publicly_accessible = null;
5179
5180
		if ( is_null( $is_site_publicly_accessible ) ) {
5181
			$is_site_publicly_accessible = false;
5182
5183
			Jetpack::load_xml_rpc_client();
5184
			$rpc = new Jetpack_IXR_Client();
5185
5186
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5187
			if ( $success ) {
5188
				$response = $rpc->getResponse();
5189
				if ( $response ) {
5190
					$is_site_publicly_accessible = true;
5191
				}
5192
			}
5193
5194
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5195
		}
5196
5197
		if ( $is_site_publicly_accessible ) {
5198
			return;
5199
		}
5200
5201
		$module_slug = self::get_module_slug( $file );
5202
5203
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5204
		if ( ! $privacy_checks ) {
5205
			$privacy_checks = $module_slug;
5206
		} else {
5207
			$privacy_checks .= ",$module_slug";
5208
		}
5209
5210
		Jetpack::state( 'privacy_checks', $privacy_checks );
5211
	}
5212
5213
	/**
5214
	 * Helper method for multicall XMLRPC.
5215
	 */
5216
	public static function xmlrpc_async_call() {
5217
		global $blog_id;
5218
		static $clients = array();
5219
5220
		$client_blog_id = is_multisite() ? $blog_id : 0;
5221
5222
		if ( ! isset( $clients[$client_blog_id] ) ) {
5223
			Jetpack::load_xml_rpc_client();
5224
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5225
			if ( function_exists( 'ignore_user_abort' ) ) {
5226
				ignore_user_abort( true );
5227
			}
5228
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5229
		}
5230
5231
		$args = func_get_args();
5232
5233
		if ( ! empty( $args[0] ) ) {
5234
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5235
		} elseif ( is_multisite() ) {
5236
			foreach ( $clients as $client_blog_id => $client ) {
5237
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5238
					continue;
5239
				}
5240
5241
				$switch_success = switch_to_blog( $client_blog_id, true );
5242
				if ( ! $switch_success ) {
5243
					continue;
5244
				}
5245
5246
				flush();
5247
				$client->query();
5248
5249
				restore_current_blog();
5250
			}
5251
		} else {
5252
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5253
				flush();
5254
				$clients[0]->query();
5255
			}
5256
		}
5257
	}
5258
5259
	public static function staticize_subdomain( $url ) {
5260
5261
		// Extract hostname from URL
5262
		$host = parse_url( $url, PHP_URL_HOST );
5263
5264
		// Explode hostname on '.'
5265
		$exploded_host = explode( '.', $host );
5266
5267
		// Retrieve the name and TLD
5268
		if ( count( $exploded_host ) > 1 ) {
5269
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5270
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5271
			// Rebuild domain excluding subdomains
5272
			$domain = $name . '.' . $tld;
5273
		} else {
5274
			$domain = $host;
5275
		}
5276
		// Array of Automattic domains
5277
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5278
5279
		// Return $url if not an Automattic domain
5280
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5281
			return $url;
5282
		}
5283
5284
		if ( is_ssl() ) {
5285
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5286
		}
5287
5288
		srand( crc32( basename( $url ) ) );
5289
		$static_counter = rand( 0, 2 );
5290
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5291
5292
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5293
	}
5294
5295
/* JSON API Authorization */
5296
5297
	/**
5298
	 * Handles the login action for Authorizing the JSON API
5299
	 */
5300
	function login_form_json_api_authorization() {
5301
		$this->verify_json_api_authorization_request();
5302
5303
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5304
5305
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5306
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5307
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5308
	}
5309
5310
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5311
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5312
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5313
			return $url;
5314
		}
5315
5316
		$parsed_url = parse_url( $url );
5317
		$url = strtok( $url, '?' );
5318
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5319
		if ( ! empty( $parsed_url['query'] ) )
5320
			$url .= "&{$parsed_url['query']}";
5321
5322
		return $url;
5323
	}
5324
5325
	// Make sure the POSTed request is handled by the same action
5326
	function preserve_action_in_login_form_for_json_api_authorization() {
5327
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5328
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5329
	}
5330
5331
	// If someone logs in to approve API access, store the Access Code in usermeta
5332
	function store_json_api_authorization_token( $user_login, $user ) {
5333
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5334
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5335
		$token = wp_generate_password( 32, false );
5336
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5337
	}
5338
5339
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5340
	function allow_wpcom_public_api_domain( $domains ) {
5341
		$domains[] = 'public-api.wordpress.com';
5342
		return $domains;
5343
	}
5344
5345
	static function is_redirect_encoded( $redirect_url ) {
5346
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5347
	}
5348
5349
	// Add all wordpress.com environments to the safe redirect whitelist
5350
	function allow_wpcom_environments( $domains ) {
5351
		$domains[] = 'wordpress.com';
5352
		$domains[] = 'wpcalypso.wordpress.com';
5353
		$domains[] = 'horizon.wordpress.com';
5354
		$domains[] = 'calypso.localhost';
5355
		return $domains;
5356
	}
5357
5358
	// Add the Access Code details to the public-api.wordpress.com redirect
5359
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5360
		return add_query_arg(
5361
			urlencode_deep(
5362
				array(
5363
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5364
					'jetpack-user-id' => (int) $user->ID,
5365
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5366
				)
5367
			),
5368
			$redirect_to
5369
		);
5370
	}
5371
5372
5373
	/**
5374
	 * Verifies the request by checking the signature
5375
	 *
5376
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5377
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5378
	 *
5379
	 * @param null|array $environment
5380
	 */
5381
	function verify_json_api_authorization_request( $environment = null ) {
5382
		$environment = is_null( $environment )
5383
			? $_REQUEST
5384
			: $environment;
5385
5386
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5387
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5388
		if ( ! $token || empty( $token->secret ) ) {
5389
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5390
		}
5391
5392
		$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' );
5393
5394
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5395
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5396
			/**
5397
			 * Jetpack authorisation request Error.
5398
			 *
5399
			 * @since 7.5.0
5400
			 *
5401
			 */
5402
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5403
			$die_error = sprintf(
5404
				/* translators: %s is a URL */
5405
				__( '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' ),
5406
				'https://jetpack.com/support/double-encoding/'
5407
			);
5408
		}
5409
5410
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5411
5412
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5413
			$signature = $jetpack_signature->sign_request(
5414
				$environment['token'],
5415
				$environment['timestamp'],
5416
				$environment['nonce'],
5417
				'',
5418
				'GET',
5419
				$environment['jetpack_json_api_original_query'],
5420
				null,
5421
				true
5422
			);
5423
		} else {
5424
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5425
		}
5426
5427
		if ( ! $signature ) {
5428
			wp_die( $die_error );
5429
		} else if ( is_wp_error( $signature ) ) {
5430
			wp_die( $die_error );
5431
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5432
			if ( is_ssl() ) {
5433
				// 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
5434
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5435
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5436
					wp_die( $die_error );
5437
				}
5438
			} else {
5439
				wp_die( $die_error );
5440
			}
5441
		}
5442
5443
		$timestamp = (int) $environment['timestamp'];
5444
		$nonce     = stripslashes( (string) $environment['nonce'] );
5445
5446
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
5447
			// De-nonce the nonce, at least for 5 minutes.
5448
			// 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)
5449
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5450
			if ( $old_nonce_time < time() - 300 ) {
5451
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5452
			}
5453
		}
5454
5455
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5456
		$data_filters = array(
5457
			'state'        => 'opaque',
5458
			'client_id'    => 'int',
5459
			'client_title' => 'string',
5460
			'client_image' => 'url',
5461
		);
5462
5463
		foreach ( $data_filters as $key => $sanitation ) {
5464
			if ( ! isset( $data->$key ) ) {
5465
				wp_die( $die_error );
5466
			}
5467
5468
			switch ( $sanitation ) {
5469
			case 'int' :
5470
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5471
				break;
5472
			case 'opaque' :
5473
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5474
				break;
5475
			case 'string' :
5476
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5477
				break;
5478
			case 'url' :
5479
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5480
				break;
5481
			}
5482
		}
5483
5484
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5485
			wp_die( $die_error );
5486
		}
5487
	}
5488
5489
	function login_message_json_api_authorization( $message ) {
5490
		return '<p class="message">' . sprintf(
5491
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5492
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5493
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5494
	}
5495
5496
	/**
5497
	 * Get $content_width, but with a <s>twist</s> filter.
5498
	 */
5499
	public static function get_content_width() {
5500
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5501
			? $GLOBALS['content_width']
5502
			: false;
5503
		/**
5504
		 * Filter the Content Width value.
5505
		 *
5506
		 * @since 2.2.3
5507
		 *
5508
		 * @param string $content_width Content Width value.
5509
		 */
5510
		return apply_filters( 'jetpack_content_width', $content_width );
5511
	}
5512
5513
	/**
5514
	 * Pings the WordPress.com Mirror Site for the specified options.
5515
	 *
5516
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5517
	 *
5518
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5519
	 */
5520
	public function get_cloud_site_options( $option_names ) {
5521
		$option_names = array_filter( (array) $option_names, 'is_string' );
5522
5523
		Jetpack::load_xml_rpc_client();
5524
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5525
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5526
		if ( $xml->isError() ) {
5527
			return array(
5528
				'error_code' => $xml->getErrorCode(),
5529
				'error_msg'  => $xml->getErrorMessage(),
5530
			);
5531
		}
5532
		$cloud_site_options = $xml->getResponse();
5533
5534
		return $cloud_site_options;
5535
	}
5536
5537
	/**
5538
	 * Checks if the site is currently in an identity crisis.
5539
	 *
5540
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5541
	 */
5542
	public static function check_identity_crisis() {
5543
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5544
			return false;
5545
		}
5546
5547
		return Jetpack_Options::get_option( 'sync_error_idc' );
5548
	}
5549
5550
	/**
5551
	 * Checks whether the home and siteurl specifically are whitelisted
5552
	 * Written so that we don't have re-check $key and $value params every time
5553
	 * we want to check if this site is whitelisted, for example in footer.php
5554
	 *
5555
	 * @since  3.8.0
5556
	 * @return bool True = already whitelisted False = not whitelisted
5557
	 */
5558
	public static function is_staging_site() {
5559
		$is_staging = false;
5560
5561
		$known_staging = array(
5562
			'urls' => array(
5563
				'#\.staging\.wpengine\.com$#i', // WP Engine
5564
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5565
				'#\.stage\.site$#i'             // DreamPress
5566
			),
5567
			'constants' => array(
5568
				'IS_WPE_SNAPSHOT',      // WP Engine
5569
				'KINSTA_DEV_ENV',       // Kinsta.com
5570
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5571
				'JETPACK_STAGING_MODE', // Generic
5572
			)
5573
		);
5574
		/**
5575
		 * Filters the flags of known staging sites.
5576
		 *
5577
		 * @since 3.9.0
5578
		 *
5579
		 * @param array $known_staging {
5580
		 *     An array of arrays that each are used to check if the current site is staging.
5581
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5582
		 *     @type array $constants PHP constants of known staging/developement environments.
5583
		 *  }
5584
		 */
5585
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5586
5587
		if ( isset( $known_staging['urls'] ) ) {
5588
			foreach ( $known_staging['urls'] as $url ){
5589
				if ( preg_match( $url, site_url() ) ) {
5590
					$is_staging = true;
5591
					break;
5592
				}
5593
			}
5594
		}
5595
5596
		if ( isset( $known_staging['constants'] ) ) {
5597
			foreach ( $known_staging['constants'] as $constant ) {
5598
				if ( defined( $constant ) && constant( $constant ) ) {
5599
					$is_staging = true;
5600
				}
5601
			}
5602
		}
5603
5604
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5605
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5606
			$is_staging = true;
5607
		}
5608
5609
		/**
5610
		 * Filters is_staging_site check.
5611
		 *
5612
		 * @since 3.9.0
5613
		 *
5614
		 * @param bool $is_staging If the current site is a staging site.
5615
		 */
5616
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5617
	}
5618
5619
	/**
5620
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5621
	 *
5622
	 * @since 4.4.0
5623
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5624
	 *
5625
	 * @return bool
5626
	 */
5627
	public static function validate_sync_error_idc_option() {
5628
		$is_valid = false;
5629
5630
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5631
		if ( false === $idc_allowed ) {
5632
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5633
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5634
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5635
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5636
				$transient_duration = HOUR_IN_SECONDS;
5637
			} else {
5638
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5639
				$idc_allowed = '1';
5640
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5641
			}
5642
5643
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5644
		}
5645
5646
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5647
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5648
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5649
			$local_options = self::get_sync_error_idc_option();
5650
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5651
				$is_valid = true;
5652
			}
5653
		}
5654
5655
		/**
5656
		 * Filters whether the sync_error_idc option is valid.
5657
		 *
5658
		 * @since 4.4.0
5659
		 *
5660
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5661
		 */
5662
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5663
5664
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5665
			// Since the option exists, and did not validate, delete it
5666
			Jetpack_Options::delete_option( 'sync_error_idc' );
5667
		}
5668
5669
		return $is_valid;
5670
	}
5671
5672
	/**
5673
	 * Normalizes a url by doing three things:
5674
	 *  - Strips protocol
5675
	 *  - Strips www
5676
	 *  - Adds a trailing slash
5677
	 *
5678
	 * @since 4.4.0
5679
	 * @param string $url
5680
	 * @return WP_Error|string
5681
	 */
5682
	public static function normalize_url_protocol_agnostic( $url ) {
5683
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5684
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5685
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5686
		}
5687
5688
		// Strip www and protocols
5689
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5690
		return $url;
5691
	}
5692
5693
	/**
5694
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5695
	 *
5696
	 * @since 4.4.0
5697
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5698
	 *
5699
	 * @param array $response
5700
	 * @return array Array of the local urls, wpcom urls, and error code
5701
	 */
5702
	public static function get_sync_error_idc_option( $response = array() ) {
5703
		// Since the local options will hit the database directly, store the values
5704
		// in a transient to allow for autoloading and caching on subsequent views.
5705
		$local_options = get_transient( 'jetpack_idc_local' );
5706
		if ( false === $local_options ) {
5707
			$local_options = array(
5708
				'home'    => Functions::home_url(),
5709
				'siteurl' => Functions::site_url(),
5710
			);
5711
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5712
		}
5713
5714
		$options = array_merge( $local_options, $response );
5715
5716
		$returned_values = array();
5717
		foreach( $options as $key => $option ) {
5718
			if ( 'error_code' === $key ) {
5719
				$returned_values[ $key ] = $option;
5720
				continue;
5721
			}
5722
5723
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5724
				continue;
5725
			}
5726
5727
			$returned_values[ $key ] = $normalized_url;
5728
		}
5729
5730
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5731
5732
		return $returned_values;
5733
	}
5734
5735
	/**
5736
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5737
	 * If set to true, the site will be put into staging mode.
5738
	 *
5739
	 * @since 4.3.2
5740
	 * @return bool
5741
	 */
5742
	public static function sync_idc_optin() {
5743
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5744
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5745
		} else {
5746
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5747
		}
5748
5749
		/**
5750
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5751
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5752
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5753
		 *
5754
		 * @since 4.3.2
5755
		 *
5756
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5757
		 */
5758
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5759
	}
5760
5761
	/**
5762
	 * Maybe Use a .min.css stylesheet, maybe not.
5763
	 *
5764
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5765
	 */
5766
	public static function maybe_min_asset( $url, $path, $plugin ) {
5767
		// Short out on things trying to find actual paths.
5768
		if ( ! $path || empty( $plugin ) ) {
5769
			return $url;
5770
		}
5771
5772
		$path = ltrim( $path, '/' );
5773
5774
		// Strip out the abspath.
5775
		$base = dirname( plugin_basename( $plugin ) );
5776
5777
		// Short out on non-Jetpack assets.
5778
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5779
			return $url;
5780
		}
5781
5782
		// File name parsing.
5783
		$file              = "{$base}/{$path}";
5784
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5785
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5786
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5787
		$extension         = array_shift( $file_name_parts_r );
5788
5789
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5790
			// Already pointing at the minified version.
5791
			if ( 'min' === $file_name_parts_r[0] ) {
5792
				return $url;
5793
			}
5794
5795
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5796
			if ( file_exists( $min_full_path ) ) {
5797
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5798
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5799
				if ( 'css' === $extension ) {
5800
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5801
					self::$min_assets[ $key ] = $path;
5802
				}
5803
			}
5804
		}
5805
5806
		return $url;
5807
	}
5808
5809
	/**
5810
	 * If the asset is minified, let's flag .min as the suffix.
5811
	 *
5812
	 * Attached to `style_loader_src` filter.
5813
	 *
5814
	 * @param string $tag The tag that would link to the external asset.
5815
	 * @param string $handle The registered handle of the script in question.
5816
	 * @param string $href The url of the asset in question.
5817
	 */
5818
	public static function set_suffix_on_min( $src, $handle ) {
5819
		if ( false === strpos( $src, '.min.css' ) ) {
5820
			return $src;
5821
		}
5822
5823
		if ( ! empty( self::$min_assets ) ) {
5824
			foreach ( self::$min_assets as $file => $path ) {
5825
				if ( false !== strpos( $src, $file ) ) {
5826
					wp_style_add_data( $handle, 'suffix', '.min' );
5827
					return $src;
5828
				}
5829
			}
5830
		}
5831
5832
		return $src;
5833
	}
5834
5835
	/**
5836
	 * Maybe inlines a stylesheet.
5837
	 *
5838
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5839
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5840
	 *
5841
	 * Attached to `style_loader_tag` filter.
5842
	 *
5843
	 * @param string $tag The tag that would link to the external asset.
5844
	 * @param string $handle The registered handle of the script in question.
5845
	 *
5846
	 * @return string
5847
	 */
5848
	public static function maybe_inline_style( $tag, $handle ) {
5849
		global $wp_styles;
5850
		$item = $wp_styles->registered[ $handle ];
5851
5852
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5853
			return $tag;
5854
		}
5855
5856
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5857
			$href = $matches[1];
5858
			// Strip off query string
5859
			if ( $pos = strpos( $href, '?' ) ) {
5860
				$href = substr( $href, 0, $pos );
5861
			}
5862
			// Strip off fragment
5863
			if ( $pos = strpos( $href, '#' ) ) {
5864
				$href = substr( $href, 0, $pos );
5865
			}
5866
		} else {
5867
			return $tag;
5868
		}
5869
5870
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5871
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5872
			return $tag;
5873
		}
5874
5875
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5876
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5877
			// And this isn't the pass that actually deals with the RTL version...
5878
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5879
				// Short out, as the RTL version will deal with it in a moment.
5880
				return $tag;
5881
			}
5882
		}
5883
5884
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5885
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5886
		if ( $css ) {
5887
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5888
			if ( empty( $item->extra['after'] ) ) {
5889
				wp_add_inline_style( $handle, $css );
5890
			} else {
5891
				array_unshift( $item->extra['after'], $css );
5892
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5893
			}
5894
		}
5895
5896
		return $tag;
5897
	}
5898
5899
	/**
5900
	 * Loads a view file from the views
5901
	 *
5902
	 * Data passed in with the $data parameter will be available in the
5903
	 * template file as $data['value']
5904
	 *
5905
	 * @param string $template - Template file to load
5906
	 * @param array $data - Any data to pass along to the template
5907
	 * @return boolean - If template file was found
5908
	 **/
5909
	public function load_view( $template, $data = array() ) {
5910
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5911
5912
		if( file_exists( $views_dir . $template ) ) {
5913
			require_once( $views_dir . $template );
5914
			return true;
5915
		}
5916
5917
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5918
		return false;
5919
	}
5920
5921
	/**
5922
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5923
	 */
5924
	public function deprecated_hooks() {
5925
		global $wp_filter;
5926
5927
		/*
5928
		 * Format:
5929
		 * deprecated_filter_name => replacement_name
5930
		 *
5931
		 * If there is no replacement, use null for replacement_name
5932
		 */
5933
		$deprecated_list = array(
5934
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5935
			'wpl_sharing_2014_1'                                     => null,
5936
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5937
			'jetpack_identity_crisis_options_to_check'               => null,
5938
			'update_option_jetpack_single_user_site'                 => null,
5939
			'audio_player_default_colors'                            => null,
5940
			'add_option_jetpack_featured_images_enabled'             => null,
5941
			'add_option_jetpack_update_details'                      => null,
5942
			'add_option_jetpack_updates'                             => null,
5943
			'add_option_jetpack_network_name'                        => null,
5944
			'add_option_jetpack_network_allow_new_registrations'     => null,
5945
			'add_option_jetpack_network_add_new_users'               => null,
5946
			'add_option_jetpack_network_site_upload_space'           => null,
5947
			'add_option_jetpack_network_upload_file_types'           => null,
5948
			'add_option_jetpack_network_enable_administration_menus' => null,
5949
			'add_option_jetpack_is_multi_site'                       => null,
5950
			'add_option_jetpack_is_main_network'                     => null,
5951
			'add_option_jetpack_main_network_site'                   => null,
5952
			'jetpack_sync_all_registered_options'                    => null,
5953
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5954
			'jetpack_is_post_mailable'                               => null,
5955
			'jetpack_seo_site_host'                                  => null,
5956
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
5957
			'jetpack_holiday_snow_option_name'                       => null,
5958
			'jetpack_holiday_chance_of_snow'                         => null,
5959
			'jetpack_holiday_snow_js_url'                            => null,
5960
			'jetpack_is_holiday_snow_season'                         => null,
5961
			'jetpack_holiday_snow_option_updated'                    => null,
5962
			'jetpack_holiday_snowing'                                => null,
5963
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
5964
			'jetpack_cache_plans'                                    => null,
5965
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
5966
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
5967
			'jetpack_enable_site_verification'                       => null,
5968
			'can_display_jetpack_manage_notice'                      => null,
5969
			// Removed in Jetpack 7.3.0
5970
			'atd_load_scripts'                                       => null,
5971
			'atd_http_post_timeout'                                  => null,
5972
			'atd_http_post_error'                                    => null,
5973
			'atd_service_domain'                                     => null,
5974
		);
5975
5976
		// This is a silly loop depth. Better way?
5977
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5978
			if ( has_action( $hook ) ) {
5979
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
5980
					foreach( $values AS $hooked ) {
5981
						if ( is_callable( $hooked['function'] ) ) {
5982
							$function_name = 'an anonymous function';
5983
						} else {
5984
							$function_name = $hooked['function'];
5985
						}
5986
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
5987
					}
5988
				}
5989
			}
5990
		}
5991
	}
5992
5993
	/**
5994
	 * Converts any url in a stylesheet, to the correct absolute url.
5995
	 *
5996
	 * Considerations:
5997
	 *  - Normal, relative URLs     `feh.png`
5998
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5999
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6000
	 *  - Absolute URLs             `http://domain.com/feh.png`
6001
	 *  - Domain root relative URLs `/feh.png`
6002
	 *
6003
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6004
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6005
	 *
6006
	 * @return mixed|string
6007
	 */
6008
	public static function absolutize_css_urls( $css, $css_file_url ) {
6009
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6010
		$css_dir = dirname( $css_file_url );
6011
		$p       = parse_url( $css_dir );
6012
		$domain  = sprintf(
6013
					'%1$s//%2$s%3$s%4$s',
6014
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6015
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6016
					$p['host'],
6017
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6018
				);
6019
6020
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6021
			$find = $replace = array();
6022
			foreach ( $matches as $match ) {
6023
				$url = trim( $match['path'], "'\" \t" );
6024
6025
				// If this is a data url, we don't want to mess with it.
6026
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6027
					continue;
6028
				}
6029
6030
				// If this is an absolute or protocol-agnostic url,
6031
				// we don't want to mess with it.
6032
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6033
					continue;
6034
				}
6035
6036
				switch ( substr( $url, 0, 1 ) ) {
6037
					case '/':
6038
						$absolute = $domain . $url;
6039
						break;
6040
					default:
6041
						$absolute = $css_dir . '/' . $url;
6042
				}
6043
6044
				$find[]    = $match[0];
6045
				$replace[] = sprintf( 'url("%s")', $absolute );
6046
			}
6047
			$css = str_replace( $find, $replace, $css );
6048
		}
6049
6050
		return $css;
6051
	}
6052
6053
	/**
6054
	 * This methods removes all of the registered css files on the front end
6055
	 * from Jetpack in favor of using a single file. In effect "imploding"
6056
	 * all the files into one file.
6057
	 *
6058
	 * Pros:
6059
	 * - Uses only ONE css asset connection instead of 15
6060
	 * - Saves a minimum of 56k
6061
	 * - Reduces server load
6062
	 * - Reduces time to first painted byte
6063
	 *
6064
	 * Cons:
6065
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6066
	 *		should not cause any issues with themes.
6067
	 * - Plugins/themes dequeuing styles no longer do anything. See
6068
	 *		jetpack_implode_frontend_css filter for a workaround
6069
	 *
6070
	 * For some situations developers may wish to disable css imploding and
6071
	 * instead operate in legacy mode where each file loads seperately and
6072
	 * can be edited individually or dequeued. This can be accomplished with
6073
	 * the following line:
6074
	 *
6075
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6076
	 *
6077
	 * @since 3.2
6078
	 **/
6079
	public function implode_frontend_css( $travis_test = false ) {
6080
		$do_implode = true;
6081
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6082
			$do_implode = false;
6083
		}
6084
6085
		// Do not implode CSS when the page loads via the AMP plugin.
6086
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6087
			$do_implode = false;
6088
		}
6089
6090
		/**
6091
		 * Allow CSS to be concatenated into a single jetpack.css file.
6092
		 *
6093
		 * @since 3.2.0
6094
		 *
6095
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6096
		 */
6097
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6098
6099
		// Do not use the imploded file when default behavior was altered through the filter
6100
		if ( ! $do_implode ) {
6101
			return;
6102
		}
6103
6104
		// We do not want to use the imploded file in dev mode, or if not connected
6105
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6106
			if ( ! $travis_test ) {
6107
				return;
6108
			}
6109
		}
6110
6111
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6112
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6113
			return;
6114
		}
6115
6116
		/*
6117
		 * Now we assume Jetpack is connected and able to serve the single
6118
		 * file.
6119
		 *
6120
		 * In the future there will be a check here to serve the file locally
6121
		 * or potentially from the Jetpack CDN
6122
		 *
6123
		 * For now:
6124
		 * - Enqueue a single imploded css file
6125
		 * - Zero out the style_loader_tag for the bundled ones
6126
		 * - Be happy, drink scotch
6127
		 */
6128
6129
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6130
6131
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6132
6133
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6134
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6135
	}
6136
6137
	function concat_remove_style_loader_tag( $tag, $handle ) {
6138
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6139
			$tag = '';
6140
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6141
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6142
			}
6143
		}
6144
6145
		return $tag;
6146
	}
6147
6148
	/*
6149
	 * Check the heartbeat data
6150
	 *
6151
	 * Organizes the heartbeat data by severity.  For example, if the site
6152
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6153
	 *
6154
	 * Data will be added to "caution" array, if it either:
6155
	 *  - Out of date Jetpack version
6156
	 *  - Out of date WP version
6157
	 *  - Out of date PHP version
6158
	 *
6159
	 * $return array $filtered_data
6160
	 */
6161
	public static function jetpack_check_heartbeat_data() {
6162
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6163
6164
		$good    = array();
6165
		$caution = array();
6166
		$bad     = array();
6167
6168
		foreach ( $raw_data as $stat => $value ) {
6169
6170
			// Check jetpack version
6171
			if ( 'version' == $stat ) {
6172
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6173
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6174
					continue;
6175
				}
6176
			}
6177
6178
			// Check WP version
6179
			if ( 'wp-version' == $stat ) {
6180
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6181
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6182
					continue;
6183
				}
6184
			}
6185
6186
			// Check PHP version
6187
			if ( 'php-version' == $stat ) {
6188
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6189
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6190
					continue;
6191
				}
6192
			}
6193
6194
			// Check ID crisis
6195
			if ( 'identitycrisis' == $stat ) {
6196
				if ( 'yes' == $value ) {
6197
					$bad[ $stat ] = $value;
6198
					continue;
6199
				}
6200
			}
6201
6202
			// The rest are good :)
6203
			$good[ $stat ] = $value;
6204
		}
6205
6206
		$filtered_data = array(
6207
			'good'    => $good,
6208
			'caution' => $caution,
6209
			'bad'     => $bad
6210
		);
6211
6212
		return $filtered_data;
6213
	}
6214
6215
6216
	/*
6217
	 * This method is used to organize all options that can be reset
6218
	 * without disconnecting Jetpack.
6219
	 *
6220
	 * It is used in class.jetpack-cli.php to reset options
6221
	 *
6222
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6223
	 *
6224
	 * @return array of options to delete.
6225
	 */
6226
	public static function get_jetpack_options_for_reset() {
6227
		return Jetpack_Options::get_options_for_reset();
6228
	}
6229
6230
	/*
6231
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6232
	 * so we can bring them directly to their site in calypso.
6233
	 *
6234
	 * @param string | url
6235
	 * @return string | url without the guff
6236
	 */
6237
	public static function build_raw_urls( $url ) {
6238
		$strip_http = '/.*?:\/\//i';
6239
		$url = preg_replace( $strip_http, '', $url  );
6240
		$url = str_replace( '/', '::', $url );
6241
		return $url;
6242
	}
6243
6244
	/**
6245
	 * Stores and prints out domains to prefetch for page speed optimization.
6246
	 *
6247
	 * @param mixed $new_urls
6248
	 */
6249
	public static function dns_prefetch( $new_urls = null ) {
6250
		static $prefetch_urls = array();
6251
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6252
			echo "\r\n";
6253
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6254
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6255
			}
6256
		} elseif ( ! empty( $new_urls ) ) {
6257
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6258
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6259
			}
6260
			foreach ( (array) $new_urls as $this_new_url ) {
6261
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6262
			}
6263
			$prefetch_urls = array_unique( $prefetch_urls );
6264
		}
6265
	}
6266
6267
	public function wp_dashboard_setup() {
6268
		if ( self::is_active() ) {
6269
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6270
		}
6271
6272
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6273
			$jetpack_logo = new Jetpack_Logo();
6274
			$widget_title = sprintf(
6275
				wp_kses(
6276
					/* translators: Placeholder is a Jetpack logo. */
6277
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6278
					array( 'span' => array() )
6279
				),
6280
				$jetpack_logo->get_jp_emblem( true )
6281
			);
6282
6283
			wp_add_dashboard_widget(
6284
				'jetpack_summary_widget',
6285
				$widget_title,
6286
				array( __CLASS__, 'dashboard_widget' )
6287
			);
6288
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6289
6290
			// If we're inactive and not in development mode, sort our box to the top.
6291
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6292
				global $wp_meta_boxes;
6293
6294
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6295
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6296
6297
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6298
			}
6299
		}
6300
	}
6301
6302
	/**
6303
	 * @param mixed $result Value for the user's option
6304
	 * @return mixed
6305
	 */
6306
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6307
		if ( ! is_array( $sorted ) ) {
6308
			return $sorted;
6309
		}
6310
6311
		foreach ( $sorted as $box_context => $ids ) {
6312
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6313
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6314
				continue;
6315
			}
6316
6317
			$ids_array = explode( ',', $ids );
6318
			$key = array_search( 'dashboard_stats', $ids_array );
6319
6320
			if ( false !== $key ) {
6321
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6322
				$ids_array[ $key ] = 'jetpack_summary_widget';
6323
				$sorted[ $box_context ] = implode( ',', $ids_array );
6324
				// We've found it, stop searching, and just return.
6325
				break;
6326
			}
6327
		}
6328
6329
		return $sorted;
6330
	}
6331
6332
	public static function dashboard_widget() {
6333
		/**
6334
		 * Fires when the dashboard is loaded.
6335
		 *
6336
		 * @since 3.4.0
6337
		 */
6338
		do_action( 'jetpack_dashboard_widget' );
6339
	}
6340
6341
	public static function dashboard_widget_footer() {
6342
		?>
6343
		<footer>
6344
6345
		<div class="protect">
6346
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6347
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6348
				<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>
6349
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6350
				<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( array( 'action' => 'activate', 'module' => 'protect' ) ), 'jetpack_activate-protect' ) ); ?>" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6351
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6352
				</a>
6353
			<?php else : ?>
6354
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6355
			<?php endif; ?>
6356
		</div>
6357
6358
		<div class="akismet">
6359
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6360
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6361
				<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>
6362
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6363
				<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'activate', 'plugin' => 'akismet/akismet.php' ), admin_url( 'plugins.php' ) ), 'activate-plugin_akismet/akismet.php' ) ); ?>" class="button button-jetpack">
6364
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6365
				</a>
6366
			<?php else : ?>
6367
				<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>
6368
			<?php endif; ?>
6369
		</div>
6370
6371
		</footer>
6372
		<?php
6373
	}
6374
6375
	/*
6376
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6377
	 */
6378
	function jetpack_icon_user_connected( $columns ) {
6379
		$columns['user_jetpack'] = '';
6380
		return $columns;
6381
	}
6382
6383
	/*
6384
	 * Show Jetpack icon if the user is linked.
6385
	 */
6386
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6387
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6388
			$jetpack_logo = new Jetpack_Logo();
6389
			$emblem_html = sprintf(
6390
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6391
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6392
				$jetpack_logo->get_jp_emblem()
6393
			);
6394
			return $emblem_html;
6395
		}
6396
6397
		return $val;
6398
	}
6399
6400
	/*
6401
	 * Style the Jetpack user column
6402
	 */
6403
	function jetpack_user_col_style() {
6404
		global $current_screen;
6405
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6406
			<style>
6407
				.fixed .column-user_jetpack {
6408
					width: 21px;
6409
				}
6410
				.jp-emblem-user-admin svg {
6411
					width: 20px;
6412
					height: 20px;
6413
				}
6414
				.jp-emblem-user-admin path {
6415
					fill: #00BE28;
6416
				}
6417
			</style>
6418
		<?php }
6419
	}
6420
6421
	/**
6422
	 * Checks if Akismet is active and working.
6423
	 *
6424
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6425
	 * that implied usage of methods present since more recent version.
6426
	 * See https://github.com/Automattic/jetpack/pull/9585
6427
	 *
6428
	 * @since  5.1.0
6429
	 *
6430
	 * @return bool True = Akismet available. False = Aksimet not available.
6431
	 */
6432
	public static function is_akismet_active() {
6433
		static $status = null;
6434
6435
		if ( ! is_null( $status ) ) {
6436
			return $status;
6437
		}
6438
6439
		// Check if a modern version of Akismet is active.
6440
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6441
			$status = false;
6442
			return $status;
6443
		}
6444
6445
		// Make sure there is a key known to Akismet at all before verifying key.
6446
		$akismet_key = Akismet::get_api_key();
6447
		if ( ! $akismet_key ) {
6448
			$status = false;
6449
			return $status;
6450
		}
6451
6452
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6453
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6454
6455
		// 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.
6456
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6457
		// We cache the result of the Akismet key verification for ten minutes.
6458
		if ( ! $akismet_key_state || $recheck ) {
6459
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6460
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6461
		}
6462
6463
		$status = 'valid' === $akismet_key_state;
6464
6465
		return $status;
6466
	}
6467
6468
	/**
6469
	 * @deprecated
6470
	 *
6471
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6472
	 */
6473
	public static function is_function_in_backtrace() {
6474
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6475
	}
6476
6477
	/**
6478
	 * Given a minified path, and a non-minified path, will return
6479
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6480
	 *
6481
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6482
	 * root Jetpack directory.
6483
	 *
6484
	 * @since 5.6.0
6485
	 *
6486
	 * @param string $min_path
6487
	 * @param string $non_min_path
6488
	 * @return string The URL to the file
6489
	 */
6490
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6491
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6492
	}
6493
6494
	/**
6495
	 * Checks for whether Jetpack Backup & Scan is enabled.
6496
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6497
	 * @return bool|int|mixed
6498
	 */
6499
	public static function is_rewind_enabled() {
6500
		if ( ! Jetpack::is_active() ) {
6501
			return false;
6502
		}
6503
6504
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6505
		if ( false === $rewind_enabled ) {
6506
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6507
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6508
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6509
				&& ! empty( $rewind_data['state'] )
6510
				&& 'active' === $rewind_data['state'] )
6511
				? 1
6512
				: 0;
6513
6514
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6515
		}
6516
		return $rewind_enabled;
6517
	}
6518
6519
	/**
6520
	 * Return Calypso environment value; used for developing Jetpack and pairing
6521
	 * it with different Calypso enrionments, such as localhost.
6522
	 *
6523
	 * @since 7.4.0
6524
	 *
6525
	 * @return string Calypso environment
6526
	 */
6527
	public static function get_calypso_env() {
6528
		if ( isset( $_GET['calypso_env'] ) ) {
6529
			return sanitize_key( $_GET['calypso_env'] );
6530
		}
6531
6532
		if ( getenv( 'CALYPSO_ENV' ) ) {
6533
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6534
		}
6535
6536
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6537
			return sanitize_key( CALYPSO_ENV );
6538
		}
6539
6540
		return '';
6541
	}
6542
6543
	/**
6544
	 * Checks whether or not TOS has been agreed upon.
6545
	 * Will return true if a user has clicked to register, or is already connected.
6546
	 */
6547
	public static function jetpack_tos_agreed() {
6548
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6549
	}
6550
6551
	/**
6552
	 * Handles activating default modules as well general cleanup for the new connection.
6553
	 *
6554
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6555
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6556
	 * @param boolean $send_state_messages          Whether to send state messages.
6557
	 * @return void
6558
	 */
6559
	public static function handle_post_authorization_actions(
6560
		$activate_sso = false,
6561
		$redirect_on_activation_error = false,
6562
		$send_state_messages = true
6563
	) {
6564
		$other_modules = $activate_sso
6565
			? array( 'sso' )
6566
			: array();
6567
6568
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6569
			Jetpack::delete_active_modules();
6570
6571
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
6572
		} else {
6573
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6574
		}
6575
6576
		// Since this is a fresh connection, be sure to clear out IDC options
6577
		Jetpack_IDC::clear_all_idc_options();
6578
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6579
6580
		// Start nonce cleaner
6581
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6582
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6583
6584
		if ( $send_state_messages ) {
6585
			Jetpack::state( 'message', 'authorized' );
6586
		}
6587
	}
6588
6589
	/**
6590
	 * Returns a boolean for whether backups UI should be displayed or not.
6591
	 *
6592
	 * @return bool Should backups UI be displayed?
6593
	 */
6594
	public static function show_backups_ui() {
6595
		/**
6596
		 * Whether UI for backups should be displayed.
6597
		 *
6598
		 * @since 6.5.0
6599
		 *
6600
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6601
		 */
6602
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6603
	}
6604
6605
	/*
6606
	 * Deprecated manage functions
6607
	 */
6608
	function prepare_manage_jetpack_notice() {
6609
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6610
	}
6611
	function manage_activate_screen() {
6612
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6613
	}
6614
	function admin_jetpack_manage_notice() {
6615
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6616
	}
6617
	function opt_out_jetpack_manage_url() {
6618
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6619
	}
6620
	function opt_in_jetpack_manage_url() {
6621
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6622
	}
6623
	function opt_in_jetpack_manage_notice() {
6624
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6625
	}
6626
	function can_display_jetpack_manage_notice() {
6627
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6628
	}
6629
6630
	/**
6631
	 * Clean leftoveruser meta.
6632
	 *
6633
	 * Delete Jetpack-related user meta when it is no longer needed.
6634
	 *
6635
	 * @since 7.3.0
6636
	 *
6637
	 * @param int $user_id User ID being updated.
6638
	 */
6639
	public static function user_meta_cleanup( $user_id ) {
6640
		$meta_keys = array(
6641
			// AtD removed from Jetpack 7.3
6642
			'AtD_options',
6643
			'AtD_check_when',
6644
			'AtD_guess_lang',
6645
			'AtD_ignored_phrases',
6646
		);
6647
6648
		foreach ( $meta_keys as $meta_key ) {
6649
			if ( get_user_meta( $user_id, $meta_key ) ) {
6650
				delete_user_meta( $user_id, $meta_key );
6651
			}
6652
		}
6653
	}
6654
6655
	function is_active_and_not_development_mode( $maybe ) {
6656
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6657
			return false;
6658
		}
6659
		return true;
6660
	}
6661
6662
	/**
6663
	 * @deprecated use Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature
6664
	 */
6665
	public static function verify_xml_rpc_signature() {
6666
		return self::connection()->verify_xml_rpc_signature();
6667
	}
6668
}
6669