Completed
Push — update/_inc_minify_v2 ( d7c168 )
by
unknown
08:21
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
		'eu-cookie-law-style',
60
		'flickr-widget-style',
61
	);
62
63
	/**
64
	 * Contains all assets that have had their URL rewritten to minified versions.
65
	 *
66
	 * @var array
67
	 */
68
	static $min_assets = array();
69
70
	public $plugins_to_deactivate = array(
71
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
72
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
73
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
74
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
75
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
76
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
77
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
78
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
79
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
80
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
81
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
82
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
83
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
84
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
85
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
86
	);
87
88
	static $capability_translations = array(
89
		'administrator' => 'manage_options',
90
		'editor'        => 'edit_others_posts',
91
		'author'        => 'publish_posts',
92
		'contributor'   => 'edit_posts',
93
		'subscriber'    => 'read',
94
	);
95
96
	/**
97
	 * Map of modules that have conflicts with plugins and should not be auto-activated
98
	 * if the plugins are active.  Used by filter_default_modules
99
	 *
100
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
101
	 * change `module-slug` and add this to your plugin:
102
	 *
103
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
104
	 * function my_jetpack_get_default_modules( $modules ) {
105
	 *     return array_diff( $modules, array( 'module-slug' ) );
106
	 * }
107
	 *
108
	 * @var array
109
	 */
110
	private $conflicting_plugins = array(
111
		'comments'          => array(
112
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
113
			'Disqus'                               => 'disqus-comment-system/disqus.php',
114
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
115
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
116
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
117
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
118
		),
119
		'comment-likes' => array(
120
			'Epoch'                                => 'epoch/plugincore.php',
121
		),
122
		'contact-form'      => array(
123
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
124
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
125
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
126
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
127
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
128
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
129
		),
130
		'minileven'         => array(
131
			'WPtouch'                              => 'wptouch/wptouch.php',
132
		),
133
		'latex'             => array(
134
			'LaTeX for WordPress'                  => 'latex/latex.php',
135
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
136
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
137
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
138
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
139
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
140
		),
141
		'protect'           => array(
142
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
143
			'Captcha'                              => 'captcha/captcha.php',
144
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
145
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
146
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
147
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
148
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
149
			'Security-protection'                  => 'security-protection/security-protection.php',
150
			'Login Security'                       => 'login-security/login-security.php',
151
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
152
			'Wordfence Security'                   => 'wordfence/wordfence.php',
153
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
154
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
155
		),
156
		'random-redirect'   => array(
157
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
158
		),
159
		'related-posts'     => array(
160
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
161
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
162
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
163
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
164
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
165
			'outbrain'                             => 'outbrain/outbrain.php',
166
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
167
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
168
		),
169
		'sharedaddy'        => array(
170
			'AddThis'                              => 'addthis/addthis_social_widget.php',
171
			'Add To Any'                           => 'add-to-any/add-to-any.php',
172
			'ShareThis'                            => 'share-this/sharethis.php',
173
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
174
		),
175
		'seo-tools' => array(
176
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
177
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
178
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
179
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
180
		),
181
		'verification-tools' => array(
182
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
183
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
184
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
185
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
186
		),
187
		'widget-visibility' => array(
188
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
189
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
190
		),
191
		'sitemaps' => array(
192
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
193
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
194
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
195
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
196
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
197
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
198
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
199
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
200
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
201
			'Sitemap'                              => 'sitemap/sitemap.php',
202
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
203
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
204
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
205
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
206
		),
207
		'lazy-images' => array(
208
			'Lazy Load'              => 'lazy-load/lazy-load.php',
209
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
210
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
211
		),
212
	);
213
214
	/**
215
	 * Plugins for which we turn off our Facebook OG Tags implementation.
216
	 *
217
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
218
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
219
	 *
220
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
221
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
222
	 */
223
	private $open_graph_conflicting_plugins = array(
224
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
225
		                                                         // 2 Click Social Media Buttons
226
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
227
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
228
		'autodescription/autodescription.php',                   // The SEO Framework
229
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
230
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
231
		                                                         // Open Graph Meta Tags by Heateor
232
		'facebook/facebook.php',                                 // Facebook (official plugin)
233
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
234
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
235
		                                                         // Facebook Featured Image & OG Meta Tags
236
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
237
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
238
		                                                         // Facebook Open Graph Meta Tags for WordPress
239
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
240
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
241
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
242
		                                                         // Fedmich's Facebook Open Graph Meta
243
		'network-publisher/networkpub.php',                      // Network Publisher
244
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
245
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
246
		                                                         // NextScripts SNAP
247
		'og-tags/og-tags.php',                                   // OG Tags
248
		'opengraph/opengraph.php',                               // Open Graph
249
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
250
		                                                         // Open Graph Protocol Framework
251
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
252
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
253
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
254
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
255
		'sharepress/sharepress.php',                             // SharePress
256
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
257
		'social-discussions/social-discussions.php',             // Social Discussions
258
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
259
		'socialize/socialize.php',                               // Socialize
260
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
261
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
262
		                                                         // Tweet, Like, Google +1 and Share
263
		'wordbooker/wordbooker.php',                             // Wordbooker
264
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
265
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
266
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
267
		                                                         // WP Facebook Like Send & Open Graph Meta
268
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
269
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
270
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
271
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
272
	);
273
274
	/**
275
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
276
	 */
277
	private $twitter_cards_conflicting_plugins = array(
278
	//	'twitter/twitter.php',                       // The official one handles this on its own.
279
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
280
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
281
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
282
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
283
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
284
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
285
		'twitter-cards/twitter-cards.php',           // Twitter Cards
286
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
287
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
288
	);
289
290
	/**
291
	 * Message to display in admin_notice
292
	 * @var string
293
	 */
294
	public $message = '';
295
296
	/**
297
	 * Error to display in admin_notice
298
	 * @var string
299
	 */
300
	public $error = '';
301
302
	/**
303
	 * Modules that need more privacy description.
304
	 * @var string
305
	 */
306
	public $privacy_checks = '';
307
308
	/**
309
	 * Stats to record once the page loads
310
	 *
311
	 * @var array
312
	 */
313
	public $stats = array();
314
315
	/**
316
	 * Jetpack_Sync object
317
	 */
318
	public $sync;
319
320
	/**
321
	 * Verified data for JSON authorization request
322
	 */
323
	public $json_api_authorization_request = array();
324
325
	/**
326
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
327
	 */
328
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
329
330
	/**
331
	 * Holds the singleton instance of this class
332
	 * @since 2.3.3
333
	 * @var Jetpack
334
	 */
335
	static $instance = false;
336
337
	/**
338
	 * Singleton
339
	 * @static
340
	 */
341
	public static function init() {
342
		if ( ! self::$instance ) {
343
			self::$instance = new Jetpack;
344
345
			self::$instance->plugin_upgrade();
346
		}
347
348
		return self::$instance;
349
	}
350
351
	/**
352
	 * Must never be called statically
353
	 */
354
	function plugin_upgrade() {
355
		if ( Jetpack::is_active() ) {
356
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
357
			if ( JETPACK__VERSION != $version ) {
358
				// Prevent multiple upgrades at once - only a single process should trigger
359
				// an upgrade to avoid stampedes
360
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
361
					return;
362
				}
363
364
				// Set a short lock to prevent multiple instances of the upgrade
365
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
366
367
				// check which active modules actually exist and remove others from active_modules list
368
				$unfiltered_modules = Jetpack::get_active_modules();
369
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
370
				if ( array_diff( $unfiltered_modules, $modules ) ) {
371
					Jetpack::update_active_modules( $modules );
372
				}
373
374
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
375
376
				// Upgrade to 4.3.0
377
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
378
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
379
				}
380
381
				// Make sure Markdown for posts gets turned back on
382
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
383
					update_option( 'wpcom_publish_posts_with_markdown', true );
384
				}
385
386
				if ( did_action( 'wp_loaded' ) ) {
387
					self::upgrade_on_load();
388
				} else {
389
					add_action(
390
						'wp_loaded',
391
						array( __CLASS__, 'upgrade_on_load' )
392
					);
393
				}
394
			}
395
		}
396
	}
397
398
	/**
399
	 * Runs upgrade routines that need to have modules loaded.
400
	 */
401
	static function upgrade_on_load() {
402
403
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
404
		// This can happen in case Jetpack has been just upgraded and is
405
		// being initialized late during the page load. In this case we wait
406
		// until the next proper admin page load with Jetpack active.
407
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
408
			delete_transient( self::$plugin_upgrade_lock_key );
409
410
			return;
411
		}
412
413
		Jetpack::maybe_set_version_option();
414
415
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
416
			Jetpack_Widget_Conditions::migrate_post_type_rules();
417
		}
418
419
		if (
420
			class_exists( 'Jetpack_Sitemap_Manager' )
421
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
422
		) {
423
			do_action( 'jetpack_sitemaps_purge_data' );
424
		}
425
426
		delete_transient( self::$plugin_upgrade_lock_key );
427
	}
428
429
	static function activate_manage( ) {
430
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
431
			self::activate_module( 'manage', false, false );
432
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
433
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
434
		}
435
	}
436
437
	static function update_active_modules( $modules ) {
438
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
439
440
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
441
442
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
443
			$new_active_modules = array_diff( $modules, $current_modules );
444
			foreach( $new_active_modules as $module ) {
445
				/**
446
				 * Fires when a specific module is activated.
447
				 *
448
				 * @since 1.9.0
449
				 *
450
				 * @param string $module Module slug.
451
				 * @param boolean $success whether the module was activated. @since 4.2
452
				 */
453
				do_action( 'jetpack_activate_module', $module, $success );
454
455
				/**
456
				 * Fires when a module is activated.
457
				 * The dynamic part of the filter, $module, is the module slug.
458
				 *
459
				 * @since 1.9.0
460
				 *
461
				 * @param string $module Module slug.
462
				 */
463
				do_action( "jetpack_activate_module_$module", $module );
464
			}
465
466
			$new_deactive_modules = array_diff( $current_modules, $modules );
467
			foreach( $new_deactive_modules as $module ) {
468
				/**
469
				 * Fired after a module has been deactivated.
470
				 *
471
				 * @since 4.2.0
472
				 *
473
				 * @param string $module Module slug.
474
				 * @param boolean $success whether the module was deactivated.
475
				 */
476
				do_action( 'jetpack_deactivate_module', $module, $success );
477
				/**
478
				 * Fires when a module is deactivated.
479
				 * The dynamic part of the filter, $module, is the module slug.
480
				 *
481
				 * @since 1.9.0
482
				 *
483
				 * @param string $module Module slug.
484
				 */
485
				do_action( "jetpack_deactivate_module_$module", $module );
486
			}
487
		}
488
489
		return $success;
490
	}
491
492
	static function delete_active_modules() {
493
		self::update_active_modules( array() );
494
	}
495
496
	/**
497
	 * Constructor.  Initializes WordPress hooks
498
	 */
499
	private function __construct() {
500
		/*
501
		 * Check for and alert any deprecated hooks
502
		 */
503
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
504
505
		/*
506
		 * Enable enhanced handling of previewing sites in Calypso
507
		 */
508
		if ( Jetpack::is_active() ) {
509
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
510
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
511
		}
512
513
		/*
514
		 * Load things that should only be in Network Admin.
515
		 *
516
		 * For now blow away everything else until a more full
517
		 * understanding of what is needed at the network level is
518
		 * available
519
		 */
520
		if( is_multisite() ) {
521
			Jetpack_Network::init();
522
		}
523
524
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
525
526
		// Unlink user before deleting the user from .com
527
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
528
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
529
530
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
531
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
532
533
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
534
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
535
536
			$this->require_jetpack_authentication();
537
538
			if ( Jetpack::is_active() ) {
539
				// Hack to preserve $HTTP_RAW_POST_DATA
540
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
541
542
				$signed = $this->verify_xml_rpc_signature();
543
				if ( $signed && ! is_wp_error( $signed ) ) {
544
					// The actual API methods.
545
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
546
				} else {
547
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
548
					// active Jetpack connection, so that additional users can link their account.
549
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
550
				}
551
			} else {
552
				// The bootstrap API methods.
553
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
554
			}
555
556
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
557
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
558
		} elseif (
559
			is_admin() &&
560
			isset( $_POST['action'] ) && (
561
				'jetpack_upload_file' == $_POST['action'] ||
562
				'jetpack_update_file' == $_POST['action']
563
			)
564
		) {
565
			$this->require_jetpack_authentication();
566
			$this->add_remote_request_handlers();
567
		} else {
568
			if ( Jetpack::is_active() ) {
569
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
570
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
571
			}
572
		}
573
574
		if ( Jetpack::is_active() ) {
575
			Jetpack_Heartbeat::init();
576
		}
577
578
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
579
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
580
581
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
582
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
583
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
584
		}
585
586
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
587
588
		add_action( 'admin_init', array( $this, 'admin_init' ) );
589
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
590
591
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
592
593
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
594
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
595
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
596
597
		// returns HTTPS support status
598
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
599
600
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
601
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
602
603
		// JITM AJAX callback function
604
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
605
606
		// Universal ajax callback for all tracking events triggered via js
607
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
608
609
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
610
611
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
612
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
613
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
614
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
615
616
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
617
618
		/**
619
		 * These actions run checks to load additional files.
620
		 * They check for external files or plugins, so they need to run as late as possible.
621
		 */
622
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
623
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
624
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
625
626
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
627
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
628
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
629
630
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
631
632
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
633
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
634
635
		// A filter to control all just in time messages
636
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
637
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
638
639
		// If enabled, point edit post and page links to Calypso instead of WP-Admin.
640
		// We should make sure to only do this for front end links.
641
		if ( Jetpack_Options::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
642
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_links_to_calypso' ), 1, 2 );
643
		}
644
645
		// Update the Jetpack plan from API on heartbeats
646
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
647
648
		/**
649
		 * This is the hack to concatinate all css files into one.
650
		 * For description and reasoning see the implode_frontend_css method
651
		 *
652
		 * Super late priority so we catch all the registered styles
653
		 */
654
		if( !is_admin() ) {
655
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
656
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
657
		}
658
659
		/**
660
		 * These are sync actions that we need to keep track of for jitms
661
		 */
662
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
663
664
		// Actually push the stats on shutdown.
665
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
666
			add_action( 'shutdown', array( $this, 'push_stats' ) );
667
		}
668
	}
669
670
	function point_edit_links_to_calypso( $default_url, $post_id ) {
671
		$post = get_post( $post_id );
672
673
		if ( empty( $post ) ) {
674
			return $default_url;
675
		}
676
677
		$post_type = $post->post_type;
678
679
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
680
		// https://en.support.wordpress.com/custom-post-types/
681
		$allowed_post_types = array(
682
			'post' => 'post',
683
			'page' => 'page',
684
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
685
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
686
		);
687
688
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
689
			return $default_url;
690
		}
691
692
		$path_prefix = $allowed_post_types[ $post_type ];
693
694
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
695
696
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
697
	}
698
699
	function jetpack_track_last_sync_callback( $params ) {
700
		/**
701
		 * Filter to turn off jitm caching
702
		 *
703
		 * @since 5.4.0
704
		 *
705
		 * @param bool false Whether to cache just in time messages
706
		 */
707
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
708
			return $params;
709
		}
710
711
		if ( is_array( $params ) && isset( $params[0] ) ) {
712
			$option = $params[0];
713
			if ( 'active_plugins' === $option ) {
714
				// use the cache if we can, but not terribly important if it gets evicted
715
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
716
			}
717
		}
718
719
		return $params;
720
	}
721
722
	function jetpack_connection_banner_callback() {
723
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
724
725
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
726
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
727
			wp_send_json_success();
728
		}
729
730
		wp_die();
731
	}
732
733
	function jetpack_admin_ajax_tracks_callback() {
734
		// Check for nonce
735
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
736
			wp_die( 'Permissions check failed.' );
737
		}
738
739
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
740
			wp_die( 'No valid event name or type.' );
741
		}
742
743
		$tracks_data = array();
744
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
745
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
746
				$tracks_data = $_REQUEST['tracksEventProp'];
747
			} else {
748
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
749
			}
750
		}
751
752
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
753
		wp_send_json_success();
754
		wp_die();
755
	}
756
757
	/**
758
	 * The callback for the JITM ajax requests.
759
	 */
760
	function jetpack_jitm_ajax_callback() {
761
		// Check for nonce
762
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
763
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
764
		}
765
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
766
			$module_slug = $_REQUEST['jitmModule'];
767
			Jetpack::log( 'activate', $module_slug );
768
			Jetpack::activate_module( $module_slug, false, false );
769
			Jetpack::state( 'message', 'no_message' );
770
771
			//A Jetpack module is being activated through a JITM, track it
772
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
773
			$this->do_stats( 'server_side' );
774
775
			wp_send_json_success();
776
		}
777
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
778
			// get the hide_jitm options array
779
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
780
			$module_slug = $_REQUEST['jitmModule'];
781
782
			if( ! $jetpack_hide_jitm ) {
783
				$jetpack_hide_jitm = array(
784
					$module_slug => 'hide'
785
				);
786
			} else {
787
				$jetpack_hide_jitm[$module_slug] = 'hide';
788
			}
789
790
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
791
792
			//jitm is being dismissed forever, track it
793
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
794
			$this->do_stats( 'server_side' );
795
796
			wp_send_json_success();
797
		}
798 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
799
			$module_slug = $_REQUEST['jitmModule'];
800
801
			// User went to WordPress.com, track this
802
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
803
			$this->do_stats( 'server_side' );
804
805
			wp_send_json_success();
806
		}
807 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
808
			$track = $_REQUEST['jitmModule'];
809
810
			// User is viewing JITM, track it.
811
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
812
			$this->do_stats( 'server_side' );
813
814
			wp_send_json_success();
815
		}
816
	}
817
818
	/**
819
	 * If there are any stats that need to be pushed, but haven't been, push them now.
820
	 */
821
	function push_stats() {
822
		if ( ! empty( $this->stats ) ) {
823
			$this->do_stats( 'server_side' );
824
		}
825
	}
826
827
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
828
		switch( $cap ) {
829
			case 'jetpack_connect' :
830
			case 'jetpack_reconnect' :
831
				if ( Jetpack::is_development_mode() ) {
832
					$caps = array( 'do_not_allow' );
833
					break;
834
				}
835
				/**
836
				 * Pass through. If it's not development mode, these should match disconnect.
837
				 * Let users disconnect if it's development mode, just in case things glitch.
838
				 */
839
			case 'jetpack_disconnect' :
840
				/**
841
				 * In multisite, can individual site admins manage their own connection?
842
				 *
843
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
844
				 */
845
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
846
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
847
						/**
848
						 * We need to update the option name -- it's terribly unclear which
849
						 * direction the override goes.
850
						 *
851
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
852
						 */
853
						$caps = array( 'do_not_allow' );
854
						break;
855
					}
856
				}
857
858
				$caps = array( 'manage_options' );
859
				break;
860
			case 'jetpack_manage_modules' :
861
			case 'jetpack_activate_modules' :
862
			case 'jetpack_deactivate_modules' :
863
				$caps = array( 'manage_options' );
864
				break;
865
			case 'jetpack_configure_modules' :
866
				$caps = array( 'manage_options' );
867
				break;
868
			case 'jetpack_network_admin_page':
869
			case 'jetpack_network_settings_page':
870
				$caps = array( 'manage_network_plugins' );
871
				break;
872
			case 'jetpack_network_sites_page':
873
				$caps = array( 'manage_sites' );
874
				break;
875
			case 'jetpack_admin_page' :
876
				if ( Jetpack::is_development_mode() ) {
877
					$caps = array( 'manage_options' );
878
					break;
879
				} else {
880
					$caps = array( 'read' );
881
				}
882
				break;
883
			case 'jetpack_connect_user' :
884
				if ( Jetpack::is_development_mode() ) {
885
					$caps = array( 'do_not_allow' );
886
					break;
887
				}
888
				$caps = array( 'read' );
889
				break;
890
		}
891
		return $caps;
892
	}
893
894
	function require_jetpack_authentication() {
895
		// Don't let anyone authenticate
896
		$_COOKIE = array();
897
		remove_all_filters( 'authenticate' );
898
		remove_all_actions( 'wp_login_failed' );
899
900
		if ( Jetpack::is_active() ) {
901
			// Allow Jetpack authentication
902
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
903
		}
904
	}
905
906
	/**
907
	 * Load language files
908
	 * @action plugins_loaded
909
	 */
910
	public static function plugin_textdomain() {
911
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
912
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
913
	}
914
915
	/**
916
	 * Register assets for use in various modules and the Jetpack admin page.
917
	 *
918
	 * @uses wp_script_is, wp_register_script, plugins_url
919
	 * @action wp_loaded
920
	 * @return null
921
	 */
922
	public function register_assets() {
923 View Code Duplication
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
924
			wp_register_script( 'spin', plugins_url( '_inc/build/spin.min.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
925
		}
926
927 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
928
			wp_register_script( 'jquery.spin', plugins_url( '_inc/build/jquery.spin.min.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
929
		}
930
931 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
932
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/build/gallery-settings.min.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
933
		}
934
935 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
936
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/build/twitter-timeline.min.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
937
		}
938
939
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
940
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/build/facebook-embed.min.js', __FILE__ ), array( 'jquery' ), null, true );
941
942
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
943
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
944
			if ( ! is_numeric( $fb_app_id ) ) {
945
				$fb_app_id = '';
946
			}
947
			wp_localize_script(
948
				'jetpack-facebook-embed',
949
				'jpfbembed',
950
				array(
951
					'appid' => $fb_app_id,
952
					'locale' => $this->get_locale(),
953
				)
954
			);
955
		}
956
957
		/**
958
		 * As jetpack_register_genericons is by default fired off a hook,
959
		 * the hook may have already fired by this point.
960
		 * So, let's just trigger it manually.
961
		 */
962
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
963
		jetpack_register_genericons();
964
965
		/**
966
		 * Register the social logos
967
		 */
968
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
969
		jetpack_register_social_logos();
970
971 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
972
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
973
	}
974
975
	/**
976
	 * Guess locale from language code.
977
	 *
978
	 * @param string $lang Language code.
979
	 * @return string|bool
980
	 */
981
	function guess_locale_from_lang( $lang ) {
982
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
983
			return 'en_US';
984
		}
985
986 View Code Duplication
		if ( ! class_exists( 'GP_Locales' ) ) {
987
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
988
				return false;
989
			}
990
991
			require JETPACK__GLOTPRESS_LOCALES_PATH;
992
		}
993
994
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
995
			// WP.com: get_locale() returns 'it'
996
			$locale = GP_Locales::by_slug( $lang );
997
		} else {
998
			// Jetpack: get_locale() returns 'it_IT';
999
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1000
		}
1001
1002
		if ( ! $locale ) {
1003
			return false;
1004
		}
1005
1006
		if ( empty( $locale->facebook_locale ) ) {
1007
			if ( empty( $locale->wp_locale ) ) {
1008
				return false;
1009
			} else {
1010
				// Facebook SDK is smart enough to fall back to en_US if a
1011
				// locale isn't supported. Since supported Facebook locales
1012
				// can fall out of sync, we'll attempt to use the known
1013
				// wp_locale value and rely on said fallback.
1014
				return $locale->wp_locale;
1015
			}
1016
		}
1017
1018
		return $locale->facebook_locale;
1019
	}
1020
1021
	/**
1022
	 * Get the locale.
1023
	 *
1024
	 * @return string|bool
1025
	 */
1026
	function get_locale() {
1027
		$locale = $this->guess_locale_from_lang( get_locale() );
1028
1029
		if ( ! $locale ) {
1030
			$locale = 'en_US';
1031
		}
1032
1033
		return $locale;
1034
	}
1035
1036
	/**
1037
	 * Device Pixels support
1038
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1039
	 */
1040
	function devicepx() {
1041
		if ( Jetpack::is_active() ) {
1042
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1043
		}
1044
	}
1045
1046
	/**
1047
	 * Return the network_site_url so that .com knows what network this site is a part of.
1048
	 * @param  bool $option
1049
	 * @return string
1050
	 */
1051
	public function jetpack_main_network_site_option( $option ) {
1052
		return network_site_url();
1053
	}
1054
	/**
1055
	 * Network Name.
1056
	 */
1057
	static function network_name( $option = null ) {
1058
		global $current_site;
1059
		return $current_site->site_name;
1060
	}
1061
	/**
1062
	 * Does the network allow new user and site registrations.
1063
	 * @return string
1064
	 */
1065
	static function network_allow_new_registrations( $option = null ) {
1066
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1067
	}
1068
	/**
1069
	 * Does the network allow admins to add new users.
1070
	 * @return boolian
1071
	 */
1072
	static function network_add_new_users( $option = null ) {
1073
		return (bool) get_site_option( 'add_new_users' );
1074
	}
1075
	/**
1076
	 * File upload psace left per site in MB.
1077
	 *  -1 means NO LIMIT.
1078
	 * @return number
1079
	 */
1080
	static function network_site_upload_space( $option = null ) {
1081
		// value in MB
1082
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1083
	}
1084
1085
	/**
1086
	 * Network allowed file types.
1087
	 * @return string
1088
	 */
1089
	static function network_upload_file_types( $option = null ) {
1090
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1091
	}
1092
1093
	/**
1094
	 * Maximum file upload size set by the network.
1095
	 * @return number
1096
	 */
1097
	static function network_max_upload_file_size( $option = null ) {
1098
		// value in KB
1099
		return get_site_option( 'fileupload_maxk', 300 );
1100
	}
1101
1102
	/**
1103
	 * Lets us know if a site allows admins to manage the network.
1104
	 * @return array
1105
	 */
1106
	static function network_enable_administration_menus( $option = null ) {
1107
		return get_site_option( 'menu_items' );
1108
	}
1109
1110
	/**
1111
	 * If a user has been promoted to or demoted from admin, we need to clear the
1112
	 * jetpack_other_linked_admins transient.
1113
	 *
1114
	 * @since 4.3.2
1115
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1116
	 *
1117
	 * @param int    $user_id   The user ID whose role changed.
1118
	 * @param string $role      The new role.
1119
	 * @param array  $old_roles An array of the user's previous roles.
1120
	 */
1121
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1122
		if ( 'administrator' == $role
1123
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1124
			|| is_null( $old_roles )
1125
		) {
1126
			delete_transient( 'jetpack_other_linked_admins' );
1127
		}
1128
	}
1129
1130
	/**
1131
	 * Checks to see if there are any other users available to become primary
1132
	 * Users must both:
1133
	 * - Be linked to wpcom
1134
	 * - Be an admin
1135
	 *
1136
	 * @return mixed False if no other users are linked, Int if there are.
1137
	 */
1138
	static function get_other_linked_admins() {
1139
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1140
1141
		if ( false === $other_linked_users ) {
1142
			$admins = get_users( array( 'role' => 'administrator' ) );
1143
			if ( count( $admins ) > 1 ) {
1144
				$available = array();
1145
				foreach ( $admins as $admin ) {
1146
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1147
						$available[] = $admin->ID;
1148
					}
1149
				}
1150
1151
				$count_connected_admins = count( $available );
1152
				if ( count( $available ) > 1 ) {
1153
					$other_linked_users = $count_connected_admins;
1154
				} else {
1155
					$other_linked_users = 0;
1156
				}
1157
			} else {
1158
				$other_linked_users = 0;
1159
			}
1160
1161
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1162
		}
1163
1164
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1165
	}
1166
1167
	/**
1168
	 * Return whether we are dealing with a multi network setup or not.
1169
	 * The reason we are type casting this is because we want to avoid the situation where
1170
	 * the result is false since when is_main_network_option return false it cases
1171
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1172
	 * database which could be set to anything as opposed to what this function returns.
1173
	 * @param  bool  $option
1174
	 *
1175
	 * @return boolean
1176
	 */
1177
	public function is_main_network_option( $option ) {
1178
		// return '1' or ''
1179
		return (string) (bool) Jetpack::is_multi_network();
1180
	}
1181
1182
	/**
1183
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1184
	 *
1185
	 * @param  string  $option
1186
	 * @return boolean
1187
	 */
1188
	public function is_multisite( $option ) {
1189
		return (string) (bool) is_multisite();
1190
	}
1191
1192
	/**
1193
	 * Implemented since there is no core is multi network function
1194
	 * Right now there is no way to tell if we which network is the dominant network on the system
1195
	 *
1196
	 * @since  3.3
1197
	 * @return boolean
1198
	 */
1199
	public static function is_multi_network() {
1200
		global  $wpdb;
1201
1202
		// if we don't have a multi site setup no need to do any more
1203
		if ( ! is_multisite() ) {
1204
			return false;
1205
		}
1206
1207
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1208
		if ( $num_sites > 1 ) {
1209
			return true;
1210
		} else {
1211
			return false;
1212
		}
1213
	}
1214
1215
	/**
1216
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1217
	 * @return null
1218
	 */
1219
	function update_jetpack_main_network_site_option() {
1220
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1221
	}
1222
	/**
1223
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1224
	 *
1225
	 */
1226
	function update_jetpack_network_settings() {
1227
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1228
		// Only sync this info for the main network site.
1229
	}
1230
1231
	/**
1232
	 * Get back if the current site is single user site.
1233
	 *
1234
	 * @return bool
1235
	 */
1236
	public static function is_single_user_site() {
1237
		global $wpdb;
1238
1239 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1240
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1241
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1242
		}
1243
		return 1 === (int) $some_users;
1244
	}
1245
1246
	/**
1247
	 * Returns true if the site has file write access false otherwise.
1248
	 * @return string ( '1' | '0' )
1249
	 **/
1250
	public static function file_system_write_access() {
1251
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1252
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1253
		}
1254
1255
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1256
1257
		$filesystem_method = get_filesystem_method();
1258
		if ( $filesystem_method === 'direct' ) {
1259
			return 1;
1260
		}
1261
1262
		ob_start();
1263
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1264
		ob_end_clean();
1265
		if ( $filesystem_credentials_are_stored ) {
1266
			return 1;
1267
		}
1268
		return 0;
1269
	}
1270
1271
	/**
1272
	 * Finds out if a site is using a version control system.
1273
	 * @return string ( '1' | '0' )
1274
	 **/
1275
	public static function is_version_controlled() {
1276
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1277
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1278
	}
1279
1280
	/**
1281
	 * Determines whether the current theme supports featured images or not.
1282
	 * @return string ( '1' | '0' )
1283
	 */
1284
	public static function featured_images_enabled() {
1285
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1286
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1287
	}
1288
1289
	/**
1290
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1291
	 *
1292
	 * @deprecated 4.7 use get_avatar_url instead.
1293
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1294
	 * @param int $size Size of the avatar image
1295
	 * @param string $default URL to a default image to use if no avatar is available
1296
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1297
	 *
1298
	 * @return array
1299
	 */
1300
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1301
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1302
		return get_avatar_url( $id_or_email, array(
1303
			'size' => $size,
1304
			'default' => $default,
1305
			'force_default' => $force_display,
1306
		) );
1307
	}
1308
1309
	/**
1310
	 * jetpack_updates is saved in the following schema:
1311
	 *
1312
	 * array (
1313
	 *      'plugins'                       => (int) Number of plugin updates available.
1314
	 *      'themes'                        => (int) Number of theme updates available.
1315
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1316
	 *      'translations'                  => (int) Number of translation updates available.
1317
	 *      'total'                         => (int) Total of all available updates.
1318
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1319
	 * )
1320
	 * @return array
1321
	 */
1322
	public static function get_updates() {
1323
		$update_data = wp_get_update_data();
1324
1325
		// Stores the individual update counts as well as the total count.
1326
		if ( isset( $update_data['counts'] ) ) {
1327
			$updates = $update_data['counts'];
1328
		}
1329
1330
		// If we need to update WordPress core, let's find the latest version number.
1331 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1332
			$cur = get_preferred_from_update_core();
1333
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1334
				$updates['wp_update_version'] = $cur->current;
1335
			}
1336
		}
1337
		return isset( $updates ) ? $updates : array();
1338
	}
1339
1340
	public static function get_update_details() {
1341
		$update_details = array(
1342
			'update_core' => get_site_transient( 'update_core' ),
1343
			'update_plugins' => get_site_transient( 'update_plugins' ),
1344
			'update_themes' => get_site_transient( 'update_themes' ),
1345
		);
1346
		return $update_details;
1347
	}
1348
1349
	public static function refresh_update_data() {
1350
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1351
1352
	}
1353
1354
	public static function refresh_theme_data() {
1355
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1356
	}
1357
1358
	/**
1359
	 * Is Jetpack active?
1360
	 */
1361
	public static function is_active() {
1362
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1363
	}
1364
1365
	/**
1366
	 * Make an API call to WordPress.com for plan status
1367
	 *
1368
	 * @uses Jetpack_Options::get_option()
1369
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1370
	 * @uses update_option()
1371
	 *
1372
	 * @access public
1373
	 * @static
1374
	 *
1375
	 * @return bool True if plan is updated, false if no update
1376
	 */
1377
	public static function refresh_active_plan_from_wpcom() {
1378
		// Make the API request
1379
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1380
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1381
1382
		// Bail if there was an error or malformed response
1383
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1384
			return false;
1385
		}
1386
1387
		// Decode the results
1388
		$results = json_decode( $response['body'], true );
1389
1390
		// Bail if there were no results or plan details returned
1391
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1392
			return false;
1393
		}
1394
1395
		// Store the option and return true if updated
1396
		return update_option( 'jetpack_active_plan', $results['plan'] );
1397
	}
1398
1399
	/**
1400
	 * Get the plan that this Jetpack site is currently using
1401
	 *
1402
	 * @uses get_option()
1403
	 *
1404
	 * @access public
1405
	 * @static
1406
	 *
1407
	 * @return array Active Jetpack plan details
1408
	 */
1409
	public static function get_active_plan() {
1410
		$plan = get_option( 'jetpack_active_plan', array() );
1411
1412
		// Set the default options
1413
		if ( empty( $plan ) || ( isset( $plan['product_slug'] ) && 'jetpack_free' === $plan['product_slug'] ) ) {
1414
			$plan = wp_parse_args( $plan, array(
1415
				'product_slug' => 'jetpack_free',
1416
				'supports'     => array(),
1417
				'class'        => 'free',
1418
			) );
1419
		}
1420
1421
		// Define what paid modules are supported by personal plans
1422
		$personal_plans = array(
1423
			'jetpack_personal',
1424
			'jetpack_personal_monthly',
1425
			'personal-bundle',
1426
		);
1427
1428
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1429
			$plan['supports'] = array(
1430
				'akismet',
1431
			);
1432
			$plan['class'] = 'personal';
1433
		}
1434
1435
		// Define what paid modules are supported by premium plans
1436
		$premium_plans = array(
1437
			'jetpack_premium',
1438
			'jetpack_premium_monthly',
1439
			'value_bundle',
1440
		);
1441
1442
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1443
			$plan['supports'] = array(
1444
				'videopress',
1445
				'akismet',
1446
				'vaultpress',
1447
				'wordads',
1448
			);
1449
			$plan['class'] = 'premium';
1450
		}
1451
1452
		// Define what paid modules are supported by professional plans
1453
		$business_plans = array(
1454
			'jetpack_business',
1455
			'jetpack_business_monthly',
1456
			'business-bundle',
1457
		);
1458
1459
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1460
			$plan['supports'] = array(
1461
				'videopress',
1462
				'akismet',
1463
				'vaultpress',
1464
				'seo-tools',
1465
				'google-analytics',
1466
				'wordads',
1467
				'search',
1468
			);
1469
			$plan['class'] = 'business';
1470
		}
1471
1472
		// Make sure we have an array here in the event database data is stale
1473
		if ( ! isset( $plan['supports'] ) ) {
1474
			$plan['supports'] = array();
1475
		}
1476
1477
		return $plan;
1478
	}
1479
1480
	/**
1481
	 * Determine whether the active plan supports a particular feature
1482
	 *
1483
	 * @uses Jetpack::get_active_plan()
1484
	 *
1485
	 * @access public
1486
	 * @static
1487
	 *
1488
	 * @return bool True if plan supports feature, false if not
1489
	 */
1490
	public static function active_plan_supports( $feature ) {
1491
		$plan = Jetpack::get_active_plan();
1492
1493
		if ( in_array( $feature, $plan['supports'] ) ) {
1494
			return true;
1495
		}
1496
1497
		return false;
1498
	}
1499
1500
	/**
1501
	 * Is Jetpack in development (offline) mode?
1502
	 */
1503
	public static function is_development_mode() {
1504
		$development_mode = false;
1505
1506
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1507
			$development_mode = JETPACK_DEV_DEBUG;
1508
		} elseif ( $site_url = site_url() ) {
1509
			$development_mode = false === strpos( $site_url, '.' );
1510
		}
1511
1512
		/**
1513
		 * Filters Jetpack's development mode.
1514
		 *
1515
		 * @see https://jetpack.com/support/development-mode/
1516
		 *
1517
		 * @since 2.2.1
1518
		 *
1519
		 * @param bool $development_mode Is Jetpack's development mode active.
1520
		 */
1521
		return apply_filters( 'jetpack_development_mode', $development_mode );
1522
	}
1523
1524
	/**
1525
	* Get Jetpack development mode notice text and notice class.
1526
	*
1527
	* Mirrors the checks made in Jetpack::is_development_mode
1528
	*
1529
	*/
1530
	public static function show_development_mode_notice() {
1531
		if ( Jetpack::is_development_mode() ) {
1532
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1533
				$notice = sprintf(
1534
					/* translators: %s is a URL */
1535
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1536
					'https://jetpack.com/support/development-mode/'
1537
				);
1538
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1539
				$notice = sprintf(
1540
					/* translators: %s is a URL */
1541
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1542
					'https://jetpack.com/support/development-mode/'
1543
				);
1544
			} else {
1545
				$notice = sprintf(
1546
					/* translators: %s is a URL */
1547
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1548
					'https://jetpack.com/support/development-mode/'
1549
				);
1550
			}
1551
1552
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1553
		}
1554
1555
		// Throw up a notice if using a development version and as for feedback.
1556
		if ( Jetpack::is_development_version() ) {
1557
			/* translators: %s is a URL */
1558
			$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/' );
1559
1560
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1561
		}
1562
		// Throw up a notice if using staging mode
1563
		if ( Jetpack::is_staging_site() ) {
1564
			/* translators: %s is a URL */
1565
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1566
1567
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1568
		}
1569
	}
1570
1571
	/**
1572
	 * Whether Jetpack's version maps to a public release, or a development version.
1573
	 */
1574
	public static function is_development_version() {
1575
		/**
1576
		 * Allows filtering whether this is a development version of Jetpack.
1577
		 *
1578
		 * This filter is especially useful for tests.
1579
		 *
1580
		 * @since 4.3.0
1581
		 *
1582
		 * @param bool $development_version Is this a develoment version of Jetpack?
1583
		 */
1584
		return (bool) apply_filters(
1585
			'jetpack_development_version',
1586
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1587
		);
1588
	}
1589
1590
	/**
1591
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1592
	 */
1593
	public static function is_user_connected( $user_id = false ) {
1594
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1595
		if ( ! $user_id ) {
1596
			return false;
1597
		}
1598
1599
		return (bool) Jetpack_Data::get_access_token( $user_id );
1600
	}
1601
1602
	/**
1603
	 * Get the wpcom user data of the current|specified connected user.
1604
	 */
1605
	public static function get_connected_user_data( $user_id = null ) {
1606
		if ( ! $user_id ) {
1607
			$user_id = get_current_user_id();
1608
		}
1609
1610
		$transient_key = "jetpack_connected_user_data_$user_id";
1611
1612
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1613
			return $cached_user_data;
1614
		}
1615
1616
		Jetpack::load_xml_rpc_client();
1617
		$xml = new Jetpack_IXR_Client( array(
1618
			'user_id' => $user_id,
1619
		) );
1620
		$xml->query( 'wpcom.getUser' );
1621
		if ( ! $xml->isError() ) {
1622
			$user_data = $xml->getResponse();
1623
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1624
			return $user_data;
1625
		}
1626
1627
		return false;
1628
	}
1629
1630
	/**
1631
	 * Get the wpcom email of the current|specified connected user.
1632
	 */
1633 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1634
		if ( ! $user_id ) {
1635
			$user_id = get_current_user_id();
1636
		}
1637
		Jetpack::load_xml_rpc_client();
1638
		$xml = new Jetpack_IXR_Client( array(
1639
			'user_id' => $user_id,
1640
		) );
1641
		$xml->query( 'wpcom.getUserEmail' );
1642
		if ( ! $xml->isError() ) {
1643
			return $xml->getResponse();
1644
		}
1645
		return false;
1646
	}
1647
1648
	/**
1649
	 * Get the wpcom email of the master user.
1650
	 */
1651
	public static function get_master_user_email() {
1652
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1653
		if ( $master_user_id ) {
1654
			return self::get_connected_user_email( $master_user_id );
1655
		}
1656
		return '';
1657
	}
1658
1659
	function current_user_is_connection_owner() {
1660
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1661
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1662
	}
1663
1664
	/**
1665
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1666
	 */
1667
	function extra_oembed_providers() {
1668
		// Cloudup: https://dev.cloudup.com/#oembed
1669
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1670
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1671
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1672
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1673
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1674
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1675
	}
1676
1677
	/**
1678
	 * Synchronize connected user role changes
1679
	 */
1680
	function user_role_change( $user_id ) {
1681
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1682
		Jetpack_Sync_Users::user_role_change( $user_id );
1683
	}
1684
1685
	/**
1686
	 * Loads the currently active modules.
1687
	 */
1688
	public static function load_modules() {
1689
		if (
1690
			! self::is_active()
1691
			&& ! self::is_development_mode()
1692
			&& (
1693
				! is_multisite()
1694
				|| ! get_site_option( 'jetpack_protect_active' )
1695
			)
1696
		) {
1697
			return;
1698
		}
1699
1700
		$version = Jetpack_Options::get_option( 'version' );
1701 View Code Duplication
		if ( ! $version ) {
1702
			$version = $old_version = JETPACK__VERSION . ':' . time();
1703
			/** This action is documented in class.jetpack.php */
1704
			do_action( 'updating_jetpack_version', $version, false );
1705
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1706
		}
1707
		list( $version ) = explode( ':', $version );
1708
1709
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1710
1711
		$modules_data = array();
1712
1713
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1714
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1715
			$updated_modules = array();
1716
			foreach ( $modules as $module ) {
1717
				$modules_data[ $module ] = Jetpack::get_module( $module );
1718
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1719
					continue;
1720
				}
1721
1722
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1723
					continue;
1724
				}
1725
1726
				$updated_modules[] = $module;
1727
			}
1728
1729
			$modules = array_diff( $modules, $updated_modules );
1730
		}
1731
1732
		$is_development_mode = Jetpack::is_development_mode();
1733
1734
		foreach ( $modules as $index => $module ) {
1735
			// If we're in dev mode, disable modules requiring a connection
1736
			if ( $is_development_mode ) {
1737
				// Prime the pump if we need to
1738
				if ( empty( $modules_data[ $module ] ) ) {
1739
					$modules_data[ $module ] = Jetpack::get_module( $module );
1740
				}
1741
				// If the module requires a connection, but we're in local mode, don't include it.
1742
				if ( $modules_data[ $module ]['requires_connection'] ) {
1743
					continue;
1744
				}
1745
			}
1746
1747
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1748
				continue;
1749
			}
1750
1751
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1752
				unset( $modules[ $index ] );
1753
				self::update_active_modules( array_values( $modules ) );
1754
				continue;
1755
			}
1756
1757
			/**
1758
			 * Fires when a specific module is loaded.
1759
			 * The dynamic part of the hook, $module, is the module slug.
1760
			 *
1761
			 * @since 1.1.0
1762
			 */
1763
			do_action( 'jetpack_module_loaded_' . $module );
1764
		}
1765
1766
		/**
1767
		 * Fires when all the modules are loaded.
1768
		 *
1769
		 * @since 1.1.0
1770
		 */
1771
		do_action( 'jetpack_modules_loaded' );
1772
1773
		// 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.
1774
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1775
	}
1776
1777
	/**
1778
	 * Check if Jetpack's REST API compat file should be included
1779
	 * @action plugins_loaded
1780
	 * @return null
1781
	 */
1782
	public function check_rest_api_compat() {
1783
		/**
1784
		 * Filters the list of REST API compat files to be included.
1785
		 *
1786
		 * @since 2.2.5
1787
		 *
1788
		 * @param array $args Array of REST API compat files to include.
1789
		 */
1790
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1791
1792
		if ( function_exists( 'bbpress' ) )
1793
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1794
1795
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1796
			require_once $_jetpack_rest_api_compat_include;
1797
	}
1798
1799
	/**
1800
	 * Gets all plugins currently active in values, regardless of whether they're
1801
	 * traditionally activated or network activated.
1802
	 *
1803
	 * @todo Store the result in core's object cache maybe?
1804
	 */
1805
	public static function get_active_plugins() {
1806
		$active_plugins = (array) get_option( 'active_plugins', array() );
1807
1808
		if ( is_multisite() ) {
1809
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1810
			// whereas active_plugins stores them in the values.
1811
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1812
			if ( $network_plugins ) {
1813
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1814
			}
1815
		}
1816
1817
		sort( $active_plugins );
1818
1819
		return array_unique( $active_plugins );
1820
	}
1821
1822
	/**
1823
	 * Gets and parses additional plugin data to send with the heartbeat data
1824
	 *
1825
	 * @since 3.8.1
1826
	 *
1827
	 * @return array Array of plugin data
1828
	 */
1829
	public static function get_parsed_plugin_data() {
1830
		if ( ! function_exists( 'get_plugins' ) ) {
1831
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1832
		}
1833
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1834
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1835
		$active_plugins = Jetpack::get_active_plugins();
1836
1837
		$plugins = array();
1838
		foreach ( $all_plugins as $path => $plugin_data ) {
1839
			$plugins[ $path ] = array(
1840
					'is_active' => in_array( $path, $active_plugins ),
1841
					'file'      => $path,
1842
					'name'      => $plugin_data['Name'],
1843
					'version'   => $plugin_data['Version'],
1844
					'author'    => $plugin_data['Author'],
1845
			);
1846
		}
1847
1848
		return $plugins;
1849
	}
1850
1851
	/**
1852
	 * Gets and parses theme data to send with the heartbeat data
1853
	 *
1854
	 * @since 3.8.1
1855
	 *
1856
	 * @return array Array of theme data
1857
	 */
1858
	public static function get_parsed_theme_data() {
1859
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1860
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1861
1862
		$themes = array();
1863
		foreach ( $all_themes as $slug => $theme_data ) {
1864
			$theme_headers = array();
1865
			foreach ( $header_keys as $header_key ) {
1866
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1867
			}
1868
1869
			$themes[ $slug ] = array(
1870
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1871
					'slug' => $slug,
1872
					'theme_root' => $theme_data->get_theme_root_uri(),
1873
					'parent' => $theme_data->parent(),
1874
					'headers' => $theme_headers
1875
			);
1876
		}
1877
1878
		return $themes;
1879
	}
1880
1881
	/**
1882
	 * Checks whether a specific plugin is active.
1883
	 *
1884
	 * We don't want to store these in a static variable, in case
1885
	 * there are switch_to_blog() calls involved.
1886
	 */
1887
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1888
		return in_array( $plugin, self::get_active_plugins() );
1889
	}
1890
1891
	/**
1892
	 * Check if Jetpack's Open Graph tags should be used.
1893
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1894
	 *
1895
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1896
	 * @action plugins_loaded
1897
	 * @return null
1898
	 */
1899
	public function check_open_graph() {
1900
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1901
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1902
		}
1903
1904
		$active_plugins = self::get_active_plugins();
1905
1906
		if ( ! empty( $active_plugins ) ) {
1907
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1908
				if ( in_array( $plugin, $active_plugins ) ) {
1909
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1910
					break;
1911
				}
1912
			}
1913
		}
1914
1915
		/**
1916
		 * Allow the addition of Open Graph Meta Tags to all pages.
1917
		 *
1918
		 * @since 2.0.3
1919
		 *
1920
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1921
		 */
1922
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1923
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1924
		}
1925
	}
1926
1927
	/**
1928
	 * Check if Jetpack's Twitter tags should be used.
1929
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1930
	 *
1931
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1932
	 * @action plugins_loaded
1933
	 * @return null
1934
	 */
1935
	public function check_twitter_tags() {
1936
1937
		$active_plugins = self::get_active_plugins();
1938
1939
		if ( ! empty( $active_plugins ) ) {
1940
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1941
				if ( in_array( $plugin, $active_plugins ) ) {
1942
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1943
					break;
1944
				}
1945
			}
1946
		}
1947
1948
		/**
1949
		 * Allow Twitter Card Meta tags to be disabled.
1950
		 *
1951
		 * @since 2.6.0
1952
		 *
1953
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1954
		 */
1955
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1956
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1957
		}
1958
	}
1959
1960
	/**
1961
	 * Allows plugins to submit security reports.
1962
 	 *
1963
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1964
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1965
	 * @param array   $args         See definitions above
1966
	 */
1967
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1968
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1969
	}
1970
1971
/* Jetpack Options API */
1972
1973
	public static function get_option_names( $type = 'compact' ) {
1974
		return Jetpack_Options::get_option_names( $type );
1975
	}
1976
1977
	/**
1978
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1979
 	 *
1980
	 * @param string $name    Option name
1981
	 * @param mixed  $default (optional)
1982
	 */
1983
	public static function get_option( $name, $default = false ) {
1984
		return Jetpack_Options::get_option( $name, $default );
1985
	}
1986
1987
	/**
1988
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1989
 	 *
1990
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1991
	 * @param string $name  Option name
1992
	 * @param mixed  $value Option value
1993
	 */
1994
	public static function update_option( $name, $value ) {
1995
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1996
		return Jetpack_Options::update_option( $name, $value );
1997
	}
1998
1999
	/**
2000
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2001
 	 *
2002
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2003
	 * @param array $array array( option name => option value, ... )
2004
	 */
2005
	public static function update_options( $array ) {
2006
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2007
		return Jetpack_Options::update_options( $array );
2008
	}
2009
2010
	/**
2011
	 * Deletes the given option.  May be passed multiple option names as an array.
2012
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2013
	 *
2014
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2015
	 * @param string|array $names
2016
	 */
2017
	public static function delete_option( $names ) {
2018
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2019
		return Jetpack_Options::delete_option( $names );
2020
	}
2021
2022
	/**
2023
	 * Enters a user token into the user_tokens option
2024
	 *
2025
	 * @param int $user_id
2026
	 * @param string $token
2027
	 * return bool
2028
	 */
2029
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2030
		// not designed for concurrent updates
2031
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2032
		if ( ! is_array( $user_tokens ) )
2033
			$user_tokens = array();
2034
		$user_tokens[$user_id] = $token;
2035
		if ( $is_master_user ) {
2036
			$master_user = $user_id;
2037
			$options     = compact( 'user_tokens', 'master_user' );
2038
		} else {
2039
			$options = compact( 'user_tokens' );
2040
		}
2041
		return Jetpack_Options::update_options( $options );
2042
	}
2043
2044
	/**
2045
	 * Returns an array of all PHP files in the specified absolute path.
2046
	 * Equivalent to glob( "$absolute_path/*.php" ).
2047
	 *
2048
	 * @param string $absolute_path The absolute path of the directory to search.
2049
	 * @return array Array of absolute paths to the PHP files.
2050
	 */
2051
	public static function glob_php( $absolute_path ) {
2052
		if ( function_exists( 'glob' ) ) {
2053
			return glob( "$absolute_path/*.php" );
2054
		}
2055
2056
		$absolute_path = untrailingslashit( $absolute_path );
2057
		$files = array();
2058
		if ( ! $dir = @opendir( $absolute_path ) ) {
2059
			return $files;
2060
		}
2061
2062
		while ( false !== $file = readdir( $dir ) ) {
2063
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2064
				continue;
2065
			}
2066
2067
			$file = "$absolute_path/$file";
2068
2069
			if ( ! is_file( $file ) ) {
2070
				continue;
2071
			}
2072
2073
			$files[] = $file;
2074
		}
2075
2076
		closedir( $dir );
2077
2078
		return $files;
2079
	}
2080
2081
	public static function activate_new_modules( $redirect = false ) {
2082
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2083
			return;
2084
		}
2085
2086
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2087 View Code Duplication
		if ( ! $jetpack_old_version ) {
2088
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2089
			/** This action is documented in class.jetpack.php */
2090
			do_action( 'updating_jetpack_version', $version, false );
2091
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2092
		}
2093
2094
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2095
2096
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2097
			return;
2098
		}
2099
2100
		$active_modules     = Jetpack::get_active_modules();
2101
		$reactivate_modules = array();
2102
		foreach ( $active_modules as $active_module ) {
2103
			$module = Jetpack::get_module( $active_module );
2104
			if ( ! isset( $module['changed'] ) ) {
2105
				continue;
2106
			}
2107
2108
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2109
				continue;
2110
			}
2111
2112
			$reactivate_modules[] = $active_module;
2113
			Jetpack::deactivate_module( $active_module );
2114
		}
2115
2116
		$new_version = JETPACK__VERSION . ':' . time();
2117
		/** This action is documented in class.jetpack.php */
2118
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2119
		Jetpack_Options::update_options(
2120
			array(
2121
				'version'     => $new_version,
2122
				'old_version' => $jetpack_old_version,
2123
			)
2124
		);
2125
2126
		Jetpack::state( 'message', 'modules_activated' );
2127
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2128
2129
		if ( $redirect ) {
2130
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2131
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2132
				$page = $_GET['page'];
2133
			}
2134
2135
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2136
			exit;
2137
		}
2138
	}
2139
2140
	/**
2141
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2142
	 * Make sure to tuck away module "library" files in a sub-directory.
2143
	 */
2144
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2145
		static $modules = null;
2146
2147
		if ( ! isset( $modules ) ) {
2148
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2149
			// Use the cache if we're on the front-end and it's available...
2150
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2151
				$modules = $available_modules_option[ JETPACK__VERSION ];
2152
			} else {
2153
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2154
2155
				$modules = array();
2156
2157
				foreach ( $files as $file ) {
2158
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2159
						continue;
2160
					}
2161
2162
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2163
				}
2164
2165
				Jetpack_Options::update_option( 'available_modules', array(
2166
					JETPACK__VERSION => $modules,
2167
				) );
2168
			}
2169
		}
2170
2171
		/**
2172
		 * Filters the array of modules available to be activated.
2173
		 *
2174
		 * @since 2.4.0
2175
		 *
2176
		 * @param array $modules Array of available modules.
2177
		 * @param string $min_version Minimum version number required to use modules.
2178
		 * @param string $max_version Maximum version number required to use modules.
2179
		 */
2180
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2181
2182
		if ( ! $min_version && ! $max_version ) {
2183
			return array_keys( $mods );
2184
		}
2185
2186
		$r = array();
2187
		foreach ( $mods as $slug => $introduced ) {
2188
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2189
				continue;
2190
			}
2191
2192
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2193
				continue;
2194
			}
2195
2196
			$r[] = $slug;
2197
		}
2198
2199
		return $r;
2200
	}
2201
2202
	/**
2203
	 * Default modules loaded on activation.
2204
	 */
2205
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2206
		$return = array();
2207
2208
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2209
			$module_data = Jetpack::get_module( $module );
2210
2211
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2212
				case 'yes' :
2213
					$return[] = $module;
2214
					break;
2215
				case 'public' :
2216
					if ( Jetpack_Options::get_option( 'public' ) ) {
2217
						$return[] = $module;
2218
					}
2219
					break;
2220
				case 'no' :
2221
				default :
2222
					break;
2223
			}
2224
		}
2225
		/**
2226
		 * Filters the array of default modules.
2227
		 *
2228
		 * @since 2.5.0
2229
		 *
2230
		 * @param array $return Array of default modules.
2231
		 * @param string $min_version Minimum version number required to use modules.
2232
		 * @param string $max_version Maximum version number required to use modules.
2233
		 */
2234
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2235
	}
2236
2237
	/**
2238
	 * Checks activated modules during auto-activation to determine
2239
	 * if any of those modules are being deprecated.  If so, close
2240
	 * them out, and add any replacement modules.
2241
	 *
2242
	 * Runs at priority 99 by default.
2243
	 *
2244
	 * This is run late, so that it can still activate a module if
2245
	 * the new module is a replacement for another that the user
2246
	 * currently has active, even if something at the normal priority
2247
	 * would kibosh everything.
2248
	 *
2249
	 * @since 2.6
2250
	 * @uses jetpack_get_default_modules filter
2251
	 * @param array $modules
2252
	 * @return array
2253
	 */
2254
	function handle_deprecated_modules( $modules ) {
2255
		$deprecated_modules = array(
2256
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2257
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2258
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2259
		);
2260
2261
		// Don't activate SSO if they never completed activating WPCC.
2262
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2263
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2264
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2265
				$deprecated_modules['wpcc'] = null;
2266
			}
2267
		}
2268
2269
		foreach ( $deprecated_modules as $module => $replacement ) {
2270
			if ( Jetpack::is_module_active( $module ) ) {
2271
				self::deactivate_module( $module );
2272
				if ( $replacement ) {
2273
					$modules[] = $replacement;
2274
				}
2275
			}
2276
		}
2277
2278
		return array_unique( $modules );
2279
	}
2280
2281
	/**
2282
	 * Checks activated plugins during auto-activation to determine
2283
	 * if any of those plugins are in the list with a corresponding module
2284
	 * that is not compatible with the plugin. The module will not be allowed
2285
	 * to auto-activate.
2286
	 *
2287
	 * @since 2.6
2288
	 * @uses jetpack_get_default_modules filter
2289
	 * @param array $modules
2290
	 * @return array
2291
	 */
2292
	function filter_default_modules( $modules ) {
2293
2294
		$active_plugins = self::get_active_plugins();
2295
2296
		if ( ! empty( $active_plugins ) ) {
2297
2298
			// For each module we'd like to auto-activate...
2299
			foreach ( $modules as $key => $module ) {
2300
				// If there are potential conflicts for it...
2301
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2302
					// For each potential conflict...
2303
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2304
						// If that conflicting plugin is active...
2305
						if ( in_array( $plugin, $active_plugins ) ) {
2306
							// Remove that item from being auto-activated.
2307
							unset( $modules[ $key ] );
2308
						}
2309
					}
2310
				}
2311
			}
2312
		}
2313
2314
		return $modules;
2315
	}
2316
2317
	/**
2318
	 * Extract a module's slug from its full path.
2319
	 */
2320
	public static function get_module_slug( $file ) {
2321
		return str_replace( '.php', '', basename( $file ) );
2322
	}
2323
2324
	/**
2325
	 * Generate a module's path from its slug.
2326
	 */
2327
	public static function get_module_path( $slug ) {
2328
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2329
	}
2330
2331
	/**
2332
	 * Load module data from module file. Headers differ from WordPress
2333
	 * plugin headers to avoid them being identified as standalone
2334
	 * plugins on the WordPress plugins page.
2335
	 */
2336
	public static function get_module( $module ) {
2337
		$headers = array(
2338
			'name'                      => 'Module Name',
2339
			'description'               => 'Module Description',
2340
			'jumpstart_desc'            => 'Jumpstart Description',
2341
			'sort'                      => 'Sort Order',
2342
			'recommendation_order'      => 'Recommendation Order',
2343
			'introduced'                => 'First Introduced',
2344
			'changed'                   => 'Major Changes In',
2345
			'deactivate'                => 'Deactivate',
2346
			'free'                      => 'Free',
2347
			'requires_connection'       => 'Requires Connection',
2348
			'auto_activate'             => 'Auto Activate',
2349
			'module_tags'               => 'Module Tags',
2350
			'feature'                   => 'Feature',
2351
			'additional_search_queries' => 'Additional Search Queries',
2352
		);
2353
2354
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2355
2356
		$mod = Jetpack::get_file_data( $file, $headers );
2357
		if ( empty( $mod['name'] ) ) {
2358
			return false;
2359
		}
2360
2361
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2362
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2363
		$mod['deactivate']              = empty( $mod['deactivate'] );
2364
		$mod['free']                    = empty( $mod['free'] );
2365
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2366
2367
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2368
			$mod['auto_activate'] = 'No';
2369
		} else {
2370
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2371
		}
2372
2373
		if ( $mod['module_tags'] ) {
2374
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2375
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2376
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2377
		} else {
2378
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2379
		}
2380
2381
		if ( $mod['feature'] ) {
2382
			$mod['feature'] = explode( ',', $mod['feature'] );
2383
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2384
		} else {
2385
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2386
		}
2387
2388
		/**
2389
		 * Filters the feature array on a module.
2390
		 *
2391
		 * This filter allows you to control where each module is filtered: Recommended,
2392
		 * Jumpstart, and the default "Other" listing.
2393
		 *
2394
		 * @since 3.5.0
2395
		 *
2396
		 * @param array   $mod['feature'] The areas to feature this module:
2397
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2398
		 *     'Recommended' shows on the main Jetpack admin screen.
2399
		 *     'Other' should be the default if no other value is in the array.
2400
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2401
		 * @param array   $mod All the currently assembled module data.
2402
		 */
2403
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2404
2405
		/**
2406
		 * Filter the returned data about a module.
2407
		 *
2408
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2409
		 * so please be careful.
2410
		 *
2411
		 * @since 3.6.0
2412
		 *
2413
		 * @param array   $mod    The details of the requested module.
2414
		 * @param string  $module The slug of the module, e.g. sharedaddy
2415
		 * @param string  $file   The path to the module source file.
2416
		 */
2417
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2418
	}
2419
2420
	/**
2421
	 * Like core's get_file_data implementation, but caches the result.
2422
	 */
2423
	public static function get_file_data( $file, $headers ) {
2424
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2425
		$file_name = basename( $file );
2426
2427
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2428
2429
		$file_data_option = get_transient( $cache_key );
2430
2431
		if ( false === $file_data_option ) {
2432
			$file_data_option = array();
2433
		}
2434
2435
		$key           = md5( $file_name . serialize( $headers ) );
2436
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2437
2438
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2439
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2440
			return $file_data_option[ $key ];
2441
		}
2442
2443
		$data = get_file_data( $file, $headers );
2444
2445
		$file_data_option[ $key ] = $data;
2446
2447
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2448
2449
		return $data;
2450
	}
2451
2452
2453
	/**
2454
	 * Return translated module tag.
2455
	 *
2456
	 * @param string $tag Tag as it appears in each module heading.
2457
	 *
2458
	 * @return mixed
2459
	 */
2460
	public static function translate_module_tag( $tag ) {
2461
		return jetpack_get_module_i18n_tag( $tag );
2462
	}
2463
2464
	/**
2465
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2466
	 *
2467
	 * @since 3.9.2
2468
	 *
2469
	 * @param array $modules
2470
	 *
2471
	 * @return string|void
2472
	 */
2473
	public static function get_translated_modules( $modules ) {
2474
		foreach ( $modules as $index => $module ) {
2475
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2476
			if ( isset( $module['name'] ) ) {
2477
				$modules[ $index ]['name'] = $i18n_module['name'];
2478
			}
2479
			if ( isset( $module['description'] ) ) {
2480
				$modules[ $index ]['description'] = $i18n_module['description'];
2481
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2482
			}
2483
		}
2484
		return $modules;
2485
	}
2486
2487
	/**
2488
	 * Get a list of activated modules as an array of module slugs.
2489
	 */
2490
	public static function get_active_modules() {
2491
		$active = Jetpack_Options::get_option( 'active_modules' );
2492
2493
		if ( ! is_array( $active ) ) {
2494
			$active = array();
2495
		}
2496
2497
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2498
			$active[] = 'vaultpress';
2499
		} else {
2500
			$active = array_diff( $active, array( 'vaultpress' ) );
2501
		}
2502
2503
		//If protect is active on the main site of a multisite, it should be active on all sites.
2504
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2505
			$active[] = 'protect';
2506
		}
2507
2508
		return array_unique( $active );
2509
	}
2510
2511
	/**
2512
	 * Check whether or not a Jetpack module is active.
2513
	 *
2514
	 * @param string $module The slug of a Jetpack module.
2515
	 * @return bool
2516
	 *
2517
	 * @static
2518
	 */
2519
	public static function is_module_active( $module ) {
2520
		return in_array( $module, self::get_active_modules() );
2521
	}
2522
2523
	public static function is_module( $module ) {
2524
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2525
	}
2526
2527
	/**
2528
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2529
	 *
2530
	 * @param bool $catch True to start catching, False to stop.
2531
	 *
2532
	 * @static
2533
	 */
2534
	public static function catch_errors( $catch ) {
2535
		static $display_errors, $error_reporting;
2536
2537
		if ( $catch ) {
2538
			$display_errors  = @ini_set( 'display_errors', 1 );
2539
			$error_reporting = @error_reporting( E_ALL );
2540
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2541
		} else {
2542
			@ini_set( 'display_errors', $display_errors );
2543
			@error_reporting( $error_reporting );
2544
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2545
		}
2546
	}
2547
2548
	/**
2549
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2550
	 */
2551
	public static function catch_errors_on_shutdown() {
2552
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2553
	}
2554
2555
	/**
2556
	 * Rewrite any string to make paths easier to read.
2557
	 *
2558
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2559
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2560
	 *
2561
	 * @param $string
2562
	 * @return mixed
2563
	 */
2564
	public static function alias_directories( $string ) {
2565
		// ABSPATH has a trailing slash.
2566
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2567
		// WP_CONTENT_DIR does not have a trailing slash.
2568
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2569
2570
		return $string;
2571
	}
2572
2573
	public static function activate_default_modules(
2574
		$min_version = false,
2575
		$max_version = false,
2576
		$other_modules = array(),
2577
		$redirect = true,
2578
		$send_state_messages = true
2579
	) {
2580
		$jetpack = Jetpack::init();
2581
2582
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2583
		$modules = array_merge( $other_modules, $modules );
2584
2585
		// Look for standalone plugins and disable if active.
2586
2587
		$to_deactivate = array();
2588
		foreach ( $modules as $module ) {
2589
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2590
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2591
			}
2592
		}
2593
2594
		$deactivated = array();
2595
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2596
			list( $probable_file, $probable_title ) = $deactivate_me;
2597
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2598
				$deactivated[] = $module;
2599
			}
2600
		}
2601
2602
		if ( $deactivated && $redirect ) {
2603
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2604
2605
			$url = add_query_arg(
2606
				array(
2607
					'action'   => 'activate_default_modules',
2608
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2609
				),
2610
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2611
			);
2612
			wp_safe_redirect( $url );
2613
			exit;
2614
		}
2615
2616
		/**
2617
		 * Fires before default modules are activated.
2618
		 *
2619
		 * @since 1.9.0
2620
		 *
2621
		 * @param string $min_version Minimum version number required to use modules.
2622
		 * @param string $max_version Maximum version number required to use modules.
2623
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2624
		 */
2625
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2626
2627
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2628
		Jetpack::restate();
2629
		Jetpack::catch_errors( true );
2630
2631
		$active = Jetpack::get_active_modules();
2632
2633
		foreach ( $modules as $module ) {
2634
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2635
				$active[] = $module;
2636
				self::update_active_modules( $active );
2637
				continue;
2638
			}
2639
2640
			if ( $send_state_messages && in_array( $module, $active ) ) {
2641
				$module_info = Jetpack::get_module( $module );
2642 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2643
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2644
					if ( $active_state = Jetpack::state( $state ) ) {
2645
						$active_state = explode( ',', $active_state );
2646
					} else {
2647
						$active_state = array();
2648
					}
2649
					$active_state[] = $module;
2650
					Jetpack::state( $state, implode( ',', $active_state ) );
2651
				}
2652
				continue;
2653
			}
2654
2655
			$file = Jetpack::get_module_path( $module );
2656
			if ( ! file_exists( $file ) ) {
2657
				continue;
2658
			}
2659
2660
			// we'll override this later if the plugin can be included without fatal error
2661
			if ( $redirect ) {
2662
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2663
			}
2664
2665
			if ( $send_state_messages ) {
2666
				Jetpack::state( 'error', 'module_activation_failed' );
2667
				Jetpack::state( 'module', $module );
2668
			}
2669
2670
			ob_start();
2671
			require $file;
2672
2673
			$active[] = $module;
2674
2675 View Code Duplication
			if ( $send_state_messages ) {
2676
2677
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2678
				if ( $active_state = Jetpack::state( $state ) ) {
2679
					$active_state = explode( ',', $active_state );
2680
				} else {
2681
					$active_state = array();
2682
				}
2683
				$active_state[] = $module;
2684
				Jetpack::state( $state, implode( ',', $active_state ) );
2685
			}
2686
2687
			Jetpack::update_active_modules( $active );
2688
2689
			ob_end_clean();
2690
		}
2691
2692
		if ( $send_state_messages ) {
2693
			Jetpack::state( 'error', false );
2694
			Jetpack::state( 'module', false );
2695
		}
2696
2697
		Jetpack::catch_errors( false );
2698
		/**
2699
		 * Fires when default modules are activated.
2700
		 *
2701
		 * @since 1.9.0
2702
		 *
2703
		 * @param string $min_version Minimum version number required to use modules.
2704
		 * @param string $max_version Maximum version number required to use modules.
2705
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2706
		 */
2707
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2708
	}
2709
2710
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2711
		/**
2712
		 * Fires before a module is activated.
2713
		 *
2714
		 * @since 2.6.0
2715
		 *
2716
		 * @param string $module Module slug.
2717
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2718
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2719
		 */
2720
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2721
2722
		$jetpack = Jetpack::init();
2723
2724
		if ( ! strlen( $module ) )
2725
			return false;
2726
2727
		if ( ! Jetpack::is_module( $module ) )
2728
			return false;
2729
2730
		// If it's already active, then don't do it again
2731
		$active = Jetpack::get_active_modules();
2732
		foreach ( $active as $act ) {
2733
			if ( $act == $module )
2734
				return true;
2735
		}
2736
2737
		$module_data = Jetpack::get_module( $module );
2738
2739
		if ( ! Jetpack::is_active() ) {
2740
			if ( !Jetpack::is_development_mode() )
2741
				return false;
2742
2743
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2744
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2745
				return false;
2746
		}
2747
2748
		// Check and see if the old plugin is active
2749
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2750
			// Deactivate the old plugin
2751
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2752
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2753
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2754
				Jetpack::state( 'deactivated_plugins', $module );
2755
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2756
				exit;
2757
			}
2758
		}
2759
2760
		// Protect won't work with mis-configured IPs
2761
		if ( 'protect' === $module ) {
2762
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2763
			if ( ! jetpack_protect_get_ip() ) {
2764
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2765
				return false;
2766
			}
2767
		}
2768
2769
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2770
		Jetpack::state( 'module', $module );
2771
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2772
2773
		Jetpack::catch_errors( true );
2774
		ob_start();
2775
		require Jetpack::get_module_path( $module );
2776
		/** This action is documented in class.jetpack.php */
2777
		do_action( 'jetpack_activate_module', $module );
2778
		$active[] = $module;
2779
		Jetpack::update_active_modules( $active );
2780
2781
		Jetpack::state( 'error', false ); // the override
2782
		ob_end_clean();
2783
		Jetpack::catch_errors( false );
2784
2785
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2786 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2787
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2788
2789
			//Jump start is being dismissed send data to MC Stats
2790
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2791
2792
			$jetpack->do_stats( 'server_side' );
2793
		}
2794
2795
		if ( $redirect ) {
2796
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2797
		}
2798
		if ( $exit ) {
2799
			exit;
2800
		}
2801
		return true;
2802
	}
2803
2804
	function activate_module_actions( $module ) {
2805
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2806
	}
2807
2808
	public static function deactivate_module( $module ) {
2809
		/**
2810
		 * Fires when a module is deactivated.
2811
		 *
2812
		 * @since 1.9.0
2813
		 *
2814
		 * @param string $module Module slug.
2815
		 */
2816
		do_action( 'jetpack_pre_deactivate_module', $module );
2817
2818
		$jetpack = Jetpack::init();
2819
2820
		$active = Jetpack::get_active_modules();
2821
		$new    = array_filter( array_diff( $active, (array) $module ) );
2822
2823
		// A flag for Jump Start so it's not shown again.
2824 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2825
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2826
2827
			//Jump start is being dismissed send data to MC Stats
2828
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2829
2830
			$jetpack->do_stats( 'server_side' );
2831
		}
2832
2833
		return self::update_active_modules( $new );
2834
	}
2835
2836
	public static function enable_module_configurable( $module ) {
2837
		$module = Jetpack::get_module_slug( $module );
2838
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2839
	}
2840
2841
	public static function module_configuration_url( $module ) {
2842
		$module = Jetpack::get_module_slug( $module );
2843
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2844
	}
2845
2846
	public static function module_configuration_load( $module, $method ) {
2847
		$module = Jetpack::get_module_slug( $module );
2848
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2849
	}
2850
2851
	public static function module_configuration_head( $module, $method ) {
2852
		$module = Jetpack::get_module_slug( $module );
2853
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2854
	}
2855
2856
	public static function module_configuration_screen( $module, $method ) {
2857
		$module = Jetpack::get_module_slug( $module );
2858
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2859
	}
2860
2861
	public static function module_configuration_activation_screen( $module, $method ) {
2862
		$module = Jetpack::get_module_slug( $module );
2863
		add_action( 'display_activate_module_setting_' . $module, $method );
2864
	}
2865
2866
/* Installation */
2867
2868
	public static function bail_on_activation( $message, $deactivate = true ) {
2869
?>
2870
<!doctype html>
2871
<html>
2872
<head>
2873
<meta charset="<?php bloginfo( 'charset' ); ?>">
2874
<style>
2875
* {
2876
	text-align: center;
2877
	margin: 0;
2878
	padding: 0;
2879
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2880
}
2881
p {
2882
	margin-top: 1em;
2883
	font-size: 18px;
2884
}
2885
</style>
2886
<body>
2887
<p><?php echo esc_html( $message ); ?></p>
2888
</body>
2889
</html>
2890
<?php
2891
		if ( $deactivate ) {
2892
			$plugins = get_option( 'active_plugins' );
2893
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2894
			$update  = false;
2895
			foreach ( $plugins as $i => $plugin ) {
2896
				if ( $plugin === $jetpack ) {
2897
					$plugins[$i] = false;
2898
					$update = true;
2899
				}
2900
			}
2901
2902
			if ( $update ) {
2903
				update_option( 'active_plugins', array_filter( $plugins ) );
2904
			}
2905
		}
2906
		exit;
2907
	}
2908
2909
	/**
2910
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2911
	 * @static
2912
	 */
2913
	public static function plugin_activation( $network_wide ) {
2914
		Jetpack_Options::update_option( 'activated', 1 );
2915
2916
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2917
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2918
		}
2919
2920
		if ( $network_wide )
2921
			Jetpack::state( 'network_nag', true );
2922
2923
		// For firing one-off events (notices) immediately after activation
2924
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2925
2926
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2927
2928
		Jetpack::plugin_initialize();
2929
	}
2930
2931
	public static function get_activation_source( $referer_url ) {
2932
2933
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
2934
			return array( 'wp-cli', null );
2935
		}
2936
2937
		$referer = parse_url( $referer_url );
2938
2939
		$source_type = 'unknown';
2940
		$source_query = null;
2941
2942
		if ( ! is_array( $referer ) ) {
2943
			return array( $source_type, $source_query );
2944
		}
2945
2946
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
2947
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
2948
2949
		if ( isset( $referer['query'] ) ) {
2950
			parse_str( $referer['query'], $query_parts );
2951
		} else {
2952
			$query_parts = array();
2953
		}
2954
2955
		if ( $plugins_path === $referer['path'] ) {
2956
			$source_type = 'list';
2957
		} elseif ( $plugins_install_path === $referer['path'] ) {
2958
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
2959
			switch( $tab ) {
2960
				case 'popular':
2961
					$source_type = 'popular';
2962
					break;
2963
				case 'recommended':
2964
					$source_type = 'recommended';
2965
					break;
2966
				case 'favorites':
2967
					$source_type = 'favorites';
2968
					break;
2969
				case 'search':
2970
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
2971
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
2972
					break;
2973
				default:
2974
					$source_type = 'featured';
2975
			}
2976
		}
2977
2978
		return array( $source_type, $source_query );
2979
	}
2980
2981
	/**
2982
	 * Runs before bumping version numbers up to a new version
2983
	 * @param  string $version    Version:timestamp
2984
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
2985
	 * @return null              [description]
2986
	 */
2987
	public static function do_version_bump( $version, $old_version ) {
2988
2989
		if ( ! $old_version ) { // For new sites
2990
			// Setting up jetpack manage
2991
			Jetpack::activate_manage();
2992
		}
2993
	}
2994
2995
	/**
2996
	 * Sets the internal version number and activation state.
2997
	 * @static
2998
	 */
2999
	public static function plugin_initialize() {
3000
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3001
			Jetpack_Options::update_option( 'activated', 2 );
3002
		}
3003
3004 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3005
			$version = $old_version = JETPACK__VERSION . ':' . time();
3006
			/** This action is documented in class.jetpack.php */
3007
			do_action( 'updating_jetpack_version', $version, false );
3008
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3009
		}
3010
3011
		Jetpack::load_modules();
3012
3013
		Jetpack_Options::delete_option( 'do_activate' );
3014
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3015
	}
3016
3017
	/**
3018
	 * Removes all connection options
3019
	 * @static
3020
	 */
3021
	public static function plugin_deactivation( ) {
3022
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3023
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3024
			Jetpack_Network::init()->deactivate();
3025
		} else {
3026
			Jetpack::disconnect( false );
3027
			//Jetpack_Heartbeat::init()->deactivate();
3028
		}
3029
	}
3030
3031
	/**
3032
	 * Disconnects from the Jetpack servers.
3033
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3034
	 * @static
3035
	 */
3036
	public static function disconnect( $update_activated_state = true ) {
3037
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3038
		Jetpack::clean_nonces( true );
3039
3040
		// If the site is in an IDC because sync is not allowed,
3041
		// let's make sure to not disconnect the production site.
3042
		if ( ! self::validate_sync_error_idc_option() ) {
3043
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3044
			Jetpack::load_xml_rpc_client();
3045
			$xml = new Jetpack_IXR_Client();
3046
			$xml->query( 'jetpack.deregister' );
3047
		}
3048
3049
		Jetpack_Options::delete_option(
3050
			array(
3051
				'blog_token',
3052
				'user_token',
3053
				'user_tokens',
3054
				'master_user',
3055
				'time_diff',
3056
				'fallback_no_verify_ssl_certs',
3057
			)
3058
		);
3059
3060
		Jetpack_IDC::clear_all_idc_options();
3061
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3062
3063
		if ( $update_activated_state ) {
3064
			Jetpack_Options::update_option( 'activated', 4 );
3065
		}
3066
3067
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3068
			// Check then record unique disconnection if site has never been disconnected previously
3069
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3070
				$jetpack_unique_connection['disconnected'] = 1;
3071
			} else {
3072
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3073
					//track unique disconnect
3074
					$jetpack = Jetpack::init();
3075
3076
					$jetpack->stat( 'connections', 'unique-disconnect' );
3077
					$jetpack->do_stats( 'server_side' );
3078
				}
3079
				// increment number of times disconnected
3080
				$jetpack_unique_connection['disconnected'] += 1;
3081
			}
3082
3083
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3084
		}
3085
3086
		// Delete cached connected user data
3087
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3088
		delete_transient( $transient_key );
3089
3090
		// Delete all the sync related data. Since it could be taking up space.
3091
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3092
		Jetpack_Sync_Sender::get_instance()->uninstall();
3093
3094
		// Disable the Heartbeat cron
3095
		Jetpack_Heartbeat::init()->deactivate();
3096
	}
3097
3098
	/**
3099
	 * Unlinks the current user from the linked WordPress.com user
3100
	 */
3101
	public static function unlink_user( $user_id = null ) {
3102
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3103
			return false;
3104
3105
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3106
3107
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3108
			return false;
3109
3110
		if ( ! isset( $tokens[ $user_id ] ) )
3111
			return false;
3112
3113
		Jetpack::load_xml_rpc_client();
3114
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3115
		$xml->query( 'jetpack.unlink_user', $user_id );
3116
3117
		unset( $tokens[ $user_id ] );
3118
3119
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3120
3121
		/**
3122
		 * Fires after the current user has been unlinked from WordPress.com.
3123
		 *
3124
		 * @since 4.1.0
3125
		 *
3126
		 * @param int $user_id The current user's ID.
3127
		 */
3128
		do_action( 'jetpack_unlinked_user', $user_id );
3129
3130
		return true;
3131
	}
3132
3133
	/**
3134
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3135
	 */
3136
	public static function try_registration() {
3137
		// Let's get some testing in beta versions and such.
3138
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3139
			// Before attempting to connect, let's make sure that the domains are viable.
3140
			$domains_to_check = array_unique( array(
3141
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3142
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3143
			) );
3144
			foreach ( $domains_to_check as $domain ) {
3145
				$result = Jetpack_Data::is_usable_domain( $domain );
3146
				if ( is_wp_error( $result ) ) {
3147
					return $result;
3148
				}
3149
			}
3150
		}
3151
3152
		$result = Jetpack::register();
3153
3154
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3155
		if ( ! $result || is_wp_error( $result ) ) {
3156
			return $result;
3157
		} else {
3158
			return true;
3159
		}
3160
	}
3161
3162
	/**
3163
	 * Tracking an internal event log. Try not to put too much chaff in here.
3164
	 *
3165
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3166
	 */
3167
	public static function log( $code, $data = null ) {
3168
		// only grab the latest 200 entries
3169
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3170
3171
		// Append our event to the log
3172
		$log_entry = array(
3173
			'time'    => time(),
3174
			'user_id' => get_current_user_id(),
3175
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3176
			'code'    => $code,
3177
		);
3178
		// Don't bother storing it unless we've got some.
3179
		if ( ! is_null( $data ) ) {
3180
			$log_entry['data'] = $data;
3181
		}
3182
		$log[] = $log_entry;
3183
3184
		// Try add_option first, to make sure it's not autoloaded.
3185
		// @todo: Add an add_option method to Jetpack_Options
3186
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3187
			Jetpack_Options::update_option( 'log', $log );
3188
		}
3189
3190
		/**
3191
		 * Fires when Jetpack logs an internal event.
3192
		 *
3193
		 * @since 3.0.0
3194
		 *
3195
		 * @param array $log_entry {
3196
		 *	Array of details about the log entry.
3197
		 *
3198
		 *	@param string time Time of the event.
3199
		 *	@param int user_id ID of the user who trigerred the event.
3200
		 *	@param int blog_id Jetpack Blog ID.
3201
		 *	@param string code Unique name for the event.
3202
		 *	@param string data Data about the event.
3203
		 * }
3204
		 */
3205
		do_action( 'jetpack_log_entry', $log_entry );
3206
	}
3207
3208
	/**
3209
	 * Get the internal event log.
3210
	 *
3211
	 * @param $event (string) - only return the specific log events
3212
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3213
	 *
3214
	 * @return array of log events || WP_Error for invalid params
3215
	 */
3216
	public static function get_log( $event = false, $num = false ) {
3217
		if ( $event && ! is_string( $event ) ) {
3218
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3219
		}
3220
3221
		if ( $num && ! is_numeric( $num ) ) {
3222
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3223
		}
3224
3225
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3226
3227
		// If nothing set - act as it did before, otherwise let's start customizing the output
3228
		if ( ! $num && ! $event ) {
3229
			return $entire_log;
3230
		} else {
3231
			$entire_log = array_reverse( $entire_log );
3232
		}
3233
3234
		$custom_log_output = array();
3235
3236
		if ( $event ) {
3237
			foreach ( $entire_log as $log_event ) {
3238
				if ( $event == $log_event[ 'code' ] ) {
3239
					$custom_log_output[] = $log_event;
3240
				}
3241
			}
3242
		} else {
3243
			$custom_log_output = $entire_log;
3244
		}
3245
3246
		if ( $num ) {
3247
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3248
		}
3249
3250
		return $custom_log_output;
3251
	}
3252
3253
	/**
3254
	 * Log modification of important settings.
3255
	 */
3256
	public static function log_settings_change( $option, $old_value, $value ) {
3257
		switch( $option ) {
3258
			case 'jetpack_sync_non_public_post_stati':
3259
				self::log( $option, $value );
3260
				break;
3261
		}
3262
	}
3263
3264
	/**
3265
	 * Return stat data for WPCOM sync
3266
	 */
3267
	public static function get_stat_data( $encode = true, $extended = true ) {
3268
		$data = Jetpack_Heartbeat::generate_stats_array();
3269
3270
		if ( $extended ) {
3271
			$additional_data = self::get_additional_stat_data();
3272
			$data = array_merge( $data, $additional_data );
3273
		}
3274
3275
		if ( $encode ) {
3276
			return json_encode( $data );
3277
		}
3278
3279
		return $data;
3280
	}
3281
3282
	/**
3283
	 * Get additional stat data to sync to WPCOM
3284
	 */
3285
	public static function get_additional_stat_data( $prefix = '' ) {
3286
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3287
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3288
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3289
		$return["{$prefix}site-count"]     = 0;
3290
3291
		if ( function_exists( 'get_blog_count' ) ) {
3292
			$return["{$prefix}site-count"] = get_blog_count();
3293
		}
3294
		return $return;
3295
	}
3296
3297
	private static function get_site_user_count() {
3298
		global $wpdb;
3299
3300
		if ( function_exists( 'wp_is_large_network' ) ) {
3301
			if ( wp_is_large_network( 'users' ) ) {
3302
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3303
			}
3304
		}
3305 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3306
			// It wasn't there, so regenerate the data and save the transient
3307
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3308
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3309
		}
3310
		return $user_count;
3311
	}
3312
3313
	/* Admin Pages */
3314
3315
	function admin_init() {
3316
		// If the plugin is not connected, display a connect message.
3317
		if (
3318
			// the plugin was auto-activated and needs its candy
3319
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3320
		||
3321
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3322
			! Jetpack_Options::get_option( 'activated' )
3323
		) {
3324
			Jetpack::plugin_initialize();
3325
		}
3326
3327
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3328
			Jetpack_Connection_Banner::init();
3329
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3330
			// Upgrade: 1.1 -> 1.1.1
3331
			// Check and see if host can verify the Jetpack servers' SSL certificate
3332
			$args = array();
3333
			Jetpack_Client::_wp_remote_request(
3334
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3335
				$args,
3336
				true
3337
			);
3338
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3339
			// Show the notice on the Dashboard only for now
3340
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3341
		}
3342
3343
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3344
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3345
		}
3346
3347
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3348
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3349
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3350
3351
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3352
			// Artificially throw errors in certain whitelisted cases during plugin activation
3353
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3354
		}
3355
3356
		// Jetpack Manage Activation Screen from .com
3357
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3358
3359
		// Add custom column in wp-admin/users.php to show whether user is linked.
3360
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3361
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3362
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3363
	}
3364
3365
	function admin_body_class( $admin_body_class = '' ) {
3366
		$classes = explode( ' ', trim( $admin_body_class ) );
3367
3368
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3369
3370
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3371
		return " $admin_body_class ";
3372
	}
3373
3374
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3375
		return $admin_body_class . ' jetpack-pagestyles ';
3376
	}
3377
3378
	/**
3379
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3380
	 *
3381
	 * @return null
3382
	 */
3383
	function prepare_manage_jetpack_notice() {
3384
3385
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3386
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3387
	}
3388
3389
	function manage_activate_screen() {
3390
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3391
	}
3392
	/**
3393
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3394
	 * This function artificially throws errors for such cases (whitelisted).
3395
	 *
3396
	 * @param string $plugin The activated plugin.
3397
	 */
3398
	function throw_error_on_activate_plugin( $plugin ) {
3399
		$active_modules = Jetpack::get_active_modules();
3400
3401
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3402
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3403
			$throw = false;
3404
3405
			// Try and make sure it really was the stats plugin
3406
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3407
				if ( 'stats.php' == basename( $plugin ) ) {
3408
					$throw = true;
3409
				}
3410
			} else {
3411
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3412
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3413
					$throw = true;
3414
				}
3415
			}
3416
3417
			if ( $throw ) {
3418
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3419
			}
3420
		}
3421
	}
3422
3423
	function intercept_plugin_error_scrape_init() {
3424
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3425
	}
3426
3427
	function intercept_plugin_error_scrape( $action, $result ) {
3428
		if ( ! $result ) {
3429
			return;
3430
		}
3431
3432
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3433
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3434
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3435
			}
3436
		}
3437
	}
3438
3439
	function add_remote_request_handlers() {
3440
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3441
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3442
	}
3443
3444
	function remote_request_handlers() {
3445
		$action = current_filter();
3446
3447
		switch ( current_filter() ) {
3448
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3449
			$response = $this->upload_handler();
3450
			break;
3451
3452
		case 'wp_ajax_nopriv_jetpack_update_file' :
3453
			$response = $this->upload_handler( true );
3454
			break;
3455
		default :
3456
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3457
			break;
3458
		}
3459
3460
		if ( ! $response ) {
3461
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3462
		}
3463
3464
		if ( is_wp_error( $response ) ) {
3465
			$status_code       = $response->get_error_data();
3466
			$error             = $response->get_error_code();
3467
			$error_description = $response->get_error_message();
3468
3469
			if ( ! is_int( $status_code ) ) {
3470
				$status_code = 400;
3471
			}
3472
3473
			status_header( $status_code );
3474
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3475
		}
3476
3477
		status_header( 200 );
3478
		if ( true === $response ) {
3479
			exit;
3480
		}
3481
3482
		die( json_encode( (object) $response ) );
3483
	}
3484
3485
	/**
3486
	 * Uploads a file gotten from the global $_FILES.
3487
	 * If `$update_media_item` is true and `post_id` is defined
3488
	 * the attachment file of the media item (gotten through of the post_id)
3489
	 * will be updated instead of add a new one.
3490
	 *
3491
	 * @param  boolean $update_media_item - update media attachment
3492
	 * @return array - An array describing the uploadind files process
3493
	 */
3494
	function upload_handler( $update_media_item = false ) {
3495
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3496
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3497
		}
3498
3499
		$user = wp_authenticate( '', '' );
3500
		if ( ! $user || is_wp_error( $user ) ) {
3501
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3502
		}
3503
3504
		wp_set_current_user( $user->ID );
3505
3506
		if ( ! current_user_can( 'upload_files' ) ) {
3507
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3508
		}
3509
3510
		if ( empty( $_FILES ) ) {
3511
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3512
		}
3513
3514
		foreach ( array_keys( $_FILES ) as $files_key ) {
3515
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3516
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3517
			}
3518
		}
3519
3520
		$media_keys = array_keys( $_FILES['media'] );
3521
3522
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3523
		if ( ! $token || is_wp_error( $token ) ) {
3524
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3525
		}
3526
3527
		$uploaded_files = array();
3528
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3529
		unset( $GLOBALS['post'] );
3530
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3531
			$file = array();
3532
			foreach ( $media_keys as $media_key ) {
3533
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3534
			}
3535
3536
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3537
3538
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3539
			if ( $hmac_provided !== $hmac_file ) {
3540
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3541
				continue;
3542
			}
3543
3544
			$_FILES['.jetpack.upload.'] = $file;
3545
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3546
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3547
				$post_id = 0;
3548
			}
3549
3550
			if ( $update_media_item ) {
3551
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3552
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3553
				}
3554
3555
				$media_array = $_FILES['media'];
3556
3557
				$file_array['name'] = $media_array['name'][0];
3558
				$file_array['type'] = $media_array['type'][0];
3559
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3560
				$file_array['error'] = $media_array['error'][0];
3561
				$file_array['size'] = $media_array['size'][0];
3562
3563
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3564
3565
				if ( is_wp_error( $edited_media_item ) ) {
3566
					return $edited_media_item;
3567
				}
3568
3569
				$response = (object) array(
3570
					'id'   => (string) $post_id,
3571
					'file' => (string) $edited_media_item->post_title,
3572
					'url'  => (string) wp_get_attachment_url( $post_id ),
3573
					'type' => (string) $edited_media_item->post_mime_type,
3574
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3575
				);
3576
3577
				return (array) array( $response );
3578
			}
3579
3580
			$attachment_id = media_handle_upload(
3581
				'.jetpack.upload.',
3582
				$post_id,
3583
				array(),
3584
				array(
3585
					'action' => 'jetpack_upload_file',
3586
				)
3587
			);
3588
3589
			if ( ! $attachment_id ) {
3590
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3591
			} elseif ( is_wp_error( $attachment_id ) ) {
3592
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3593
			} else {
3594
				$attachment = get_post( $attachment_id );
3595
				$uploaded_files[$index] = (object) array(
3596
					'id'   => (string) $attachment_id,
3597
					'file' => $attachment->post_title,
3598
					'url'  => wp_get_attachment_url( $attachment_id ),
3599
					'type' => $attachment->post_mime_type,
3600
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3601
				);
3602
				// Zip files uploads are not supported unless they are done for installation purposed
3603
				// lets delete them in case something goes wrong in this whole process
3604
				if ( 'application/zip' === $attachment->post_mime_type ) {
3605
					// Schedule a cleanup for 2 hours from now in case of failed install.
3606
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3607
				}
3608
			}
3609
		}
3610
		if ( ! is_null( $global_post ) ) {
3611
			$GLOBALS['post'] = $global_post;
3612
		}
3613
3614
		return $uploaded_files;
3615
	}
3616
3617
	/**
3618
	 * Add help to the Jetpack page
3619
	 *
3620
	 * @since Jetpack (1.2.3)
3621
	 * @return false if not the Jetpack page
3622
	 */
3623
	function admin_help() {
3624
		$current_screen = get_current_screen();
3625
3626
		// Overview
3627
		$current_screen->add_help_tab(
3628
			array(
3629
				'id'		=> 'home',
3630
				'title'		=> __( 'Home', 'jetpack' ),
3631
				'content'	=>
3632
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3633
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3634
					'<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>',
3635
			)
3636
		);
3637
3638
		// Screen Content
3639
		if ( current_user_can( 'manage_options' ) ) {
3640
			$current_screen->add_help_tab(
3641
				array(
3642
					'id'		=> 'settings',
3643
					'title'		=> __( 'Settings', 'jetpack' ),
3644
					'content'	=>
3645
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3646
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3647
						'<ol>' .
3648
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3649
							'<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>' .
3650
						'</ol>' .
3651
						'<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>'
3652
				)
3653
			);
3654
		}
3655
3656
		// Help Sidebar
3657
		$current_screen->set_help_sidebar(
3658
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3659
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3660
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3661
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3662
		);
3663
	}
3664
3665
	function admin_menu_css() {
3666
		wp_enqueue_style( 'jetpack-icons' );
3667
	}
3668
3669
	function admin_menu_order() {
3670
		return true;
3671
	}
3672
3673 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3674
		$jp_menu_order = array();
3675
3676
		foreach ( $menu_order as $index => $item ) {
3677
			if ( $item != 'jetpack' ) {
3678
				$jp_menu_order[] = $item;
3679
			}
3680
3681
			if ( $index == 0 ) {
3682
				$jp_menu_order[] = 'jetpack';
3683
			}
3684
		}
3685
3686
		return $jp_menu_order;
3687
	}
3688
3689
	function admin_head() {
3690 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3691
			/** This action is documented in class.jetpack-admin-page.php */
3692
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3693
	}
3694
3695
	function admin_banner_styles() {
3696
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3697
3698 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3699
			wp_register_style(
3700
				'jetpack-dops-style',
3701
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3702
				array(),
3703
				JETPACK__VERSION
3704
			);
3705
		}
3706
3707
		wp_enqueue_style(
3708
			'jetpack',
3709
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3710
			array( 'jetpack-dops-style' ),
3711
			 JETPACK__VERSION . '-20121016'
3712
		);
3713
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3714
		wp_style_add_data( 'jetpack', 'suffix', $min );
3715
	}
3716
3717
	function plugin_action_links( $actions ) {
3718
3719
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3720
3721
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3722
			return array_merge(
3723
				$jetpack_home,
3724
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3725
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3726
				$actions
3727
				);
3728
			}
3729
3730
		return array_merge( $jetpack_home, $actions );
3731
	}
3732
3733
	/**
3734
	 * This is the first banner
3735
	 * It should be visible only to user that can update the option
3736
	 * Are not connected
3737
	 *
3738
	 * @return null
3739
	 */
3740
	function admin_jetpack_manage_notice() {
3741
		$screen = get_current_screen();
3742
3743
		// Don't show the connect notice on the jetpack settings page.
3744
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3745
			return;
3746
		}
3747
3748
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3749
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3750
		/**
3751
		 * I think it would be great to have different wordsing depending on where you are
3752
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3753
		 * etc..
3754
		 */
3755
3756
		?>
3757
		<div id="message" class="updated jp-banner">
3758
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3759
				<div class="jp-banner__description-container">
3760
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3761
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3762
					<p class="jp-banner__button-container">
3763
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3764
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3765
					</p>
3766
				</div>
3767
		</div>
3768
		<?php
3769
	}
3770
3771
	/**
3772
	 * Returns the url that the user clicks to remove the notice for the big banner
3773
	 * @return string
3774
	 */
3775
	function opt_out_jetpack_manage_url() {
3776
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3777
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3778
	}
3779
	/**
3780
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3781
	 * @return string
3782
	 */
3783
	function opt_in_jetpack_manage_url() {
3784
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3785
	}
3786
3787
	function opt_in_jetpack_manage_notice() {
3788
		?>
3789
		<div class="wrap">
3790
			<div id="message" class="jetpack-message is-opt-in">
3791
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'https://jetpack.com/support/site-management' ); ?>
3792
			</div>
3793
		</div>
3794
		<?php
3795
3796
	}
3797
	/**
3798
	 * Determines whether to show the notice of not true = display notice
3799
	 * @return bool
3800
	 */
3801
	function can_display_jetpack_manage_notice() {
3802
		// never display the notice to users that can't do anything about it anyways
3803
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3804
			return false;
3805
3806
		// don't display if we are in development more
3807
		if( Jetpack::is_development_mode() ) {
3808
			return false;
3809
		}
3810
		// don't display if the site is private
3811
		if(  ! Jetpack_Options::get_option( 'public' ) )
3812
			return false;
3813
3814
		/**
3815
		 * Should the Jetpack Remote Site Management notice be displayed.
3816
		 *
3817
		 * @since 3.3.0
3818
		 *
3819
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3820
		 */
3821
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3822
	}
3823
3824
	/*
3825
	 * Registration flow:
3826
	 * 1 - ::admin_page_load() action=register
3827
	 * 2 - ::try_registration()
3828
	 * 3 - ::register()
3829
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3830
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3831
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3832
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3833
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3834
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3835
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3836
	 *       jetpack_id, jetpack_secret, jetpack_public
3837
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3838
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3839
	 * 5 - user logs in with WP.com account
3840
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3841
	 *		- Jetpack_Client_Server::authorize()
3842
	 *		- Jetpack_Client_Server::get_token()
3843
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3844
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3845
	 *			- which responds with access_token, token_type, scope
3846
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3847
	 *		- Jetpack::activate_default_modules()
3848
	 *     		- Deactivates deprecated plugins
3849
	 *     		- Activates all default modules
3850
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3851
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3852
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3853
	 *     Done!
3854
	 */
3855
3856
	/**
3857
	 * Handles the page load events for the Jetpack admin page
3858
	 */
3859
	function admin_page_load() {
3860
		$error = false;
3861
3862
		// Make sure we have the right body class to hook stylings for subpages off of.
3863
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3864
3865
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3866
			// Should only be used in intermediate redirects to preserve state across redirects
3867
			Jetpack::restate();
3868
		}
3869
3870
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3871
			// User clicked in the iframe to link their accounts
3872
			if ( ! Jetpack::is_user_connected() ) {
3873
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3874
				if ( isset( $_GET['notes_iframe'] ) )
3875
					$connect_url .= '&notes_iframe';
3876
				wp_redirect( $connect_url );
3877
				exit;
3878
			} else {
3879
				if ( ! isset( $_GET['calypso_env'] ) ) {
3880
					Jetpack::state( 'message', 'already_authorized' );
3881
					wp_safe_redirect( Jetpack::admin_url() );
3882
					exit;
3883
				} else {
3884
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3885
					$connect_url .= '&already_authorized=true';
3886
					wp_redirect( $connect_url );
3887
					exit;
3888
				}
3889
			}
3890
		}
3891
3892
3893
		if ( isset( $_GET['action'] ) ) {
3894
			switch ( $_GET['action'] ) {
3895
			case 'authorize':
3896
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3897
					Jetpack::state( 'message', 'already_authorized' );
3898
					wp_safe_redirect( Jetpack::admin_url() );
3899
					exit;
3900
				}
3901
				Jetpack::log( 'authorize' );
3902
				$client_server = new Jetpack_Client_Server;
3903
				$client_server->client_authorize();
3904
				exit;
3905
			case 'register' :
3906
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3907
					$error = 'cheatin';
3908
					break;
3909
				}
3910
				check_admin_referer( 'jetpack-register' );
3911
				Jetpack::log( 'register' );
3912
				Jetpack::maybe_set_version_option();
3913
				$registered = Jetpack::try_registration();
3914
				if ( is_wp_error( $registered ) ) {
3915
					$error = $registered->get_error_code();
3916
					Jetpack::state( 'error', $error );
3917
					Jetpack::state( 'error', $registered->get_error_message() );
3918
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
3919
						'error_code' => $error,
3920
						'error_message' => $registered->get_error_message()
3921
					) );
3922
					break;
3923
				}
3924
3925
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3926
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3927
3928
				JetpackTracking::record_user_event( 'jpc_register_success', array(
3929
					'from' => $from
3930
				) );
3931
3932
				wp_redirect( $this->build_connect_url( true, $redirect, $from ) );
3933
				exit;
3934
			case 'activate' :
3935
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3936
					$error = 'cheatin';
3937
					break;
3938
				}
3939
3940
				$module = stripslashes( $_GET['module'] );
3941
				check_admin_referer( "jetpack_activate-$module" );
3942
				Jetpack::log( 'activate', $module );
3943
				Jetpack::activate_module( $module );
3944
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3945
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3946
				exit;
3947
			case 'activate_default_modules' :
3948
				check_admin_referer( 'activate_default_modules' );
3949
				Jetpack::log( 'activate_default_modules' );
3950
				Jetpack::restate();
3951
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3952
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3953
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3954
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3955
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3956
				exit;
3957
			case 'disconnect' :
3958
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3959
					$error = 'cheatin';
3960
					break;
3961
				}
3962
3963
				check_admin_referer( 'jetpack-disconnect' );
3964
				Jetpack::log( 'disconnect' );
3965
				Jetpack::disconnect();
3966
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3967
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3968
			case 'reconnect' :
3969
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3970
					$error = 'cheatin';
3971
					break;
3972
				}
3973
3974
				check_admin_referer( 'jetpack-reconnect' );
3975
				Jetpack::log( 'reconnect' );
3976
				$this->disconnect();
3977
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3978
				exit;
3979 View Code Duplication
			case 'deactivate' :
3980
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3981
					$error = 'cheatin';
3982
					break;
3983
				}
3984
3985
				$modules = stripslashes( $_GET['module'] );
3986
				check_admin_referer( "jetpack_deactivate-$modules" );
3987
				foreach ( explode( ',', $modules ) as $module ) {
3988
					Jetpack::log( 'deactivate', $module );
3989
					Jetpack::deactivate_module( $module );
3990
					Jetpack::state( 'message', 'module_deactivated' );
3991
				}
3992
				Jetpack::state( 'module', $modules );
3993
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3994
				exit;
3995
			case 'unlink' :
3996
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3997
				check_admin_referer( 'jetpack-unlink' );
3998
				Jetpack::log( 'unlink' );
3999
				$this->unlink_user();
4000
				Jetpack::state( 'message', 'unlinked' );
4001
				if ( 'sub-unlink' == $redirect ) {
4002
					wp_safe_redirect( admin_url() );
4003
				} else {
4004
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4005
				}
4006
				exit;
4007
			default:
4008
				/**
4009
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4010
				 *
4011
				 * @since 2.6.0
4012
				 *
4013
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4014
				 */
4015
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4016
			}
4017
		}
4018
4019
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4020
			self::activate_new_modules( true );
4021
		}
4022
4023
		$message_code = Jetpack::state( 'message' );
4024
		if ( Jetpack::state( 'optin-manage' ) ) {
4025
			$activated_manage = $message_code;
4026
			$message_code = 'jetpack-manage';
4027
		}
4028
4029
		switch ( $message_code ) {
4030
		case 'jetpack-manage':
4031
			$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>';
4032
			if ( $activated_manage ) {
4033
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4034
			}
4035
			break;
4036
4037
		}
4038
4039
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4040
4041
		if ( ! empty( $deactivated_plugins ) ) {
4042
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4043
			$deactivated_titles  = array();
4044
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4045
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4046
					continue;
4047
				}
4048
4049
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4050
			}
4051
4052
			if ( $deactivated_titles ) {
4053
				if ( $this->message ) {
4054
					$this->message .= "<br /><br />\n";
4055
				}
4056
4057
				$this->message .= wp_sprintf(
4058
					_n(
4059
						'Jetpack contains the most recent version of the old %l plugin.',
4060
						'Jetpack contains the most recent versions of the old %l plugins.',
4061
						count( $deactivated_titles ),
4062
						'jetpack'
4063
					),
4064
					$deactivated_titles
4065
				);
4066
4067
				$this->message .= "<br />\n";
4068
4069
				$this->message .= _n(
4070
					'The old version has been deactivated and can be removed from your site.',
4071
					'The old versions have been deactivated and can be removed from your site.',
4072
					count( $deactivated_titles ),
4073
					'jetpack'
4074
				);
4075
			}
4076
		}
4077
4078
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4079
4080
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4081
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4082
		}
4083
4084 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4085
			/**
4086
			 * Fires when a module configuration page is loaded.
4087
			 * The dynamic part of the hook is the configure parameter from the URL.
4088
			 *
4089
			 * @since 1.1.0
4090
			 */
4091
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4092
		}
4093
4094
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4095
	}
4096
4097
	function admin_notices() {
4098
4099
		if ( $this->error ) {
4100
?>
4101
<div id="message" class="jetpack-message jetpack-err">
4102
	<div class="squeezer">
4103
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4104
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4105
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4106
<?php	endif; ?>
4107
	</div>
4108
</div>
4109
<?php
4110
		}
4111
4112
		if ( $this->message ) {
4113
?>
4114
<div id="message" class="jetpack-message">
4115
	<div class="squeezer">
4116
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4117
	</div>
4118
</div>
4119
<?php
4120
		}
4121
4122
		if ( $this->privacy_checks ) :
4123
			$module_names = $module_slugs = array();
4124
4125
			$privacy_checks = explode( ',', $this->privacy_checks );
4126
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4127
			foreach ( $privacy_checks as $module_slug ) {
4128
				$module = Jetpack::get_module( $module_slug );
4129
				if ( ! $module ) {
4130
					continue;
4131
				}
4132
4133
				$module_slugs[] = $module_slug;
4134
				$module_names[] = "<strong>{$module['name']}</strong>";
4135
			}
4136
4137
			$module_slugs = join( ',', $module_slugs );
4138
?>
4139
<div id="message" class="jetpack-message jetpack-err">
4140
	<div class="squeezer">
4141
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4142
		<p><?php
4143
			echo wp_kses(
4144
				wptexturize(
4145
					wp_sprintf(
4146
						_nx(
4147
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4148
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4149
							count( $privacy_checks ),
4150
							'%l = list of Jetpack module/feature names',
4151
							'jetpack'
4152
						),
4153
						$module_names
4154
					)
4155
				),
4156
				array( 'strong' => true )
4157
			);
4158
4159
			echo "\n<br />\n";
4160
4161
			echo wp_kses(
4162
				sprintf(
4163
					_nx(
4164
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4165
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4166
						count( $privacy_checks ),
4167
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4168
						'jetpack'
4169
					),
4170
					wp_nonce_url(
4171
						Jetpack::admin_url(
4172
							array(
4173
								'page'   => 'jetpack',
4174
								'action' => 'deactivate',
4175
								'module' => urlencode( $module_slugs ),
4176
							)
4177
						),
4178
						"jetpack_deactivate-$module_slugs"
4179
					),
4180
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4181
				),
4182
				array( 'a' => array( 'href' => true, 'title' => true ) )
4183
			);
4184
		?></p>
4185
	</div>
4186
</div>
4187
<?php endif;
4188
	// only display the notice if the other stuff is not there
4189
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4190
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4191
			$this->opt_in_jetpack_manage_notice();
4192
		}
4193
	}
4194
4195
	/**
4196
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4197
	 */
4198
	function stat( $group, $detail ) {
4199
		if ( ! isset( $this->stats[ $group ] ) )
4200
			$this->stats[ $group ] = array();
4201
		$this->stats[ $group ][] = $detail;
4202
	}
4203
4204
	/**
4205
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4206
	 */
4207
	function do_stats( $method = '' ) {
4208
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4209
			foreach ( $this->stats as $group => $stats ) {
4210
				if ( is_array( $stats ) && count( $stats ) ) {
4211
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4212
					if ( 'server_side' === $method ) {
4213
						self::do_server_side_stat( $args );
4214
					} else {
4215
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4216
					}
4217
				}
4218
				unset( $this->stats[ $group ] );
4219
			}
4220
		}
4221
	}
4222
4223
	/**
4224
	 * Runs stats code for a one-off, server-side.
4225
	 *
4226
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4227
	 *
4228
	 * @return bool If it worked.
4229
	 */
4230
	static function do_server_side_stat( $args ) {
4231
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4232
		if ( is_wp_error( $response ) )
4233
			return false;
4234
4235
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4236
			return false;
4237
4238
		return true;
4239
	}
4240
4241
	/**
4242
	 * Builds the stats url.
4243
	 *
4244
	 * @param $args array|string The arguments to append to the URL.
4245
	 *
4246
	 * @return string The URL to be pinged.
4247
	 */
4248
	static function build_stats_url( $args ) {
4249
		$defaults = array(
4250
			'v'    => 'wpcom2',
4251
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4252
		);
4253
		$args     = wp_parse_args( $args, $defaults );
4254
		/**
4255
		 * Filter the URL used as the Stats tracking pixel.
4256
		 *
4257
		 * @since 2.3.2
4258
		 *
4259
		 * @param string $url Base URL used as the Stats tracking pixel.
4260
		 */
4261
		$base_url = apply_filters(
4262
			'jetpack_stats_base_url',
4263
			'https://pixel.wp.com/g.gif'
4264
		);
4265
		$url      = add_query_arg( $args, $base_url );
4266
		return $url;
4267
	}
4268
4269
	static function translate_current_user_to_role() {
4270
		foreach ( self::$capability_translations as $role => $cap ) {
4271
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4272
				return $role;
4273
			}
4274
		}
4275
4276
		return false;
4277
	}
4278
4279
	static function translate_user_to_role( $user ) {
4280
		foreach ( self::$capability_translations as $role => $cap ) {
4281
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4282
				return $role;
4283
			}
4284
		}
4285
4286
		return false;
4287
    }
4288
4289
	static function translate_role_to_cap( $role ) {
4290
		if ( ! isset( self::$capability_translations[$role] ) ) {
4291
			return false;
4292
		}
4293
4294
		return self::$capability_translations[$role];
4295
	}
4296
4297
	static function sign_role( $role, $user_id = null ) {
4298
		if ( empty( $user_id ) ) {
4299
			$user_id = (int) get_current_user_id();
4300
		}
4301
4302
		if ( ! $user_id  ) {
4303
			return false;
4304
		}
4305
4306
		$token = Jetpack_Data::get_access_token();
4307
		if ( ! $token || is_wp_error( $token ) ) {
4308
			return false;
4309
		}
4310
4311
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4312
	}
4313
4314
4315
	/**
4316
	 * Builds a URL to the Jetpack connection auth page
4317
	 *
4318
	 * @since 3.9.5
4319
	 *
4320
	 * @param bool $raw If true, URL will not be escaped.
4321
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4322
	 *                              If string, will be a custom redirect.
4323
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4324
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4325
	 *
4326
	 * @return string Connect URL
4327
	 */
4328
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4329
		$site_id = Jetpack_Options::get_option( 'id' );
4330
		$token = Jetpack_Options::get_option( 'blog_token' );
4331
4332
		if ( $register || ! $token || ! $site_id ) {
4333
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4334
4335
			if ( ! empty( $redirect ) ) {
4336
				$url = add_query_arg(
4337
					'redirect',
4338
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4339
					$url
4340
				);
4341
			}
4342
4343
			if( is_network_admin() ) {
4344
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4345
			}
4346
		} else {
4347
4348
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4349
			// because otherwise this logic can get us in to a loop.
4350
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4351
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4352
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4353
4354
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4355
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4356
					'1.1'
4357
				);
4358
4359
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4360
					// Generating a register URL instead to refresh the existing token
4361
					return $this->build_connect_url( $raw, $redirect, $from, true );
4362
				}
4363
			}
4364
4365
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4366
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4367
			}
4368
4369
			$role = self::translate_current_user_to_role();
4370
			$signed_role = self::sign_role( $role );
4371
4372
			$user = wp_get_current_user();
4373
4374
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4375
			$redirect = $redirect
4376
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4377
				: $jetpack_admin_page;
4378
4379
			if( isset( $_REQUEST['is_multisite'] ) ) {
4380
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4381
			}
4382
4383
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4384
4385
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4386
				? get_site_icon_url()
4387
				: false;
4388
4389
			/**
4390
			 * Filter the type of authorization.
4391
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4392
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4393
			 *
4394
			 * @since 4.3.3
4395
			 *
4396
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4397
			 */
4398
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4399
4400
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4401
4402
			$args = urlencode_deep(
4403
				array(
4404
					'response_type' => 'code',
4405
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4406
					'redirect_uri'  => add_query_arg(
4407
						array(
4408
							'action'   => 'authorize',
4409
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4410
							'redirect' => urlencode( $redirect ),
4411
						),
4412
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4413
					),
4414
					'state'         => $user->ID,
4415
					'scope'         => $signed_role,
4416
					'user_email'    => $user->user_email,
4417
					'user_login'    => $user->user_login,
4418
					'is_active'     => Jetpack::is_active(),
4419
					'jp_version'    => JETPACK__VERSION,
4420
					'auth_type'     => $auth_type,
4421
					'secret'        => $secrets['secret_1'],
4422
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4423
					'blogname'      => get_option( 'blogname' ),
4424
					'site_url'      => site_url(),
4425
					'home_url'      => home_url(),
4426
					'site_icon'     => $site_icon,
4427
					'site_lang'     => get_locale(),
4428
					'_ui'           => $tracks_identity['_ui'],
4429
					'_ut'           => $tracks_identity['_ut']
4430
				)
4431
			);
4432
4433
			self::apply_activation_source_to_args( $args );
4434
4435
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4436
		}
4437
4438
		if ( $from ) {
4439
			$url = add_query_arg( 'from', $from, $url );
4440
		}
4441
4442
4443
		if ( isset( $_GET['calypso_env'] ) ) {
4444
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4445
		}
4446
4447
		if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4448
			$url = add_query_arg( 'onboarding', $token, $url );
4449
4450
			// Remove this once https://github.com/Automattic/wp-calypso/pull/17094 is merged.
4451
			// Uncomment for development until it's merged.
4452
			//$url = add_query_arg( 'calypso_env', 'development', $url );
4453
		}
4454
4455
		return $raw ? $url : esc_url( $url );
4456
	}
4457
4458
	public static function apply_activation_source_to_args( &$args ) {
4459
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4460
4461
		if ( $activation_source_name ) {
4462
			$args['_as'] = urlencode( $activation_source_name );
4463
		}
4464
4465
		if ( $activation_source_keyword ) {
4466
			$args['_ak'] = urlencode( $activation_source_keyword );
4467
		}
4468
	}
4469
4470
	function build_reconnect_url( $raw = false ) {
4471
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4472
		return $raw ? $url : esc_url( $url );
4473
	}
4474
4475
	public static function admin_url( $args = null ) {
4476
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4477
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4478
		return $url;
4479
	}
4480
4481
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4482
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4483
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4484
	}
4485
4486
	function dismiss_jetpack_notice() {
4487
4488
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4489
			return;
4490
		}
4491
4492
		switch( $_GET['jetpack-notice'] ) {
4493
			case 'dismiss':
4494
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4495
4496
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4497
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4498
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4499
				}
4500
				break;
4501 View Code Duplication
			case 'jetpack-manage-opt-out':
4502
4503
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4504
					// Don't show the banner again
4505
4506
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4507
					// redirect back to the page that had the notice
4508
					if ( wp_get_referer() ) {
4509
						wp_safe_redirect( wp_get_referer() );
4510
					} else {
4511
						// Take me to Jetpack
4512
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4513
					}
4514
				}
4515
				break;
4516 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4517
4518
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4519
					// Don't show the banner again
4520
4521
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4522
					// redirect back to the page that had the notice
4523
					if ( wp_get_referer() ) {
4524
						wp_safe_redirect( wp_get_referer() );
4525
					} else {
4526
						// Take me to Jetpack
4527
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4528
					}
4529
				}
4530
				break;
4531
			case 'jetpack-manage-opt-in':
4532
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4533
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4534
4535
					$redirection_url = Jetpack::admin_url();
4536
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4537
4538
					// Don't redirect form the Jetpack Setting Page
4539
					$referer_parsed = parse_url ( wp_get_referer() );
4540
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4541
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4542
						// Take the user to Jetpack home except when on the setting page
4543
						$redirection_url = wp_get_referer();
4544
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4545
					}
4546
					// Also update the JSON API FULL MANAGEMENT Option
4547
					Jetpack::activate_module( 'manage', false, false );
4548
4549
					// Special Message when option in.
4550
					Jetpack::state( 'optin-manage', 'true' );
4551
					// Activate the Module if not activated already
4552
4553
					// Redirect properly
4554
					wp_safe_redirect( $redirection_url );
4555
4556
				}
4557
				break;
4558
		}
4559
	}
4560
4561
	public static function admin_screen_configure_module( $module_id ) {
4562
4563
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4564
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4565
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4566
				/**
4567
				 * Fires to diplay a custom module activation screen.
4568
				 *
4569
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4570
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4571
				 *
4572
				 * @module manage
4573
				 *
4574
				 * @since 3.8.0
4575
				 *
4576
				 * @param int $module_id Module ID.
4577
				 */
4578
				do_action( 'display_activate_module_setting_' . $module_id );
4579
			} else {
4580
				self::display_activate_module_link( $module_id );
4581
			}
4582
4583
			return false;
4584
		} ?>
4585
4586
		<div id="jp-settings-screen" style="position: relative">
4587
			<h3>
4588
			<?php
4589
				$module = Jetpack::get_module( $module_id );
4590
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4591
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4592
			?>
4593
			</h3>
4594
			<?php
4595
				/**
4596
				 * Fires within the displayed message when a feature configuation is updated.
4597
				 *
4598
				 * @since 3.4.0
4599
				 *
4600
				 * @param int $module_id Module ID.
4601
				 */
4602
				do_action( 'jetpack_notices_update_settings', $module_id );
4603
				/**
4604
				 * Fires when a feature configuation screen is loaded.
4605
				 * The dynamic part of the hook, $module_id, is the module ID.
4606
				 *
4607
				 * @since 1.1.0
4608
				 */
4609
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4610
			?>
4611
		</div><?php
4612
	}
4613
4614
	/**
4615
	 * Display link to activate the module to see the settings screen.
4616
	 * @param  string $module_id
4617
	 * @return null
4618
	 */
4619
	public static function display_activate_module_link( $module_id ) {
4620
4621
		$info =  Jetpack::get_module( $module_id );
4622
		$extra = '';
4623
		$activate_url = wp_nonce_url(
4624
				Jetpack::admin_url(
4625
					array(
4626
						'page'   => 'jetpack',
4627
						'action' => 'activate',
4628
						'module' => $module_id,
4629
					)
4630
				),
4631
				"jetpack_activate-$module_id"
4632
			);
4633
4634
		?>
4635
4636
		<div class="wrap configure-module">
4637
			<div id="jp-settings-screen">
4638
				<?php
4639
				if ( $module_id == 'json-api' ) {
4640
4641
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4642
4643
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4644
4645
					$info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'https://jetpack.com/support/site-management' );
4646
4647
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4648
				} ?>
4649
4650
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4651
				<div class="narrow">
4652
					<p><?php echo  $info['description']; ?></p>
4653
					<?php if( $extra ) { ?>
4654
					<p><?php echo esc_html( $extra ); ?></p>
4655
					<?php } ?>
4656
					<p>
4657
						<?php
4658
						if( wp_get_referer() ) {
4659
							printf( __( '<a class="button-primary" href="%s">Activate Now</a> or <a href="%s" >return to previous page</a>.', 'jetpack' ) , $activate_url, wp_get_referer() );
4660
						} else {
4661
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4662
						} ?>
4663
					</p>
4664
				</div>
4665
4666
			</div>
4667
		</div>
4668
4669
		<?php
4670
	}
4671
4672
	public static function sort_modules( $a, $b ) {
4673
		if ( $a['sort'] == $b['sort'] )
4674
			return 0;
4675
4676
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4677
	}
4678
4679
	function ajax_recheck_ssl() {
4680
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4681
		$result = Jetpack::permit_ssl( true );
4682
		wp_send_json( array(
4683
			'enabled' => $result,
4684
			'message' => get_transient( 'jetpack_https_test_message' )
4685
		) );
4686
	}
4687
4688
/* Client API */
4689
4690
	/**
4691
	 * Returns the requested Jetpack API URL
4692
	 *
4693
	 * @return string
4694
	 */
4695
	public static function api_url( $relative_url ) {
4696
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4697
	}
4698
4699
	/**
4700
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4701
	 */
4702
	public static function fix_url_for_bad_hosts( $url ) {
4703
		if ( 0 !== strpos( $url, 'https://' ) ) {
4704
			return $url;
4705
		}
4706
4707
		switch ( JETPACK_CLIENT__HTTPS ) {
4708
			case 'ALWAYS' :
4709
				return $url;
4710
			case 'NEVER' :
4711
				return set_url_scheme( $url, 'http' );
4712
			// default : case 'AUTO' :
4713
		}
4714
4715
		// we now return the unmodified SSL URL by default, as a security precaution
4716
		return $url;
4717
	}
4718
4719
	/**
4720
	 * Create a random secret for validating onboarding payload
4721
	 *
4722
	 * @return string Secret token
4723
	 */
4724
	public static function create_onboarding_token() {
4725
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4726
			$token = wp_generate_password( 32, false );
4727
			Jetpack_Options::update_option( 'onboarding', $token );
4728
		}
4729
4730
		return $token;
4731
	}
4732
4733
	/**
4734
	 * Remove the onboarding token
4735
	 *
4736
	 * @return bool True on success, false on failure
4737
	 */
4738
	public static function invalidate_onboarding_token() {
4739
		return Jetpack_Options::delete_option( 'onboarding' );
4740
	}
4741
4742
	/**
4743
	 * Validate an onboarding token for a specific action
4744
	 *
4745
	 * @return boolean True if token/action pair is accepted, false if not
4746
	 */
4747
	public static function validate_onboarding_token_action( $token, $action ) {
4748
		// Compare tokens, bail if tokens do not match
4749
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4750
			return false;
4751
		}
4752
4753
		// List of valid actions we can take
4754
		$valid_actions = array(
4755
			'/jetpack/v4/settings',
4756
		);
4757
4758
		// Whitelist the action
4759
		if ( ! in_array( $action, $valid_actions ) ) {
4760
			return false;
4761
		}
4762
4763
		return true;
4764
	}
4765
4766
	/**
4767
	 * Checks to see if the URL is using SSL to connect with Jetpack
4768
	 *
4769
	 * @since 2.3.3
4770
	 * @return boolean
4771
	 */
4772
	public static function permit_ssl( $force_recheck = false ) {
4773
		// Do some fancy tests to see if ssl is being supported
4774
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4775
			$message = '';
4776
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4777
				$ssl = 0;
4778
			} else {
4779
				switch ( JETPACK_CLIENT__HTTPS ) {
4780
					case 'NEVER':
4781
						$ssl = 0;
4782
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4783
						break;
4784
					case 'ALWAYS':
4785
					case 'AUTO':
4786
					default:
4787
						$ssl = 1;
4788
						break;
4789
				}
4790
4791
				// If it's not 'NEVER', test to see
4792
				if ( $ssl ) {
4793
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4794
						$ssl = 0;
4795
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4796
					} else {
4797
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4798
						if ( is_wp_error( $response ) ) {
4799
							$ssl = 0;
4800
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4801
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4802
							$ssl = 0;
4803
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4804
						}
4805
					}
4806
				}
4807
			}
4808
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4809
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4810
		}
4811
4812
		return (bool) $ssl;
4813
	}
4814
4815
	/*
4816
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4817
	 */
4818
	public function alert_auto_ssl_fail() {
4819
		if ( ! current_user_can( 'manage_options' ) )
4820
			return;
4821
4822
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4823
		?>
4824
4825
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4826
			<div class="jp-banner__content">
4827
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4828
				<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>
4829
				<p>
4830
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4831
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4832
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4833
				</p>
4834
				<p>
4835
					<?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' ),
4836
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4837
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4838
				</p>
4839
			</div>
4840
		</div>
4841
		<style>
4842
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4843
		</style>
4844
		<script type="text/javascript">
4845
			jQuery( document ).ready( function( $ ) {
4846
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4847
					var $this = $( this );
4848
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4849
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4850
					e.preventDefault();
4851
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4852
					$.post( ajaxurl, data )
4853
					  .done( function( response ) {
4854
					  	if ( response.enabled ) {
4855
					  		$( '#jetpack-ssl-warning' ).hide();
4856
					  	} else {
4857
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4858
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4859
					  	}
4860
					  }.bind( $this ) );
4861
				} );
4862
			} );
4863
		</script>
4864
4865
		<?php
4866
	}
4867
4868
	/**
4869
	 * Returns the Jetpack XML-RPC API
4870
	 *
4871
	 * @return string
4872
	 */
4873
	public static function xmlrpc_api_url() {
4874
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4875
		return untrailingslashit( $base ) . '/xmlrpc.php';
4876
	}
4877
4878
	/**
4879
	 * Creates two secret tokens and the end of life timestamp for them.
4880
	 *
4881
	 * Note these tokens are unique per call, NOT static per site for connecting.
4882
	 *
4883
	 * @since 2.6
4884
	 * @return array
4885
	 */
4886
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4887
		if ( ! $user_id ) {
4888
			$user_id = get_current_user_id();
4889
		}
4890
4891
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
4892
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4893
4894
		if (
4895
			isset( $secrets[ $secret_name ] ) &&
4896
			$secrets[ $secret_name ]['exp'] > time()
4897
		) {
4898
			return $secrets[ $secret_name ];
4899
		}
4900
4901
		$secret_value = array(
4902
			'secret_1'  => wp_generate_password( 32, false ),
4903
			'secret_2'  => wp_generate_password( 32, false ),
4904
			'exp'       => time() + $exp,
4905
		);
4906
4907
		$secrets[ $secret_name ] = $secret_value;
4908
4909
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4910
		return $secrets[ $secret_name ];
4911
	}
4912
4913
	public static function get_secrets( $action, $user_id ) {
4914
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4915
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4916
4917
		if ( ! isset( $secrets[ $secret_name ] ) ) {
4918
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4919
		}
4920
4921
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
4922
			self::delete_secrets( $action, $user_id );
4923
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4924
		}
4925
4926
		return $secrets[ $secret_name ];
4927
	}
4928
4929
	public static function delete_secrets( $action, $user_id ) {
4930
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4931
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4932
		if ( isset( $secrets[ $secret_name ] ) ) {
4933
			unset( $secrets[ $secret_name ] );
4934
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4935
		}
4936
	}
4937
4938
	/**
4939
	 * Builds the timeout limit for queries talking with the wpcom servers.
4940
	 *
4941
	 * Based on local php max_execution_time in php.ini
4942
	 *
4943
	 * @since 2.6
4944
	 * @return int
4945
	 * @deprecated
4946
	 **/
4947
	public function get_remote_query_timeout_limit() {
4948
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4949
		return Jetpack::get_max_execution_time();
4950
	}
4951
4952
	/**
4953
	 * Builds the timeout limit for queries talking with the wpcom servers.
4954
	 *
4955
	 * Based on local php max_execution_time in php.ini
4956
	 *
4957
	 * @since 5.4
4958
	 * @return int
4959
	 **/
4960
	public static function get_max_execution_time() {
4961
		$timeout = (int) ini_get( 'max_execution_time' );
4962
4963
		// Ensure exec time set in php.ini
4964
		if ( ! $timeout ) {
4965
			$timeout = 30;
4966
		}
4967
		return $timeout;
4968
	}
4969
4970
	/**
4971
	 * Sets a minimum request timeout, and returns the current timeout
4972
	 *
4973
	 * @since 5.4
4974
	 **/
4975
	public static function set_min_time_limit( $min_timeout ) {
4976
		$timeout = self::get_max_execution_time();
4977
		if ( $timeout < $min_timeout ) {
4978
			$timeout = $min_timeout;
4979
			set_time_limit( $timeout );
4980
		}
4981
		return $timeout;
4982
	}
4983
4984
4985
	/**
4986
	 * Takes the response from the Jetpack register new site endpoint and
4987
	 * verifies it worked properly.
4988
	 *
4989
	 * @since 2.6
4990
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4991
	 **/
4992
	public function validate_remote_register_response( $response ) {
4993
	  if ( is_wp_error( $response ) ) {
4994
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4995
		}
4996
4997
		$code   = wp_remote_retrieve_response_code( $response );
4998
		$entity = wp_remote_retrieve_body( $response );
4999
		if ( $entity )
5000
			$registration_response = json_decode( $entity );
5001
		else
5002
			$registration_response = false;
5003
5004
		$code_type = intval( $code / 100 );
5005
		if ( 5 == $code_type ) {
5006
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5007
		} elseif ( 408 == $code ) {
5008
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5009
		} elseif ( ! empty( $registration_response->error ) ) {
5010
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5011
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5012
			} else {
5013
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5014
			}
5015
5016
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5017
		} elseif ( 200 != $code ) {
5018
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5019
		}
5020
5021
		// Jetpack ID error block
5022
		if ( empty( $registration_response->jetpack_id ) ) {
5023
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5024
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5025
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5026
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5027
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5028
		}
5029
5030
	    return $registration_response;
5031
	}
5032
	/**
5033
	 * @return bool|WP_Error
5034
	 */
5035
	public static function register() {
5036
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5037
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5038
		$secrets = Jetpack::generate_secrets( 'register' );
5039
5040 View Code Duplication
		if (
5041
			empty( $secrets['secret_1'] ) ||
5042
			empty( $secrets['secret_2'] ) ||
5043
			empty( $secrets['exp'] )
5044
		) {
5045
			return new Jetpack_Error( 'missing_secrets' );
5046
		}
5047
5048
		// better to try (and fail) to set a higher timeout than this system
5049
		// supports than to have register fail for more users than it should
5050
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5051
5052
		$gmt_offset = get_option( 'gmt_offset' );
5053
		if ( ! $gmt_offset ) {
5054
			$gmt_offset = 0;
5055
		}
5056
5057
		$stats_options = get_option( 'stats_options' );
5058
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5059
5060
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5061
5062
		$args = array(
5063
			'method'  => 'POST',
5064
			'body'    => array(
5065
				'siteurl'         => site_url(),
5066
				'home'            => home_url(),
5067
				'gmt_offset'      => $gmt_offset,
5068
				'timezone_string' => (string) get_option( 'timezone_string' ),
5069
				'site_name'       => (string) get_option( 'blogname' ),
5070
				'secret_1'        => $secrets['secret_1'],
5071
				'secret_2'        => $secrets['secret_2'],
5072
				'site_lang'       => get_locale(),
5073
				'timeout'         => $timeout,
5074
				'stats_id'        => $stats_id,
5075
				'state'           => get_current_user_id(),
5076
				'_ui'             => $tracks_identity['_ui'],
5077
				'_ut'             => $tracks_identity['_ut'],
5078
				'jetpack_version' => JETPACK__VERSION
5079
			),
5080
			'headers' => array(
5081
				'Accept' => 'application/json',
5082
			),
5083
			'timeout' => $timeout,
5084
		);
5085
5086
		self::apply_activation_source_to_args( $args['body'] );
5087
5088
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5089
5090
		// Make sure the response is valid and does not contain any Jetpack errors
5091
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5092
		if ( is_wp_error( $registration_details ) ) {
5093
			return $registration_details;
5094
		} elseif ( ! $registration_details ) {
5095
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5096
		}
5097
5098 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5099
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5100
		}
5101
5102
		if ( isset( $registration_details->jetpack_public ) ) {
5103
			$jetpack_public = (int) $registration_details->jetpack_public;
5104
		} else {
5105
			$jetpack_public = false;
5106
		}
5107
5108
		Jetpack_Options::update_options(
5109
			array(
5110
				'id'         => (int)    $registration_details->jetpack_id,
5111
				'blog_token' => (string) $registration_details->jetpack_secret,
5112
				'public'     => $jetpack_public,
5113
			)
5114
		);
5115
5116
		/**
5117
		 * Fires when a site is registered on WordPress.com.
5118
		 *
5119
		 * @since 3.7.0
5120
		 *
5121
		 * @param int $json->jetpack_id Jetpack Blog ID.
5122
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5123
		 * @param int|bool $jetpack_public Is the site public.
5124
		 */
5125
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5126
5127
		// Initialize Jump Start for the first and only time.
5128
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5129
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5130
5131
			$jetpack = Jetpack::init();
5132
5133
			$jetpack->stat( 'jumpstart', 'unique-views' );
5134
			$jetpack->do_stats( 'server_side' );
5135
		};
5136
5137
		return true;
5138
	}
5139
5140
	/**
5141
	 * If the db version is showing something other that what we've got now, bump it to current.
5142
	 *
5143
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5144
	 */
5145
	public static function maybe_set_version_option() {
5146
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5147
		if ( JETPACK__VERSION != $version ) {
5148
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5149
5150
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5151
				/** This action is documented in class.jetpack.php */
5152
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5153
			}
5154
5155
			return true;
5156
		}
5157
		return false;
5158
	}
5159
5160
/* Client Server API */
5161
5162
	/**
5163
	 * Loads the Jetpack XML-RPC client
5164
	 */
5165
	public static function load_xml_rpc_client() {
5166
		require_once ABSPATH . WPINC . '/class-IXR.php';
5167
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5168
	}
5169
5170
	/**
5171
	 * Resets the saved authentication state in between testing requests.
5172
	 */
5173
	public function reset_saved_auth_state() {
5174
		$this->xmlrpc_verification = null;
5175
		$this->rest_authentication_status = null;
5176
	}
5177
5178
	function verify_xml_rpc_signature() {
5179
		if ( $this->xmlrpc_verification ) {
5180
			return $this->xmlrpc_verification;
5181
		}
5182
5183
		// It's not for us
5184
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5185
			return false;
5186
		}
5187
5188
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5189
		if (
5190
			empty( $token_key )
5191
		||
5192
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5193
		) {
5194
			return false;
5195
		}
5196
5197
		if ( '0' === $user_id ) {
5198
			$token_type = 'blog';
5199
			$user_id = 0;
5200
		} else {
5201
			$token_type = 'user';
5202
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5203
				return false;
5204
			}
5205
			$user_id = (int) $user_id;
5206
5207
			$user = new WP_User( $user_id );
5208
			if ( ! $user || ! $user->exists() ) {
5209
				return false;
5210
			}
5211
		}
5212
5213
		$token = Jetpack_Data::get_access_token( $user_id );
5214
		if ( ! $token ) {
5215
			return false;
5216
		}
5217
5218
		$token_check = "$token_key.";
5219
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5220
			return false;
5221
		}
5222
5223
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5224
5225
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5226
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5227
			$post_data   = $_POST;
5228
			$file_hashes = array();
5229
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5230
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5231
					continue;
5232
				}
5233
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5234
				$file_hashes[$post_data_key] = $post_data_value;
5235
			}
5236
5237
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5238
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5239
				$post_data[$post_data_key] = $post_data_value;
5240
			}
5241
5242
			ksort( $post_data );
5243
5244
			$body = http_build_query( stripslashes_deep( $post_data ) );
5245
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5246
			$body = file_get_contents( 'php://input' );
5247
		} else {
5248
			$body = null;
5249
		}
5250
5251
		$signature = $jetpack_signature->sign_current_request(
5252
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5253
		);
5254
5255
		if ( ! $signature ) {
5256
			return false;
5257
		} else if ( is_wp_error( $signature ) ) {
5258
			return $signature;
5259
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5260
			return false;
5261
		}
5262
5263
		$timestamp = (int) $_GET['timestamp'];
5264
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5265
5266
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5267
			return false;
5268
		}
5269
5270
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5271
		if ( isset( $this->HTTP_RAW_POST_DATA ) ) {
5272
			$jpo = json_decode( $this->HTTP_RAW_POST_DATA );
5273
			if (
5274
				isset( $jpo->onboarding ) &&
5275
				isset( $jpo->onboarding->jpUser ) && isset( $jpo->onboarding->token ) &&
5276
				is_email( $jpo->onboarding->jpUser ) && ctype_alnum( $jpo->onboarding->token ) &&
5277
				isset( $_GET['rest_route'] ) &&
5278
				self::validate_onboarding_token_action( $jpo->onboarding->token, $_GET['rest_route'] )
5279
			) {
5280
				$jpUser = get_user_by( 'email', $jpo->onboarding->jpUser );
5281
				if ( is_a( $jpUser, 'WP_User' ) ) {
5282
					wp_set_current_user( $jpUser->ID );
5283
					$user_can = is_multisite()
5284
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5285
						: current_user_can( 'manage_options' );
5286
					if ( $user_can ) {
5287
						$token_type = 'user';
5288
						$token->external_user_id = $jpUser->ID;
5289
					}
5290
				}
5291
			}
5292
		}
5293
5294
		$this->xmlrpc_verification = array(
5295
			'type'    => $token_type,
5296
			'user_id' => $token->external_user_id,
5297
		);
5298
5299
		return $this->xmlrpc_verification;
5300
	}
5301
5302
	/**
5303
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5304
	 */
5305
	function authenticate_jetpack( $user, $username, $password ) {
5306
		if ( is_a( $user, 'WP_User' ) ) {
5307
			return $user;
5308
		}
5309
5310
		$token_details = $this->verify_xml_rpc_signature();
5311
5312
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5313
			return $user;
5314
		}
5315
5316
		if ( 'user' !== $token_details['type'] ) {
5317
			return $user;
5318
		}
5319
5320
		if ( ! $token_details['user_id'] ) {
5321
			return $user;
5322
		}
5323
5324
		nocache_headers();
5325
5326
		return new WP_User( $token_details['user_id'] );
5327
	}
5328
5329
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5330
	// Uses the existing XMLRPC request signing implementation.
5331
	function wp_rest_authenticate( $user ) {
5332
		if ( ! empty( $user ) ) {
5333
			// Another authentication method is in effect.
5334
			return $user;
5335
		}
5336
5337
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5338
			// Nothing to do for this authentication method.
5339
			return null;
5340
		}
5341
5342
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5343
			// Nothing to do for this authentication method.
5344
			return null;
5345
		}
5346
5347
		// Ensure that we always have the request body available.  At this
5348
		// point, the WP REST API code to determine the request body has not
5349
		// run yet.  That code may try to read from 'php://input' later, but
5350
		// this can only be done once per request in PHP versions prior to 5.6.
5351
		// So we will go ahead and perform this read now if needed, and save
5352
		// the request body where both the Jetpack signature verification code
5353
		// and the WP REST API code can see it.
5354
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5355
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5356
		}
5357
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5358
5359
		// Only support specific request parameters that have been tested and
5360
		// are known to work with signature verification.  A different method
5361
		// can be passed to the WP REST API via the '?_method=' parameter if
5362
		// needed.
5363
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5364
			$this->rest_authentication_status = new WP_Error(
5365
				'rest_invalid_request',
5366
				__( 'This request method is not supported.', 'jetpack' ),
5367
				array( 'status' => 400 )
5368
			);
5369
			return null;
5370
		}
5371
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5372
			$this->rest_authentication_status = new WP_Error(
5373
				'rest_invalid_request',
5374
				__( 'This request method does not support body parameters.', 'jetpack' ),
5375
				array( 'status' => 400 )
5376
			);
5377
			return null;
5378
		}
5379
5380
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
5381
			$content_type = $_SERVER['CONTENT_TYPE'];
5382
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
5383
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
5384
		}
5385
5386
		if (
5387
			isset( $content_type ) &&
5388
			$content_type !== 'application/x-www-form-urlencoded' &&
5389
			$content_type !== 'application/json'
5390
		) {
5391
			$this->rest_authentication_status = new WP_Error(
5392
				'rest_invalid_request',
5393
				__( 'This Content-Type is not supported.', 'jetpack' ),
5394
				array( 'status' => 400 )
5395
			);
5396
			return null;
5397
		}
5398
5399
		$verified = $this->verify_xml_rpc_signature();
5400
5401
		if ( is_wp_error( $verified ) ) {
5402
			$this->rest_authentication_status = $verified;
5403
			return null;
5404
		}
5405
5406
		if (
5407
			$verified &&
5408
			isset( $verified['type'] ) &&
5409
			'user' === $verified['type'] &&
5410
			! empty( $verified['user_id'] )
5411
		) {
5412
			// Authentication successful.
5413
			$this->rest_authentication_status = true;
5414
			return $verified['user_id'];
5415
		}
5416
5417
		// Something else went wrong.  Probably a signature error.
5418
		$this->rest_authentication_status = new WP_Error(
5419
			'rest_invalid_signature',
5420
			__( 'The request is not signed correctly.', 'jetpack' ),
5421
			array( 'status' => 400 )
5422
		);
5423
		return null;
5424
	}
5425
5426
	/**
5427
	 * Report authentication status to the WP REST API.
5428
	 *
5429
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5430
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5431
	 */
5432
	public function wp_rest_authentication_errors( $value ) {
5433
		if ( $value !== null ) {
5434
			return $value;
5435
		}
5436
		return $this->rest_authentication_status;
5437
	}
5438
5439
	function add_nonce( $timestamp, $nonce ) {
5440
		global $wpdb;
5441
		static $nonces_used_this_request = array();
5442
5443
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5444
			return $nonces_used_this_request["$timestamp:$nonce"];
5445
		}
5446
5447
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5448
		$timestamp = (int) $timestamp;
5449
		$nonce     = esc_sql( $nonce );
5450
5451
		// Raw query so we can avoid races: add_option will also update
5452
		$show_errors = $wpdb->show_errors( false );
5453
5454
		$old_nonce = $wpdb->get_row(
5455
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5456
		);
5457
5458
		if ( is_null( $old_nonce ) ) {
5459
			$return = $wpdb->query(
5460
				$wpdb->prepare(
5461
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5462
					"jetpack_nonce_{$timestamp}_{$nonce}",
5463
					time(),
5464
					'no'
5465
				)
5466
			);
5467
		} else {
5468
			$return = false;
5469
		}
5470
5471
		$wpdb->show_errors( $show_errors );
5472
5473
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5474
5475
		return $return;
5476
	}
5477
5478
	/**
5479
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5480
	 * Capture it here so we can verify the signature later.
5481
	 */
5482
	function xmlrpc_methods( $methods ) {
5483
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5484
		return $methods;
5485
	}
5486
5487
	function public_xmlrpc_methods( $methods ) {
5488
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5489
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5490
		}
5491
		return $methods;
5492
	}
5493
5494
	function jetpack_getOptions( $args ) {
5495
		global $wp_xmlrpc_server;
5496
5497
		$wp_xmlrpc_server->escape( $args );
5498
5499
		$username	= $args[1];
5500
		$password	= $args[2];
5501
5502
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5503
			return $wp_xmlrpc_server->error;
5504
		}
5505
5506
		$options = array();
5507
		$user_data = $this->get_connected_user_data();
5508
		if ( is_array( $user_data ) ) {
5509
			$options['jetpack_user_id'] = array(
5510
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5511
				'readonly'      => true,
5512
				'value'         => $user_data['ID'],
5513
			);
5514
			$options['jetpack_user_login'] = array(
5515
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5516
				'readonly'      => true,
5517
				'value'         => $user_data['login'],
5518
			);
5519
			$options['jetpack_user_email'] = array(
5520
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5521
				'readonly'      => true,
5522
				'value'         => $user_data['email'],
5523
			);
5524
			$options['jetpack_user_site_count'] = array(
5525
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5526
				'readonly'      => true,
5527
				'value'         => $user_data['site_count'],
5528
			);
5529
		}
5530
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5531
		$args = stripslashes_deep( $args );
5532
		return $wp_xmlrpc_server->wp_getOptions( $args );
5533
	}
5534
5535
	function xmlrpc_options( $options ) {
5536
		$jetpack_client_id = false;
5537
		if ( self::is_active() ) {
5538
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5539
		}
5540
		$options['jetpack_version'] = array(
5541
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5542
				'readonly'      => true,
5543
				'value'         => JETPACK__VERSION,
5544
		);
5545
5546
		$options['jetpack_client_id'] = array(
5547
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5548
				'readonly'      => true,
5549
				'value'         => $jetpack_client_id,
5550
		);
5551
		return $options;
5552
	}
5553
5554
	public static function clean_nonces( $all = false ) {
5555
		global $wpdb;
5556
5557
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5558
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5559
5560
		if ( true !== $all ) {
5561
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5562
			$sql_args[] = time() - 3600;
5563
		}
5564
5565
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5566
5567
		$sql = $wpdb->prepare( $sql, $sql_args );
5568
5569
		for ( $i = 0; $i < 1000; $i++ ) {
5570
			if ( ! $wpdb->query( $sql ) ) {
5571
				break;
5572
			}
5573
		}
5574
	}
5575
5576
	/**
5577
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5578
	 * SET: state( $key, $value );
5579
	 * GET: $value = state( $key );
5580
	 *
5581
	 * @param string $key
5582
	 * @param string $value
5583
	 * @param bool $restate private
5584
	 */
5585
	public static function state( $key = null, $value = null, $restate = false ) {
5586
		static $state = array();
5587
		static $path, $domain;
5588
		if ( ! isset( $path ) ) {
5589
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5590
			$admin_url = Jetpack::admin_url();
5591
			$bits      = parse_url( $admin_url );
5592
5593
			if ( is_array( $bits ) ) {
5594
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5595
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5596
			} else {
5597
				$path = $domain = null;
5598
			}
5599
		}
5600
5601
		// Extract state from cookies and delete cookies
5602
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5603
			$yum = $_COOKIE[ 'jetpackState' ];
5604
			unset( $_COOKIE[ 'jetpackState' ] );
5605
			foreach ( $yum as $k => $v ) {
5606
				if ( strlen( $v ) )
5607
					$state[ $k ] = $v;
5608
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5609
			}
5610
		}
5611
5612
		if ( $restate ) {
5613
			foreach ( $state as $k => $v ) {
5614
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5615
			}
5616
			return;
5617
		}
5618
5619
		// Get a state variable
5620
		if ( isset( $key ) && ! isset( $value ) ) {
5621
			if ( array_key_exists( $key, $state ) )
5622
				return $state[ $key ];
5623
			return null;
5624
		}
5625
5626
		// Set a state variable
5627
		if ( isset ( $key ) && isset( $value ) ) {
5628
			if( is_array( $value ) && isset( $value[0] ) ) {
5629
				$value = $value[0];
5630
			}
5631
			$state[ $key ] = $value;
5632
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5633
		}
5634
	}
5635
5636
	public static function restate() {
5637
		Jetpack::state( null, null, true );
5638
	}
5639
5640
	public static function check_privacy( $file ) {
5641
		static $is_site_publicly_accessible = null;
5642
5643
		if ( is_null( $is_site_publicly_accessible ) ) {
5644
			$is_site_publicly_accessible = false;
5645
5646
			Jetpack::load_xml_rpc_client();
5647
			$rpc = new Jetpack_IXR_Client();
5648
5649
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5650
			if ( $success ) {
5651
				$response = $rpc->getResponse();
5652
				if ( $response ) {
5653
					$is_site_publicly_accessible = true;
5654
				}
5655
			}
5656
5657
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5658
		}
5659
5660
		if ( $is_site_publicly_accessible ) {
5661
			return;
5662
		}
5663
5664
		$module_slug = self::get_module_slug( $file );
5665
5666
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5667
		if ( ! $privacy_checks ) {
5668
			$privacy_checks = $module_slug;
5669
		} else {
5670
			$privacy_checks .= ",$module_slug";
5671
		}
5672
5673
		Jetpack::state( 'privacy_checks', $privacy_checks );
5674
	}
5675
5676
	/**
5677
	 * Helper method for multicall XMLRPC.
5678
	 */
5679
	public static function xmlrpc_async_call() {
5680
		global $blog_id;
5681
		static $clients = array();
5682
5683
		$client_blog_id = is_multisite() ? $blog_id : 0;
5684
5685
		if ( ! isset( $clients[$client_blog_id] ) ) {
5686
			Jetpack::load_xml_rpc_client();
5687
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5688
			if ( function_exists( 'ignore_user_abort' ) ) {
5689
				ignore_user_abort( true );
5690
			}
5691
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5692
		}
5693
5694
		$args = func_get_args();
5695
5696
		if ( ! empty( $args[0] ) ) {
5697
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5698
		} elseif ( is_multisite() ) {
5699
			foreach ( $clients as $client_blog_id => $client ) {
5700
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5701
					continue;
5702
				}
5703
5704
				$switch_success = switch_to_blog( $client_blog_id, true );
5705
				if ( ! $switch_success ) {
5706
					continue;
5707
				}
5708
5709
				flush();
5710
				$client->query();
5711
5712
				restore_current_blog();
5713
			}
5714
		} else {
5715
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5716
				flush();
5717
				$clients[0]->query();
5718
			}
5719
		}
5720
	}
5721
5722
	public static function staticize_subdomain( $url ) {
5723
5724
		// Extract hostname from URL
5725
		$host = parse_url( $url, PHP_URL_HOST );
5726
5727
		// Explode hostname on '.'
5728
		$exploded_host = explode( '.', $host );
5729
5730
		// Retrieve the name and TLD
5731
		if ( count( $exploded_host ) > 1 ) {
5732
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5733
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5734
			// Rebuild domain excluding subdomains
5735
			$domain = $name . '.' . $tld;
5736
		} else {
5737
			$domain = $host;
5738
		}
5739
		// Array of Automattic domains
5740
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5741
5742
		// Return $url if not an Automattic domain
5743
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5744
			return $url;
5745
		}
5746
5747
		if ( is_ssl() ) {
5748
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5749
		}
5750
5751
		srand( crc32( basename( $url ) ) );
5752
		$static_counter = rand( 0, 2 );
5753
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5754
5755
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5756
	}
5757
5758
/* JSON API Authorization */
5759
5760
	/**
5761
	 * Handles the login action for Authorizing the JSON API
5762
	 */
5763
	function login_form_json_api_authorization() {
5764
		$this->verify_json_api_authorization_request();
5765
5766
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5767
5768
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5769
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5770
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5771
	}
5772
5773
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5774
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5775
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5776
			return $url;
5777
		}
5778
5779
		$parsed_url = parse_url( $url );
5780
		$url = strtok( $url, '?' );
5781
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5782
		if ( ! empty( $parsed_url['query'] ) )
5783
			$url .= "&{$parsed_url['query']}";
5784
5785
		return $url;
5786
	}
5787
5788
	// Make sure the POSTed request is handled by the same action
5789
	function preserve_action_in_login_form_for_json_api_authorization() {
5790
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5791
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5792
	}
5793
5794
	// If someone logs in to approve API access, store the Access Code in usermeta
5795
	function store_json_api_authorization_token( $user_login, $user ) {
5796
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5797
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5798
		$token = wp_generate_password( 32, false );
5799
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5800
	}
5801
5802
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5803
	function allow_wpcom_public_api_domain( $domains ) {
5804
		$domains[] = 'public-api.wordpress.com';
5805
		return $domains;
5806
	}
5807
5808
	// Add the Access Code details to the public-api.wordpress.com redirect
5809
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5810
		return add_query_arg(
5811
			urlencode_deep(
5812
				array(
5813
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5814
					'jetpack-user-id' => (int) $user->ID,
5815
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5816
				)
5817
			),
5818
			$redirect_to
5819
		);
5820
	}
5821
5822
5823
	/**
5824
	 * Verifies the request by checking the signature
5825
	 *
5826
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5827
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5828
	 *
5829
	 * @param null|array $environment
5830
	 */
5831
	function verify_json_api_authorization_request( $environment = null ) {
5832
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5833
5834
		$environment = is_null( $environment )
5835
			? $_REQUEST
5836
			: $environment;
5837
5838
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5839
		$token = Jetpack_Data::get_access_token( $envUserId );
5840
		if ( ! $token || empty( $token->secret ) ) {
5841
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5842
		}
5843
5844
		$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' );
5845
5846
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5847
5848
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5849
			$signature = $jetpack_signature->sign_request(
5850
				$environment['token'],
5851
				$environment['timestamp'],
5852
				$environment['nonce'],
5853
				'',
5854
				'GET',
5855
				$environment['jetpack_json_api_original_query'],
5856
				null,
5857
				true
5858
			);
5859
		} else {
5860
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5861
		}
5862
5863
		if ( ! $signature ) {
5864
			wp_die( $die_error );
5865
		} else if ( is_wp_error( $signature ) ) {
5866
			wp_die( $die_error );
5867
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5868
			if ( is_ssl() ) {
5869
				// 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
5870
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5871
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5872
					wp_die( $die_error );
5873
				}
5874
			} else {
5875
				wp_die( $die_error );
5876
			}
5877
		}
5878
5879
		$timestamp = (int) $environment['timestamp'];
5880
		$nonce     = stripslashes( (string) $environment['nonce'] );
5881
5882
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5883
			// De-nonce the nonce, at least for 5 minutes.
5884
			// 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)
5885
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5886
			if ( $old_nonce_time < time() - 300 ) {
5887
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5888
			}
5889
		}
5890
5891
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5892
		$data_filters = array(
5893
			'state'        => 'opaque',
5894
			'client_id'    => 'int',
5895
			'client_title' => 'string',
5896
			'client_image' => 'url',
5897
		);
5898
5899
		foreach ( $data_filters as $key => $sanitation ) {
5900
			if ( ! isset( $data->$key ) ) {
5901
				wp_die( $die_error );
5902
			}
5903
5904
			switch ( $sanitation ) {
5905
			case 'int' :
5906
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5907
				break;
5908
			case 'opaque' :
5909
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5910
				break;
5911
			case 'string' :
5912
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5913
				break;
5914
			case 'url' :
5915
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5916
				break;
5917
			}
5918
		}
5919
5920
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5921
			wp_die( $die_error );
5922
		}
5923
	}
5924
5925
	function login_message_json_api_authorization( $message ) {
5926
		return '<p class="message">' . sprintf(
5927
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5928
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5929
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5930
	}
5931
5932
	/**
5933
	 * Get $content_width, but with a <s>twist</s> filter.
5934
	 */
5935
	public static function get_content_width() {
5936
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5937
		/**
5938
		 * Filter the Content Width value.
5939
		 *
5940
		 * @since 2.2.3
5941
		 *
5942
		 * @param string $content_width Content Width value.
5943
		 */
5944
		return apply_filters( 'jetpack_content_width', $content_width );
5945
	}
5946
5947
	/**
5948
	 * Pings the WordPress.com Mirror Site for the specified options.
5949
	 *
5950
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5951
	 *
5952
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5953
	 */
5954
	public function get_cloud_site_options( $option_names ) {
5955
		$option_names = array_filter( (array) $option_names, 'is_string' );
5956
5957
		Jetpack::load_xml_rpc_client();
5958
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5959
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5960
		if ( $xml->isError() ) {
5961
			return array(
5962
				'error_code' => $xml->getErrorCode(),
5963
				'error_msg'  => $xml->getErrorMessage(),
5964
			);
5965
		}
5966
		$cloud_site_options = $xml->getResponse();
5967
5968
		return $cloud_site_options;
5969
	}
5970
5971
	/**
5972
	 * Checks if the site is currently in an identity crisis.
5973
	 *
5974
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5975
	 */
5976
	public static function check_identity_crisis() {
5977
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5978
			return false;
5979
		}
5980
5981
		return Jetpack_Options::get_option( 'sync_error_idc' );
5982
	}
5983
5984
	/**
5985
	 * Checks whether the home and siteurl specifically are whitelisted
5986
	 * Written so that we don't have re-check $key and $value params every time
5987
	 * we want to check if this site is whitelisted, for example in footer.php
5988
	 *
5989
	 * @since  3.8.0
5990
	 * @return bool True = already whitelisted False = not whitelisted
5991
	 */
5992
	public static function is_staging_site() {
5993
		$is_staging = false;
5994
5995
		$known_staging = array(
5996
			'urls' => array(
5997
				'#\.staging\.wpengine\.com$#i', // WP Engine
5998
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5999
				),
6000
			'constants' => array(
6001
				'IS_WPE_SNAPSHOT',      // WP Engine
6002
				'KINSTA_DEV_ENV',       // Kinsta.com
6003
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6004
				'JETPACK_STAGING_MODE', // Generic
6005
				)
6006
			);
6007
		/**
6008
		 * Filters the flags of known staging sites.
6009
		 *
6010
		 * @since 3.9.0
6011
		 *
6012
		 * @param array $known_staging {
6013
		 *     An array of arrays that each are used to check if the current site is staging.
6014
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6015
		 *     @type array $constants PHP constants of known staging/developement environments.
6016
		 *  }
6017
		 */
6018
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6019
6020
		if ( isset( $known_staging['urls'] ) ) {
6021
			foreach ( $known_staging['urls'] as $url ){
6022
				if ( preg_match( $url, site_url() ) ) {
6023
					$is_staging = true;
6024
					break;
6025
				}
6026
			}
6027
		}
6028
6029
		if ( isset( $known_staging['constants'] ) ) {
6030
			foreach ( $known_staging['constants'] as $constant ) {
6031
				if ( defined( $constant ) && constant( $constant ) ) {
6032
					$is_staging = true;
6033
				}
6034
			}
6035
		}
6036
6037
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6038
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6039
			$is_staging = true;
6040
		}
6041
6042
		/**
6043
		 * Filters is_staging_site check.
6044
		 *
6045
		 * @since 3.9.0
6046
		 *
6047
		 * @param bool $is_staging If the current site is a staging site.
6048
		 */
6049
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6050
	}
6051
6052
	/**
6053
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6054
	 *
6055
	 * @since 4.4.0
6056
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6057
	 *
6058
	 * @return bool
6059
	 */
6060
	public static function validate_sync_error_idc_option() {
6061
		$is_valid = false;
6062
6063
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6064
		if ( false === $idc_allowed ) {
6065
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6066
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6067
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6068
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6069
				$transient_duration = HOUR_IN_SECONDS;
6070
			} else {
6071
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6072
				$idc_allowed = '1';
6073
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6074
			}
6075
6076
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6077
		}
6078
6079
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6080
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6081
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6082
			$local_options = self::get_sync_error_idc_option();
6083
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6084
				$is_valid = true;
6085
			}
6086
		}
6087
6088
		/**
6089
		 * Filters whether the sync_error_idc option is valid.
6090
		 *
6091
		 * @since 4.4.0
6092
		 *
6093
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6094
		 */
6095
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6096
6097
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6098
			// Since the option exists, and did not validate, delete it
6099
			Jetpack_Options::delete_option( 'sync_error_idc' );
6100
		}
6101
6102
		return $is_valid;
6103
	}
6104
6105
	/**
6106
	 * Normalizes a url by doing three things:
6107
	 *  - Strips protocol
6108
	 *  - Strips www
6109
	 *  - Adds a trailing slash
6110
	 *
6111
	 * @since 4.4.0
6112
	 * @param string $url
6113
	 * @return WP_Error|string
6114
	 */
6115
	public static function normalize_url_protocol_agnostic( $url ) {
6116
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6117
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6118
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6119
		}
6120
6121
		// Strip www and protocols
6122
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6123
		return $url;
6124
	}
6125
6126
	/**
6127
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6128
	 *
6129
	 * @since 4.4.0
6130
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6131
	 *
6132
	 * @param array $response
6133
	 * @return array Array of the local urls, wpcom urls, and error code
6134
	 */
6135
	public static function get_sync_error_idc_option( $response = array() ) {
6136
		// Since the local options will hit the database directly, store the values
6137
		// in a transient to allow for autoloading and caching on subsequent views.
6138
		$local_options = get_transient( 'jetpack_idc_local' );
6139
		if ( false === $local_options ) {
6140
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6141
			$local_options = array(
6142
				'home'    => Jetpack_Sync_Functions::home_url(),
6143
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6144
			);
6145
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6146
		}
6147
6148
		$options = array_merge( $local_options, $response );
6149
6150
		$returned_values = array();
6151
		foreach( $options as $key => $option ) {
6152
			if ( 'error_code' === $key ) {
6153
				$returned_values[ $key ] = $option;
6154
				continue;
6155
			}
6156
6157
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6158
				continue;
6159
			}
6160
6161
			$returned_values[ $key ] = $normalized_url;
6162
		}
6163
6164
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6165
6166
		return $returned_values;
6167
	}
6168
6169
	/**
6170
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6171
	 * If set to true, the site will be put into staging mode.
6172
	 *
6173
	 * @since 4.3.2
6174
	 * @return bool
6175
	 */
6176
	public static function sync_idc_optin() {
6177
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6178
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6179
		} else {
6180
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6181
		}
6182
6183
		/**
6184
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6185
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6186
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6187
		 *
6188
		 * @since 4.3.2
6189
		 *
6190
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6191
		 */
6192
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6193
	}
6194
6195
	/**
6196
	 * Maybe Use a .min.css stylesheet, maybe not.
6197
	 *
6198
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6199
	 */
6200
	public static function maybe_min_asset( $url, $path, $plugin ) {
6201
		// Short out on things trying to find actual paths.
6202
		if ( ! $path || empty( $plugin ) ) {
6203
			return $url;
6204
		}
6205
6206
		$path = ltrim( $path, '/' );
6207
6208
		// Strip out the abspath.
6209
		$base = dirname( plugin_basename( $plugin ) );
6210
6211
		// Short out on non-Jetpack assets.
6212
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6213
			return $url;
6214
		}
6215
6216
		// File name parsing.
6217
		$file              = "{$base}/{$path}";
6218
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6219
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6220
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6221
		$extension         = array_shift( $file_name_parts_r );
6222
6223
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6224
			// Already pointing at the minified version.
6225
			if ( 'min' === $file_name_parts_r[0] ) {
6226
				return $url;
6227
			}
6228
6229
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6230
			if ( file_exists( $min_full_path ) ) {
6231
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6232
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6233
				if ( 'css' === $extension ) {
6234
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6235
					self::$min_assets[ $key ] = $path;
6236
				}
6237
			}
6238
		}
6239
6240
		return $url;
6241
	}
6242
6243
	/**
6244
	 * If the asset is minified, let's flag .min as the suffix.
6245
	 *
6246
	 * Attached to `style_loader_src` filter.
6247
	 *
6248
	 * @param string $tag The tag that would link to the external asset.
6249
	 * @param string $handle The registered handle of the script in question.
6250
	 * @param string $href The url of the asset in question.
6251
	 */
6252
	public static function set_suffix_on_min( $src, $handle ) {
6253
		if ( false === strpos( $src, '.min.css' ) ) {
6254
			return $src;
6255
		}
6256
6257
		if ( ! empty( self::$min_assets ) ) {
6258
			foreach ( self::$min_assets as $file => $path ) {
6259
				if ( false !== strpos( $src, $file ) ) {
6260
					wp_style_add_data( $handle, 'suffix', '.min' );
6261
					return $src;
6262
				}
6263
			}
6264
		}
6265
6266
		return $src;
6267
	}
6268
6269
	/**
6270
	 * Maybe inlines a stylesheet.
6271
	 *
6272
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6273
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6274
	 *
6275
	 * Attached to `style_loader_tag` filter.
6276
	 *
6277
	 * @param string $tag The tag that would link to the external asset.
6278
	 * @param string $handle The registered handle of the script in question.
6279
	 *
6280
	 * @return string
6281
	 */
6282
	public static function maybe_inline_style( $tag, $handle ) {
6283
		global $wp_styles;
6284
		$item = $wp_styles->registered[ $handle ];
6285
6286
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6287
			return $tag;
6288
		}
6289
6290
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6291
			$href = $matches[1];
6292
			// Strip off query string
6293
			if ( $pos = strpos( $href, '?' ) ) {
6294
				$href = substr( $href, 0, $pos );
6295
			}
6296
			// Strip off fragment
6297
			if ( $pos = strpos( $href, '#' ) ) {
6298
				$href = substr( $href, 0, $pos );
6299
			}
6300
		} else {
6301
			return $tag;
6302
		}
6303
6304
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6305
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6306
			return $tag;
6307
		}
6308
6309
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6310
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6311
			// And this isn't the pass that actually deals with the RTL version...
6312
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6313
				// Short out, as the RTL version will deal with it in a moment.
6314
				return $tag;
6315
			}
6316
		}
6317
6318
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6319
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6320
		if ( $css ) {
6321
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6322
			if ( empty( $item->extra['after'] ) ) {
6323
				wp_add_inline_style( $handle, $css );
6324
			} else {
6325
				array_unshift( $item->extra['after'], $css );
6326
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6327
			}
6328
		}
6329
6330
		return $tag;
6331
	}
6332
6333
	/**
6334
	 * Loads a view file from the views
6335
	 *
6336
	 * Data passed in with the $data parameter will be available in the
6337
	 * template file as $data['value']
6338
	 *
6339
	 * @param string $template - Template file to load
6340
	 * @param array $data - Any data to pass along to the template
6341
	 * @return boolean - If template file was found
6342
	 **/
6343
	public function load_view( $template, $data = array() ) {
6344
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6345
6346
		if( file_exists( $views_dir . $template ) ) {
6347
			require_once( $views_dir . $template );
6348
			return true;
6349
		}
6350
6351
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6352
		return false;
6353
	}
6354
6355
	/**
6356
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6357
	 */
6358
	public function deprecated_hooks() {
6359
		global $wp_filter;
6360
6361
		/*
6362
		 * Format:
6363
		 * deprecated_filter_name => replacement_name
6364
		 *
6365
		 * If there is no replacement, use null for replacement_name
6366
		 */
6367
		$deprecated_list = array(
6368
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6369
			'wpl_sharing_2014_1'                                     => null,
6370
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6371
			'jetpack_identity_crisis_options_to_check'               => null,
6372
			'update_option_jetpack_single_user_site'                 => null,
6373
			'audio_player_default_colors'                            => null,
6374
			'add_option_jetpack_featured_images_enabled'             => null,
6375
			'add_option_jetpack_update_details'                      => null,
6376
			'add_option_jetpack_updates'                             => null,
6377
			'add_option_jetpack_network_name'                        => null,
6378
			'add_option_jetpack_network_allow_new_registrations'     => null,
6379
			'add_option_jetpack_network_add_new_users'               => null,
6380
			'add_option_jetpack_network_site_upload_space'           => null,
6381
			'add_option_jetpack_network_upload_file_types'           => null,
6382
			'add_option_jetpack_network_enable_administration_menus' => null,
6383
			'add_option_jetpack_is_multi_site'                       => null,
6384
			'add_option_jetpack_is_main_network'                     => null,
6385
			'add_option_jetpack_main_network_site'                   => null,
6386
			'jetpack_sync_all_registered_options'                    => null,
6387
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6388
			'jetpack_is_post_mailable'                               => null,
6389
			'jetpack_seo_site_host'                                  => null,
6390
		);
6391
6392
		// This is a silly loop depth. Better way?
6393
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6394
			if ( has_action( $hook ) ) {
6395
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6396
					foreach( $values AS $hooked ) {
6397
						if ( is_callable( $hooked['function'] ) ) {
6398
							$function_name = 'an anonymous function';
6399
						} else {
6400
							$function_name = $hooked['function'];
6401
						}
6402
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6403
					}
6404
				}
6405
			}
6406
		}
6407
	}
6408
6409
	/**
6410
	 * Converts any url in a stylesheet, to the correct absolute url.
6411
	 *
6412
	 * Considerations:
6413
	 *  - Normal, relative URLs     `feh.png`
6414
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6415
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6416
	 *  - Absolute URLs             `http://domain.com/feh.png`
6417
	 *  - Domain root relative URLs `/feh.png`
6418
	 *
6419
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6420
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6421
	 *
6422
	 * @return mixed|string
6423
	 */
6424
	public static function absolutize_css_urls( $css, $css_file_url ) {
6425
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6426
		$css_dir = dirname( $css_file_url );
6427
		$p       = parse_url( $css_dir );
6428
		$domain  = sprintf(
6429
					'%1$s//%2$s%3$s%4$s',
6430
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6431
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6432
					$p['host'],
6433
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6434
				);
6435
6436
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6437
			$find = $replace = array();
6438
			foreach ( $matches as $match ) {
6439
				$url = trim( $match['path'], "'\" \t" );
6440
6441
				// If this is a data url, we don't want to mess with it.
6442
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6443
					continue;
6444
				}
6445
6446
				// If this is an absolute or protocol-agnostic url,
6447
				// we don't want to mess with it.
6448
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6449
					continue;
6450
				}
6451
6452
				switch ( substr( $url, 0, 1 ) ) {
6453
					case '/':
6454
						$absolute = $domain . $url;
6455
						break;
6456
					default:
6457
						$absolute = $css_dir . '/' . $url;
6458
				}
6459
6460
				$find[]    = $match[0];
6461
				$replace[] = sprintf( 'url("%s")', $absolute );
6462
			}
6463
			$css = str_replace( $find, $replace, $css );
6464
		}
6465
6466
		return $css;
6467
	}
6468
6469
	/**
6470
	 * This methods removes all of the registered css files on the front end
6471
	 * from Jetpack in favor of using a single file. In effect "imploding"
6472
	 * all the files into one file.
6473
	 *
6474
	 * Pros:
6475
	 * - Uses only ONE css asset connection instead of 15
6476
	 * - Saves a minimum of 56k
6477
	 * - Reduces server load
6478
	 * - Reduces time to first painted byte
6479
	 *
6480
	 * Cons:
6481
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6482
	 *		should not cause any issues with themes.
6483
	 * - Plugins/themes dequeuing styles no longer do anything. See
6484
	 *		jetpack_implode_frontend_css filter for a workaround
6485
	 *
6486
	 * For some situations developers may wish to disable css imploding and
6487
	 * instead operate in legacy mode where each file loads seperately and
6488
	 * can be edited individually or dequeued. This can be accomplished with
6489
	 * the following line:
6490
	 *
6491
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6492
	 *
6493
	 * @since 3.2
6494
	 **/
6495
	public function implode_frontend_css( $travis_test = false ) {
6496
		$do_implode = true;
6497
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6498
			$do_implode = false;
6499
		}
6500
6501
		/**
6502
		 * Allow CSS to be concatenated into a single jetpack.css file.
6503
		 *
6504
		 * @since 3.2.0
6505
		 *
6506
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6507
		 */
6508
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6509
6510
		// Do not use the imploded file when default behaviour was altered through the filter
6511
		if ( ! $do_implode ) {
6512
			return;
6513
		}
6514
6515
		// We do not want to use the imploded file in dev mode, or if not connected
6516
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6517
			if ( ! $travis_test ) {
6518
				return;
6519
			}
6520
		}
6521
6522
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6523
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6524
			return;
6525
		}
6526
6527
		/*
6528
		 * Now we assume Jetpack is connected and able to serve the single
6529
		 * file.
6530
		 *
6531
		 * In the future there will be a check here to serve the file locally
6532
		 * or potentially from the Jetpack CDN
6533
		 *
6534
		 * For now:
6535
		 * - Enqueue a single imploded css file
6536
		 * - Zero out the style_loader_tag for the bundled ones
6537
		 * - Be happy, drink scotch
6538
		 */
6539
6540
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6541
6542
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6543
6544
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6545
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6546
	}
6547
6548
	function concat_remove_style_loader_tag( $tag, $handle ) {
6549
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6550
			$tag = '';
6551
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6552
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6553
			}
6554
		}
6555
6556
		return $tag;
6557
	}
6558
6559
	/*
6560
	 * Check the heartbeat data
6561
	 *
6562
	 * Organizes the heartbeat data by severity.  For example, if the site
6563
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6564
	 *
6565
	 * Data will be added to "caution" array, if it either:
6566
	 *  - Out of date Jetpack version
6567
	 *  - Out of date WP version
6568
	 *  - Out of date PHP version
6569
	 *
6570
	 * $return array $filtered_data
6571
	 */
6572
	public static function jetpack_check_heartbeat_data() {
6573
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6574
6575
		$good    = array();
6576
		$caution = array();
6577
		$bad     = array();
6578
6579
		foreach ( $raw_data as $stat => $value ) {
6580
6581
			// Check jetpack version
6582
			if ( 'version' == $stat ) {
6583
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6584
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6585
					continue;
6586
				}
6587
			}
6588
6589
			// Check WP version
6590
			if ( 'wp-version' == $stat ) {
6591
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6592
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6593
					continue;
6594
				}
6595
			}
6596
6597
			// Check PHP version
6598
			if ( 'php-version' == $stat ) {
6599
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6600
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6601
					continue;
6602
				}
6603
			}
6604
6605
			// Check ID crisis
6606
			if ( 'identitycrisis' == $stat ) {
6607
				if ( 'yes' == $value ) {
6608
					$bad[ $stat ] = $value;
6609
					continue;
6610
				}
6611
			}
6612
6613
			// The rest are good :)
6614
			$good[ $stat ] = $value;
6615
		}
6616
6617
		$filtered_data = array(
6618
			'good'    => $good,
6619
			'caution' => $caution,
6620
			'bad'     => $bad
6621
		);
6622
6623
		return $filtered_data;
6624
	}
6625
6626
6627
	/*
6628
	 * This method is used to organize all options that can be reset
6629
	 * without disconnecting Jetpack.
6630
	 *
6631
	 * It is used in class.jetpack-cli.php to reset options
6632
	 *
6633
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6634
	 *
6635
	 * @return array of options to delete.
6636
	 */
6637
	public static function get_jetpack_options_for_reset() {
6638
		return Jetpack_Options::get_options_for_reset();
6639
	}
6640
6641
	/**
6642
	 * Check if an option of a Jetpack module has been updated.
6643
	 *
6644
	 * If any module option has been updated before Jump Start has been dismissed,
6645
	 * update the 'jumpstart' option so we can hide Jump Start.
6646
	 *
6647
	 * @param string $option_name
6648
	 *
6649
	 * @return bool
6650
	 */
6651
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6652
		// Bail if Jump Start has already been dismissed
6653
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6654
			return false;
6655
		}
6656
6657
		$jetpack = Jetpack::init();
6658
6659
		// Manual build of module options
6660
		$option_names = self::get_jetpack_options_for_reset();
6661
6662
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6663
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6664
6665
			//Jump start is being dismissed send data to MC Stats
6666
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6667
6668
			$jetpack->do_stats( 'server_side' );
6669
		}
6670
6671
	}
6672
6673
	/*
6674
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6675
	 * so we can bring them directly to their site in calypso.
6676
	 *
6677
	 * @param string | url
6678
	 * @return string | url without the guff
6679
	 */
6680
	public static function build_raw_urls( $url ) {
6681
		$strip_http = '/.*?:\/\//i';
6682
		$url = preg_replace( $strip_http, '', $url  );
6683
		$url = str_replace( '/', '::', $url );
6684
		return $url;
6685
	}
6686
6687
	/**
6688
	 * Stores and prints out domains to prefetch for page speed optimization.
6689
	 *
6690
	 * @param mixed $new_urls
6691
	 */
6692
	public static function dns_prefetch( $new_urls = null ) {
6693
		static $prefetch_urls = array();
6694
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6695
			echo "\r\n";
6696
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6697
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6698
			}
6699
		} elseif ( ! empty( $new_urls ) ) {
6700
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6701
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6702
			}
6703
			foreach ( (array) $new_urls as $this_new_url ) {
6704
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6705
			}
6706
			$prefetch_urls = array_unique( $prefetch_urls );
6707
		}
6708
	}
6709
6710
	public function wp_dashboard_setup() {
6711
		if ( self::is_active() ) {
6712
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6713
		}
6714
6715
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6716
			wp_add_dashboard_widget(
6717
				'jetpack_summary_widget',
6718
				esc_html__( 'Site Stats', 'jetpack' ),
6719
				array( __CLASS__, 'dashboard_widget' )
6720
			);
6721
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6722
6723
			// If we're inactive and not in development mode, sort our box to the top.
6724
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6725
				global $wp_meta_boxes;
6726
6727
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6728
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6729
6730
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6731
			}
6732
		}
6733
	}
6734
6735
	/**
6736
	 * @param mixed $result Value for the user's option
6737
	 * @return mixed
6738
	 */
6739
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6740
		if ( ! is_array( $sorted ) ) {
6741
			return $sorted;
6742
		}
6743
6744
		foreach ( $sorted as $box_context => $ids ) {
6745
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6746
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6747
				continue;
6748
			}
6749
6750
			$ids_array = explode( ',', $ids );
6751
			$key = array_search( 'dashboard_stats', $ids_array );
6752
6753
			if ( false !== $key ) {
6754
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6755
				$ids_array[ $key ] = 'jetpack_summary_widget';
6756
				$sorted[ $box_context ] = implode( ',', $ids_array );
6757
				// We've found it, stop searching, and just return.
6758
				break;
6759
			}
6760
		}
6761
6762
		return $sorted;
6763
	}
6764
6765
	public static function dashboard_widget() {
6766
		/**
6767
		 * Fires when the dashboard is loaded.
6768
		 *
6769
		 * @since 3.4.0
6770
		 */
6771
		do_action( 'jetpack_dashboard_widget' );
6772
	}
6773
6774
	public static function dashboard_widget_footer() {
6775
		?>
6776
		<footer>
6777
6778
		<div class="protect">
6779
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6780
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6781
				<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>
6782
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6783
				<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' ); ?>">
6784
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6785
				</a>
6786
			<?php else : ?>
6787
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6788
			<?php endif; ?>
6789
		</div>
6790
6791
		<div class="akismet">
6792
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6793
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6794
				<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>
6795
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6796
				<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">
6797
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6798
				</a>
6799
			<?php else : ?>
6800
				<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>
6801
			<?php endif; ?>
6802
		</div>
6803
6804
		</footer>
6805
		<?php
6806
	}
6807
6808
	/**
6809
	 * Return string containing the Jetpack logo.
6810
	 *
6811
	 * @since 3.9.0
6812
	 *
6813
	 * @return string
6814
	 */
6815
	public static function get_jp_emblem() {
6816
		return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0" y="0" width="20" height="20" viewBox="0 0 172.9 172.9" enable-background="new 0 0 172.9 172.9" xml:space="preserve"><path d="M86.4 0C38.7 0 0 38.7 0 86.4c0 47.7 38.7 86.4 86.4 86.4s86.4-38.7 86.4-86.4C172.9 38.7 134.2 0 86.4 0zM83.1 106.6l-27.1-6.9C49 98 45.7 90.1 49.3 84l33.8-58.5V106.6zM124.9 88.9l-33.8 58.5V66.3l27.1 6.9C125.1 74.9 128.4 82.8 124.9 88.9z" /></svg>';
6817
	}
6818
6819
	/*
6820
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6821
	 */
6822
	function jetpack_icon_user_connected( $columns ) {
6823
		$columns['user_jetpack'] = '';
6824
		return $columns;
6825
	}
6826
6827
	/*
6828
	 * Show Jetpack icon if the user is linked.
6829
	 */
6830
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6831
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6832
			$emblem_html = sprintf(
6833
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6834
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6835
				Jetpack::get_jp_emblem()
6836
			);
6837
			return $emblem_html;
6838
		}
6839
6840
		return $val;
6841
	}
6842
6843
	/*
6844
	 * Style the Jetpack user column
6845
	 */
6846
	function jetpack_user_col_style() {
6847
		global $current_screen;
6848
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6849
			<style>
6850
				.fixed .column-user_jetpack {
6851
					width: 21px;
6852
				}
6853
				.jp-emblem-user-admin svg {
6854
					width: 20px;
6855
					height: 20px;
6856
				}
6857
				.jp-emblem-user-admin path {
6858
					fill: #8cc258;
6859
				}
6860
			</style>
6861
		<?php }
6862
	}
6863
6864
	/**
6865
	 * Checks if Akismet is active and working.
6866
	 *
6867
	 * @since  5.1.0
6868
	 * @return bool True = Akismet available. False = Aksimet not available.
6869
	 */
6870
	public static function is_akismet_active() {
6871
		if ( method_exists( 'Akismet' , 'http_post' ) || function_exists( 'akismet_http_post' ) ) {
6872
			return true;
6873
		}
6874
		return false;
6875
	}
6876
6877
	/**
6878
	 * Checks if one or more function names is in debug_backtrace
6879
	 *
6880
	 * @param $names Mixed string name of function or array of string names of functions
6881
	 *
6882
	 * @return bool
6883
	 */
6884
	public static function is_function_in_backtrace( $names ) {
6885
		$backtrace = debug_backtrace( false );
6886
		if ( ! is_array( $names ) ) {
6887
			$names = array( $names );
6888
		}
6889
		$names_as_keys = array_flip( $names );
6890
6891
		//Do check in constant O(1) time for PHP5.5+
6892
		if ( function_exists( 'array_column' ) ) {
6893
			$backtrace_functions = array_column( $backtrace, 'function' );
6894
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6895
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6896
			return ! empty ( $intersection );
6897
		}
6898
6899
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6900
		foreach ( $backtrace as $call ) {
6901
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6902
				return true;
6903
			}
6904
		}
6905
		return false;
6906
	}
6907
6908
	/**
6909
	 * Given a minified path, and a non-minified path, will return
6910
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6911
	 *
6912
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6913
	 * root Jetpack directory.
6914
	 *
6915
	 * @since 5.6.0
6916
	 *
6917
	 * @param string $min_path
6918
	 * @param string $non_min_path
6919
	 * @return string The URL to the file
6920
	 */
6921
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6922
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
6923
			? $non_min_path
6924
			: $min_path;
6925
6926
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6927
	}
6928
}
6929