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

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

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