Completed
Push — try/wpcom-color-scheme-gutenbe... ( 6399f0 )
by Marin
17:19
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
		'eu-cookie-law-style',
60
		'flickr-widget-style',
61
		'jetpack-search-widget',
62
		'jetpack-simple-payments-widget-style',
63
	);
64
65
	/**
66
	 * Contains all assets that have had their URL rewritten to minified versions.
67
	 *
68
	 * @var array
69
	 */
70
	static $min_assets = array();
71
72
	public $plugins_to_deactivate = array(
73
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
74
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
75
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
76
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
77
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
78
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
79
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
80
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
81
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
82
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
83
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
84
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
85
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
86
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
87
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
88
	);
89
90
	static $capability_translations = array(
91
		'administrator' => 'manage_options',
92
		'editor'        => 'edit_others_posts',
93
		'author'        => 'publish_posts',
94
		'contributor'   => 'edit_posts',
95
		'subscriber'    => 'read',
96
	);
97
98
	/**
99
	 * Map of modules that have conflicts with plugins and should not be auto-activated
100
	 * if the plugins are active.  Used by filter_default_modules
101
	 *
102
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
103
	 * change `module-slug` and add this to your plugin:
104
	 *
105
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
106
	 * function my_jetpack_get_default_modules( $modules ) {
107
	 *     return array_diff( $modules, array( 'module-slug' ) );
108
	 * }
109
	 *
110
	 * @var array
111
	 */
112
	private $conflicting_plugins = array(
113
		'comments'          => array(
114
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
115
			'Disqus'                               => 'disqus-comment-system/disqus.php',
116
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
117
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
118
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
119
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
120
		),
121
		'comment-likes' => array(
122
			'Epoch'                                => 'epoch/plugincore.php',
123
		),
124
		'contact-form'      => array(
125
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
126
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
127
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
128
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
129
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
130
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
131
		),
132
		'minileven'         => array(
133
			'WPtouch'                              => 'wptouch/wptouch.php',
134
		),
135
		'latex'             => array(
136
			'LaTeX for WordPress'                  => 'latex/latex.php',
137
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
138
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
139
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
140
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
141
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
142
		),
143
		'protect'           => array(
144
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
145
			'Captcha'                              => 'captcha/captcha.php',
146
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
147
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
148
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
149
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
150
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
151
			'Security-protection'                  => 'security-protection/security-protection.php',
152
			'Login Security'                       => 'login-security/login-security.php',
153
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
154
			'Wordfence Security'                   => 'wordfence/wordfence.php',
155
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
156
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
157
		),
158
		'random-redirect'   => array(
159
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
160
		),
161
		'related-posts'     => array(
162
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
163
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
164
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
165
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
166
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
167
			'outbrain'                             => 'outbrain/outbrain.php',
168
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
169
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
170
		),
171
		'sharedaddy'        => array(
172
			'AddThis'                              => 'addthis/addthis_social_widget.php',
173
			'Add To Any'                           => 'add-to-any/add-to-any.php',
174
			'ShareThis'                            => 'share-this/sharethis.php',
175
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
176
		),
177
		'seo-tools' => array(
178
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
179
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
180
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
181
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
182
			'The SEO Framework'                    => 'autodescription/autodescription.php',
183
		),
184
		'verification-tools' => array(
185
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
186
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
187
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
188
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
189
			'The SEO Framework'                    => 'autodescription/autodescription.php',
190
		),
191
		'widget-visibility' => array(
192
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
193
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
194
		),
195
		'sitemaps' => array(
196
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
197
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
198
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
199
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
200
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
201
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
202
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
203
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
204
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
205
			'The SEO Framework'                    => 'autodescription/autodescription.php',
206
			'Sitemap'                              => 'sitemap/sitemap.php',
207
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
208
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
209
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
210
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
211
		),
212
		'lazy-images' => array(
213
			'Lazy Load'              => 'lazy-load/lazy-load.php',
214
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
215
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
216
		),
217
	);
218
219
	/**
220
	 * Plugins for which we turn off our Facebook OG Tags implementation.
221
	 *
222
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
223
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
224
	 *
225
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
226
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
227
	 */
228
	private $open_graph_conflicting_plugins = array(
229
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
230
		                                                         // 2 Click Social Media Buttons
231
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
232
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
233
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
234
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
235
		                                                         // Open Graph Meta Tags by Heateor
236
		'facebook/facebook.php',                                 // Facebook (official plugin)
237
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
238
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
239
		                                                         // Facebook Featured Image & OG Meta Tags
240
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
241
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
242
		                                                         // Facebook Open Graph Meta Tags for WordPress
243
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
244
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
245
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
246
		                                                         // Fedmich's Facebook Open Graph Meta
247
		'network-publisher/networkpub.php',                      // Network Publisher
248
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
249
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
250
		                                                         // NextScripts SNAP
251
		'og-tags/og-tags.php',                                   // OG Tags
252
		'opengraph/opengraph.php',                               // Open Graph
253
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
254
		                                                         // Open Graph Protocol Framework
255
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
256
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
257
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
258
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
259
		'sharepress/sharepress.php',                             // SharePress
260
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
261
		'social-discussions/social-discussions.php',             // Social Discussions
262
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
263
		'socialize/socialize.php',                               // Socialize
264
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
265
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
266
		                                                         // Tweet, Like, Google +1 and Share
267
		'wordbooker/wordbooker.php',                             // Wordbooker
268
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
269
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
270
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
271
		                                                         // WP Facebook Like Send & Open Graph Meta
272
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
273
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
274
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
275
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
276
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
277
	);
278
279
	/**
280
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
281
	 */
282
	private $twitter_cards_conflicting_plugins = array(
283
	//	'twitter/twitter.php',                       // The official one handles this on its own.
284
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
285
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
286
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
287
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
288
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
289
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
290
		'twitter-cards/twitter-cards.php',           // Twitter Cards
291
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
292
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
293
	);
294
295
	/**
296
	 * Message to display in admin_notice
297
	 * @var string
298
	 */
299
	public $message = '';
300
301
	/**
302
	 * Error to display in admin_notice
303
	 * @var string
304
	 */
305
	public $error = '';
306
307
	/**
308
	 * Modules that need more privacy description.
309
	 * @var string
310
	 */
311
	public $privacy_checks = '';
312
313
	/**
314
	 * Stats to record once the page loads
315
	 *
316
	 * @var array
317
	 */
318
	public $stats = array();
319
320
	/**
321
	 * Jetpack_Sync object
322
	 */
323
	public $sync;
324
325
	/**
326
	 * Verified data for JSON authorization request
327
	 */
328
	public $json_api_authorization_request = array();
329
330
	/**
331
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
332
	 */
333
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
334
335
	/**
336
	 * Holds the singleton instance of this class
337
	 * @since 2.3.3
338
	 * @var Jetpack
339
	 */
340
	static $instance = false;
341
342
	/**
343
	 * Singleton
344
	 * @static
345
	 */
346
	public static function init() {
347
		if ( ! self::$instance ) {
348
			self::$instance = new Jetpack;
349
350
			self::$instance->plugin_upgrade();
351
		}
352
353
		return self::$instance;
354
	}
355
356
	/**
357
	 * Must never be called statically
358
	 */
359
	function plugin_upgrade() {
360
		if ( Jetpack::is_active() ) {
361
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
362
			if ( JETPACK__VERSION != $version ) {
363
				// Prevent multiple upgrades at once - only a single process should trigger
364
				// an upgrade to avoid stampedes
365
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
366
					return;
367
				}
368
369
				// Set a short lock to prevent multiple instances of the upgrade
370
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
371
372
				// check which active modules actually exist and remove others from active_modules list
373
				$unfiltered_modules = Jetpack::get_active_modules();
374
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
375
				if ( array_diff( $unfiltered_modules, $modules ) ) {
376
					Jetpack::update_active_modules( $modules );
377
				}
378
379
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
380
381
				// Upgrade to 4.3.0
382
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
383
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
384
				}
385
386
				// Make sure Markdown for posts gets turned back on
387
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
388
					update_option( 'wpcom_publish_posts_with_markdown', true );
389
				}
390
391
				if ( did_action( 'wp_loaded' ) ) {
392
					self::upgrade_on_load();
393
				} else {
394
					add_action(
395
						'wp_loaded',
396
						array( __CLASS__, 'upgrade_on_load' )
397
					);
398
				}
399
			}
400
		}
401
	}
402
403
	/**
404
	 * Runs upgrade routines that need to have modules loaded.
405
	 */
406
	static function upgrade_on_load() {
407
408
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
409
		// This can happen in case Jetpack has been just upgraded and is
410
		// being initialized late during the page load. In this case we wait
411
		// until the next proper admin page load with Jetpack active.
412
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
413
			delete_transient( self::$plugin_upgrade_lock_key );
414
415
			return;
416
		}
417
418
		Jetpack::maybe_set_version_option();
419
420
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
421
			Jetpack_Widget_Conditions::migrate_post_type_rules();
422
		}
423
424
		if (
425
			class_exists( 'Jetpack_Sitemap_Manager' )
426
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
427
		) {
428
			do_action( 'jetpack_sitemaps_purge_data' );
429
		}
430
431
		delete_transient( self::$plugin_upgrade_lock_key );
432
	}
433
434
	static function activate_manage( ) {
435
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
436
			self::activate_module( 'manage', false, false );
437
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
438
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
439
		}
440
	}
441
442
	static function update_active_modules( $modules ) {
443
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
444
445
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
446
447
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
448
			$new_active_modules = array_diff( $modules, $current_modules );
449
			foreach( $new_active_modules as $module ) {
450
				/**
451
				 * Fires when a specific module is activated.
452
				 *
453
				 * @since 1.9.0
454
				 *
455
				 * @param string $module Module slug.
456
				 * @param boolean $success whether the module was activated. @since 4.2
457
				 */
458
				do_action( 'jetpack_activate_module', $module, $success );
459
460
				/**
461
				 * Fires when a module is activated.
462
				 * The dynamic part of the filter, $module, is the module slug.
463
				 *
464
				 * @since 1.9.0
465
				 *
466
				 * @param string $module Module slug.
467
				 */
468
				do_action( "jetpack_activate_module_$module", $module );
469
			}
470
471
			$new_deactive_modules = array_diff( $current_modules, $modules );
472
			foreach( $new_deactive_modules as $module ) {
473
				/**
474
				 * Fired after a module has been deactivated.
475
				 *
476
				 * @since 4.2.0
477
				 *
478
				 * @param string $module Module slug.
479
				 * @param boolean $success whether the module was deactivated.
480
				 */
481
				do_action( 'jetpack_deactivate_module', $module, $success );
482
				/**
483
				 * Fires when a module is deactivated.
484
				 * The dynamic part of the filter, $module, is the module slug.
485
				 *
486
				 * @since 1.9.0
487
				 *
488
				 * @param string $module Module slug.
489
				 */
490
				do_action( "jetpack_deactivate_module_$module", $module );
491
			}
492
		}
493
494
		return $success;
495
	}
496
497
	static function delete_active_modules() {
498
		self::update_active_modules( array() );
499
	}
500
501
	/**
502
	 * Constructor.  Initializes WordPress hooks
503
	 */
504
	private function __construct() {
505
		/*
506
		 * Check for and alert any deprecated hooks
507
		 */
508
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
509
510
		/*
511
		 * Enable enhanced handling of previewing sites in Calypso
512
		 */
513
		if ( Jetpack::is_active() ) {
514
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
515
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
516
		}
517
518
		/*
519
		 * Load things that should only be in Network Admin.
520
		 *
521
		 * For now blow away everything else until a more full
522
		 * understanding of what is needed at the network level is
523
		 * available
524
		 */
525
		if( is_multisite() ) {
526
			Jetpack_Network::init();
527
		}
528
529
		// Load Gutenberg editor blocks
530
		add_action( 'init', array( $this, 'load_jetpack_gutenberg' ) );
531
532
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
533
534
		// Unlink user before deleting the user from .com
535
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
536
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
537
538
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
539
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
540
541
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
542
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
543
544
			$this->require_jetpack_authentication();
545
546
			if ( Jetpack::is_active() ) {
547
				// Hack to preserve $HTTP_RAW_POST_DATA
548
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
549
550
				$signed = $this->verify_xml_rpc_signature();
551 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
552
					// The actual API methods.
553
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
554
				} else {
555
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
556
					// active Jetpack connection, so that additional users can link their account.
557
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
558
				}
559 View Code Duplication
			} else {
560
				// The bootstrap API methods.
561
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
562
				$signed = $this->verify_xml_rpc_signature();
563
				if ( $signed && ! is_wp_error( $signed ) ) {
564
					// the jetpack Provision method is available for blog-token-signed requests
565
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
566
				}
567
			}
568
569
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
570
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
571
		} elseif (
572
			is_admin() &&
573
			isset( $_POST['action'] ) && (
574
				'jetpack_upload_file' == $_POST['action'] ||
575
				'jetpack_update_file' == $_POST['action']
576
			)
577
		) {
578
			$this->require_jetpack_authentication();
579
			$this->add_remote_request_handlers();
580
		} else {
581
			if ( Jetpack::is_active() ) {
582
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
583
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
584
			}
585
		}
586
587
		if ( Jetpack::is_active() ) {
588
			Jetpack_Heartbeat::init();
589
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
590
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
591
				Jetpack_Search_Performance_Logger::init();
592
			}
593
		}
594
595
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
596
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
597
598
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
599
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
600
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
601
		}
602
603
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
604
605
		add_action( 'admin_init', array( $this, 'admin_init' ) );
606
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
607
608
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
609
610
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
611
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
612
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
613
614
		// returns HTTPS support status
615
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
616
617
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
618
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
619
620
		// JITM AJAX callback function
621
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
622
623
		// Universal ajax callback for all tracking events triggered via js
624
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
625
626
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
627
628
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
629
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
630
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
631
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
632
633
		// gutenberg locale
634
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_gutenberg_locale' ) );
635
636
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
637
638
		/**
639
		 * These actions run checks to load additional files.
640
		 * They check for external files or plugins, so they need to run as late as possible.
641
		 */
642
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
643
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
644
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
645
646
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
647
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
648
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
649
650
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
651
652
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
653
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
654
655
		// A filter to control all just in time messages
656
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
657
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
658
659
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
660
		// We should make sure to only do this for front end links.
661
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
662
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
663
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
664
665
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
666
			//so they point moderation links on emails to Calypso
667
			jetpack_require_lib( 'functions.wp-notify' );
668
		}
669
670
		// Update the Jetpack plan from API on heartbeats
671
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
672
673
		/**
674
		 * This is the hack to concatenate all css files into one.
675
		 * For description and reasoning see the implode_frontend_css method
676
		 *
677
		 * Super late priority so we catch all the registered styles
678
		 */
679
		if( !is_admin() ) {
680
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
681
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
682
		}
683
684
		/**
685
		 * These are sync actions that we need to keep track of for jitms
686
		 */
687
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
688
689
		// Actually push the stats on shutdown.
690
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
691
			add_action( 'shutdown', array( $this, 'push_stats' ) );
692
		}
693
694
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_wpcom_color_scheme_block_assets' ) );
695
	}
696
697
	function enqueue_wpcom_color_scheme_block_assets() {
698
		wp_enqueue_script(
699
			'wpcom_color_scheme_block',
700
			plugins_url( '_inc/build/wpcom-color-scheme/block.js', __FILE__ ),
701
			array(
702
				'wp-api-fetch',
703
				'wp-blocks',
704
				'wp-element',
705
				'wp-i18n',
706
			),
707
			JETPACK__VERSION,
708
			true
709
		);
710
711
		// TODO: fix Calypso's config when building from the SDK
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
712
		wp_add_inline_script(
713
			'wpcom_color_scheme_block',
714
			'window.configData={};',
715
			'before'
716
		);
717
	}
718
719
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
720
		$post = get_post( $post_id );
721
722
		if ( empty( $post ) ) {
723
			return $default_url;
724
		}
725
726
		$post_type = $post->post_type;
727
728
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
729
		// https://en.support.wordpress.com/custom-post-types/
730
		$allowed_post_types = array(
731
			'post' => 'post',
732
			'page' => 'page',
733
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
734
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
735
		);
736
737
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
738
			return $default_url;
739
		}
740
741
		$path_prefix = $allowed_post_types[ $post_type ];
742
743
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
744
745
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
746
	}
747
748
	function point_edit_comment_links_to_calypso( $url ) {
749
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
750
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
751
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
752
			Jetpack::build_raw_urls( get_home_url() ),
753
			$query_args['amp;c']
754
		) );
755
	}
756
757
	function jetpack_track_last_sync_callback( $params ) {
758
		/**
759
		 * Filter to turn off jitm caching
760
		 *
761
		 * @since 5.4.0
762
		 *
763
		 * @param bool false Whether to cache just in time messages
764
		 */
765
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
766
			return $params;
767
		}
768
769
		if ( is_array( $params ) && isset( $params[0] ) ) {
770
			$option = $params[0];
771
			if ( 'active_plugins' === $option ) {
772
				// use the cache if we can, but not terribly important if it gets evicted
773
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
774
			}
775
		}
776
777
		return $params;
778
	}
779
780
	function jetpack_connection_banner_callback() {
781
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
782
783
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
784
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
785
			wp_send_json_success();
786
		}
787
788
		wp_die();
789
	}
790
791
	function jetpack_admin_ajax_tracks_callback() {
792
		// Check for nonce
793
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
794
			wp_die( 'Permissions check failed.' );
795
		}
796
797
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
798
			wp_die( 'No valid event name or type.' );
799
		}
800
801
		$tracks_data = array();
802
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
803
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
804
				$tracks_data = $_REQUEST['tracksEventProp'];
805
			} else {
806
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
807
			}
808
		}
809
810
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
811
		wp_send_json_success();
812
		wp_die();
813
	}
814
815
	/**
816
	 * The callback for the JITM ajax requests.
817
	 */
818
	function jetpack_jitm_ajax_callback() {
819
		// Check for nonce
820
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
821
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
822
		}
823
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
824
			$module_slug = $_REQUEST['jitmModule'];
825
			Jetpack::log( 'activate', $module_slug );
826
			Jetpack::activate_module( $module_slug, false, false );
827
			Jetpack::state( 'message', 'no_message' );
828
829
			//A Jetpack module is being activated through a JITM, track it
830
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
831
			$this->do_stats( 'server_side' );
832
833
			wp_send_json_success();
834
		}
835
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
836
			// get the hide_jitm options array
837
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
838
			$module_slug = $_REQUEST['jitmModule'];
839
840
			if( ! $jetpack_hide_jitm ) {
841
				$jetpack_hide_jitm = array(
842
					$module_slug => 'hide'
843
				);
844
			} else {
845
				$jetpack_hide_jitm[$module_slug] = 'hide';
846
			}
847
848
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
849
850
			//jitm is being dismissed forever, track it
851
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
852
			$this->do_stats( 'server_side' );
853
854
			wp_send_json_success();
855
		}
856 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
857
			$module_slug = $_REQUEST['jitmModule'];
858
859
			// User went to WordPress.com, track this
860
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
861
			$this->do_stats( 'server_side' );
862
863
			wp_send_json_success();
864
		}
865 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
866
			$track = $_REQUEST['jitmModule'];
867
868
			// User is viewing JITM, track it.
869
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
870
			$this->do_stats( 'server_side' );
871
872
			wp_send_json_success();
873
		}
874
	}
875
876
	/**
877
	 * If there are any stats that need to be pushed, but haven't been, push them now.
878
	 */
879
	function push_stats() {
880
		if ( ! empty( $this->stats ) ) {
881
			$this->do_stats( 'server_side' );
882
		}
883
	}
884
885
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
886
		switch( $cap ) {
887
			case 'jetpack_connect' :
888
			case 'jetpack_reconnect' :
889
				if ( Jetpack::is_development_mode() ) {
890
					$caps = array( 'do_not_allow' );
891
					break;
892
				}
893
				/**
894
				 * Pass through. If it's not development mode, these should match disconnect.
895
				 * Let users disconnect if it's development mode, just in case things glitch.
896
				 */
897
			case 'jetpack_disconnect' :
898
				/**
899
				 * In multisite, can individual site admins manage their own connection?
900
				 *
901
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
902
				 */
903
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
904
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
905
						/**
906
						 * We need to update the option name -- it's terribly unclear which
907
						 * direction the override goes.
908
						 *
909
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
910
						 */
911
						$caps = array( 'do_not_allow' );
912
						break;
913
					}
914
				}
915
916
				$caps = array( 'manage_options' );
917
				break;
918
			case 'jetpack_manage_modules' :
919
			case 'jetpack_activate_modules' :
920
			case 'jetpack_deactivate_modules' :
921
				$caps = array( 'manage_options' );
922
				break;
923
			case 'jetpack_configure_modules' :
924
				$caps = array( 'manage_options' );
925
				break;
926
			case 'jetpack_network_admin_page':
927
			case 'jetpack_network_settings_page':
928
				$caps = array( 'manage_network_plugins' );
929
				break;
930
			case 'jetpack_network_sites_page':
931
				$caps = array( 'manage_sites' );
932
				break;
933
			case 'jetpack_admin_page' :
934
				if ( Jetpack::is_development_mode() ) {
935
					$caps = array( 'manage_options' );
936
					break;
937
				} else {
938
					$caps = array( 'read' );
939
				}
940
				break;
941
			case 'jetpack_connect_user' :
942
				if ( Jetpack::is_development_mode() ) {
943
					$caps = array( 'do_not_allow' );
944
					break;
945
				}
946
				$caps = array( 'read' );
947
				break;
948
		}
949
		return $caps;
950
	}
951
952
	function require_jetpack_authentication() {
953
		// Don't let anyone authenticate
954
		$_COOKIE = array();
955
		remove_all_filters( 'authenticate' );
956
		remove_all_actions( 'wp_login_failed' );
957
958
		if ( Jetpack::is_active() ) {
959
			// Allow Jetpack authentication
960
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
961
		}
962
	}
963
964
	/**
965
	 * Load language files
966
	 * @action plugins_loaded
967
	 */
968
	public static function plugin_textdomain() {
969
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
970
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
971
	}
972
973
	/**
974
	 * Register assets for use in various modules and the Jetpack admin page.
975
	 *
976
	 * @uses wp_script_is, wp_register_script, plugins_url
977
	 * @action wp_loaded
978
	 * @return null
979
	 */
980
	public function register_assets() {
981
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
982
			wp_register_script(
983
				'spin',
984
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
985
				false,
986
				'1.3'
987
			);
988
		}
989
990
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
991
			wp_register_script(
992
				'jquery.spin',
993
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
994
				array( 'jquery', 'spin' ),
995
				'1.3'
996
			);
997
		}
998
999 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1000
			wp_register_script(
1001
				'jetpack-gallery-settings',
1002
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1003
				array( 'media-views' ),
1004
				'20121225'
1005
			);
1006
		}
1007
1008
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1009
			wp_register_script(
1010
				'jetpack-twitter-timeline',
1011
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1012
				array( 'jquery' ),
1013
				'4.0.0',
1014
				true
1015
			);
1016
		}
1017
1018
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1019
			wp_register_script(
1020
				'jetpack-facebook-embed',
1021
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1022
				array( 'jquery' ),
1023
				null,
1024
				true
1025
			);
1026
1027
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1028
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1029
			if ( ! is_numeric( $fb_app_id ) ) {
1030
				$fb_app_id = '';
1031
			}
1032
			wp_localize_script(
1033
				'jetpack-facebook-embed',
1034
				'jpfbembed',
1035
				array(
1036
					'appid' => $fb_app_id,
1037
					'locale' => $this->get_locale(),
1038
				)
1039
			);
1040
		}
1041
1042
		/**
1043
		 * As jetpack_register_genericons is by default fired off a hook,
1044
		 * the hook may have already fired by this point.
1045
		 * So, let's just trigger it manually.
1046
		 */
1047
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1048
		jetpack_register_genericons();
1049
1050
		/**
1051
		 * Register the social logos
1052
		 */
1053
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1054
		jetpack_register_social_logos();
1055
1056 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1057
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1058
	}
1059
1060
	/**
1061
	 * Guess locale from language code.
1062
	 *
1063
	 * @param string $lang Language code.
1064
	 * @return string|bool
1065
	 */
1066 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1067
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1068
			return 'en_US';
1069
		}
1070
1071
		if ( ! class_exists( 'GP_Locales' ) ) {
1072
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1073
				return false;
1074
			}
1075
1076
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1077
		}
1078
1079
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1080
			// WP.com: get_locale() returns 'it'
1081
			$locale = GP_Locales::by_slug( $lang );
1082
		} else {
1083
			// Jetpack: get_locale() returns 'it_IT';
1084
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1085
		}
1086
1087
		if ( ! $locale ) {
1088
			return false;
1089
		}
1090
1091
		if ( empty( $locale->facebook_locale ) ) {
1092
			if ( empty( $locale->wp_locale ) ) {
1093
				return false;
1094
			} else {
1095
				// Facebook SDK is smart enough to fall back to en_US if a
1096
				// locale isn't supported. Since supported Facebook locales
1097
				// can fall out of sync, we'll attempt to use the known
1098
				// wp_locale value and rely on said fallback.
1099
				return $locale->wp_locale;
1100
			}
1101
		}
1102
1103
		return $locale->facebook_locale;
1104
	}
1105
1106
	/**
1107
	 * Get the locale.
1108
	 *
1109
	 * @return string|bool
1110
	 */
1111
	function get_locale() {
1112
		$locale = $this->guess_locale_from_lang( get_locale() );
1113
1114
		if ( ! $locale ) {
1115
			$locale = 'en_US';
1116
		}
1117
1118
		return $locale;
1119
	}
1120
1121
	/**
1122
	 * Device Pixels support
1123
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1124
	 */
1125
	function devicepx() {
1126
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1127
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1128
		}
1129
	}
1130
1131
	/**
1132
	 * Return the network_site_url so that .com knows what network this site is a part of.
1133
	 * @param  bool $option
1134
	 * @return string
1135
	 */
1136
	public function jetpack_main_network_site_option( $option ) {
1137
		return network_site_url();
1138
	}
1139
	/**
1140
	 * Network Name.
1141
	 */
1142
	static function network_name( $option = null ) {
1143
		global $current_site;
1144
		return $current_site->site_name;
1145
	}
1146
	/**
1147
	 * Does the network allow new user and site registrations.
1148
	 * @return string
1149
	 */
1150
	static function network_allow_new_registrations( $option = null ) {
1151
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1152
	}
1153
	/**
1154
	 * Does the network allow admins to add new users.
1155
	 * @return boolian
1156
	 */
1157
	static function network_add_new_users( $option = null ) {
1158
		return (bool) get_site_option( 'add_new_users' );
1159
	}
1160
	/**
1161
	 * File upload psace left per site in MB.
1162
	 *  -1 means NO LIMIT.
1163
	 * @return number
1164
	 */
1165
	static function network_site_upload_space( $option = null ) {
1166
		// value in MB
1167
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1168
	}
1169
1170
	/**
1171
	 * Network allowed file types.
1172
	 * @return string
1173
	 */
1174
	static function network_upload_file_types( $option = null ) {
1175
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1176
	}
1177
1178
	/**
1179
	 * Maximum file upload size set by the network.
1180
	 * @return number
1181
	 */
1182
	static function network_max_upload_file_size( $option = null ) {
1183
		// value in KB
1184
		return get_site_option( 'fileupload_maxk', 300 );
1185
	}
1186
1187
	/**
1188
	 * Lets us know if a site allows admins to manage the network.
1189
	 * @return array
1190
	 */
1191
	static function network_enable_administration_menus( $option = null ) {
1192
		return get_site_option( 'menu_items' );
1193
	}
1194
1195
	/**
1196
	 * If a user has been promoted to or demoted from admin, we need to clear the
1197
	 * jetpack_other_linked_admins transient.
1198
	 *
1199
	 * @since 4.3.2
1200
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1201
	 *
1202
	 * @param int    $user_id   The user ID whose role changed.
1203
	 * @param string $role      The new role.
1204
	 * @param array  $old_roles An array of the user's previous roles.
1205
	 */
1206
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1207
		if ( 'administrator' == $role
1208
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1209
			|| is_null( $old_roles )
1210
		) {
1211
			delete_transient( 'jetpack_other_linked_admins' );
1212
		}
1213
	}
1214
1215
	/**
1216
	 * Checks to see if there are any other users available to become primary
1217
	 * Users must both:
1218
	 * - Be linked to wpcom
1219
	 * - Be an admin
1220
	 *
1221
	 * @return mixed False if no other users are linked, Int if there are.
1222
	 */
1223
	static function get_other_linked_admins() {
1224
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1225
1226
		if ( false === $other_linked_users ) {
1227
			$admins = get_users( array( 'role' => 'administrator' ) );
1228
			if ( count( $admins ) > 1 ) {
1229
				$available = array();
1230
				foreach ( $admins as $admin ) {
1231
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1232
						$available[] = $admin->ID;
1233
					}
1234
				}
1235
1236
				$count_connected_admins = count( $available );
1237
				if ( count( $available ) > 1 ) {
1238
					$other_linked_users = $count_connected_admins;
1239
				} else {
1240
					$other_linked_users = 0;
1241
				}
1242
			} else {
1243
				$other_linked_users = 0;
1244
			}
1245
1246
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1247
		}
1248
1249
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1250
	}
1251
1252
	/**
1253
	 * Return whether we are dealing with a multi network setup or not.
1254
	 * The reason we are type casting this is because we want to avoid the situation where
1255
	 * the result is false since when is_main_network_option return false it cases
1256
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1257
	 * database which could be set to anything as opposed to what this function returns.
1258
	 * @param  bool  $option
1259
	 *
1260
	 * @return boolean
1261
	 */
1262
	public function is_main_network_option( $option ) {
1263
		// return '1' or ''
1264
		return (string) (bool) Jetpack::is_multi_network();
1265
	}
1266
1267
	/**
1268
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1269
	 *
1270
	 * @param  string  $option
1271
	 * @return boolean
1272
	 */
1273
	public function is_multisite( $option ) {
1274
		return (string) (bool) is_multisite();
1275
	}
1276
1277
	/**
1278
	 * Implemented since there is no core is multi network function
1279
	 * Right now there is no way to tell if we which network is the dominant network on the system
1280
	 *
1281
	 * @since  3.3
1282
	 * @return boolean
1283
	 */
1284
	public static function is_multi_network() {
1285
		global  $wpdb;
1286
1287
		// if we don't have a multi site setup no need to do any more
1288
		if ( ! is_multisite() ) {
1289
			return false;
1290
		}
1291
1292
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1293
		if ( $num_sites > 1 ) {
1294
			return true;
1295
		} else {
1296
			return false;
1297
		}
1298
	}
1299
1300
	/**
1301
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1302
	 * @return null
1303
	 */
1304
	function update_jetpack_main_network_site_option() {
1305
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1306
	}
1307
	/**
1308
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1309
	 *
1310
	 */
1311
	function update_jetpack_network_settings() {
1312
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1313
		// Only sync this info for the main network site.
1314
	}
1315
1316
	/**
1317
	 * Get back if the current site is single user site.
1318
	 *
1319
	 * @return bool
1320
	 */
1321
	public static function is_single_user_site() {
1322
		global $wpdb;
1323
1324 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1325
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1326
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1327
		}
1328
		return 1 === (int) $some_users;
1329
	}
1330
1331
	/**
1332
	 * Returns true if the site has file write access false otherwise.
1333
	 * @return string ( '1' | '0' )
1334
	 **/
1335
	public static function file_system_write_access() {
1336
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1337
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1338
		}
1339
1340
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1341
1342
		$filesystem_method = get_filesystem_method();
1343
		if ( $filesystem_method === 'direct' ) {
1344
			return 1;
1345
		}
1346
1347
		ob_start();
1348
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1349
		ob_end_clean();
1350
		if ( $filesystem_credentials_are_stored ) {
1351
			return 1;
1352
		}
1353
		return 0;
1354
	}
1355
1356
	/**
1357
	 * Finds out if a site is using a version control system.
1358
	 * @return string ( '1' | '0' )
1359
	 **/
1360
	public static function is_version_controlled() {
1361
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1362
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1363
	}
1364
1365
	/**
1366
	 * Determines whether the current theme supports featured images or not.
1367
	 * @return string ( '1' | '0' )
1368
	 */
1369
	public static function featured_images_enabled() {
1370
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1371
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1372
	}
1373
1374
	/**
1375
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1376
	 *
1377
	 * @deprecated 4.7 use get_avatar_url instead.
1378
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1379
	 * @param int $size Size of the avatar image
1380
	 * @param string $default URL to a default image to use if no avatar is available
1381
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1382
	 *
1383
	 * @return array
1384
	 */
1385
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1386
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1387
		return get_avatar_url( $id_or_email, array(
1388
			'size' => $size,
1389
			'default' => $default,
1390
			'force_default' => $force_display,
1391
		) );
1392
	}
1393
1394
	/**
1395
	 * jetpack_updates is saved in the following schema:
1396
	 *
1397
	 * array (
1398
	 *      'plugins'                       => (int) Number of plugin updates available.
1399
	 *      'themes'                        => (int) Number of theme updates available.
1400
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1401
	 *      'translations'                  => (int) Number of translation updates available.
1402
	 *      'total'                         => (int) Total of all available updates.
1403
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1404
	 * )
1405
	 * @return array
1406
	 */
1407
	public static function get_updates() {
1408
		$update_data = wp_get_update_data();
1409
1410
		// Stores the individual update counts as well as the total count.
1411
		if ( isset( $update_data['counts'] ) ) {
1412
			$updates = $update_data['counts'];
1413
		}
1414
1415
		// If we need to update WordPress core, let's find the latest version number.
1416 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1417
			$cur = get_preferred_from_update_core();
1418
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1419
				$updates['wp_update_version'] = $cur->current;
1420
			}
1421
		}
1422
		return isset( $updates ) ? $updates : array();
1423
	}
1424
1425
	public static function get_update_details() {
1426
		$update_details = array(
1427
			'update_core' => get_site_transient( 'update_core' ),
1428
			'update_plugins' => get_site_transient( 'update_plugins' ),
1429
			'update_themes' => get_site_transient( 'update_themes' ),
1430
		);
1431
		return $update_details;
1432
	}
1433
1434
	public static function refresh_update_data() {
1435
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1436
1437
	}
1438
1439
	public static function refresh_theme_data() {
1440
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1441
	}
1442
1443
	/**
1444
	 * Is Jetpack active?
1445
	 */
1446
	public static function is_active() {
1447
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1448
	}
1449
1450
	/**
1451
	 * Make an API call to WordPress.com for plan status
1452
	 *
1453
	 * @uses Jetpack_Options::get_option()
1454
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1455
	 * @uses update_option()
1456
	 *
1457
	 * @access public
1458
	 * @static
1459
	 *
1460
	 * @return bool True if plan is updated, false if no update
1461
	 */
1462
	public static function refresh_active_plan_from_wpcom() {
1463
		// Make the API request
1464
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1465
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1466
1467
		// Bail if there was an error or malformed response
1468
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1469
			return false;
1470
		}
1471
1472
		// Decode the results
1473
		$results = json_decode( $response['body'], true );
1474
1475
		// Bail if there were no results or plan details returned
1476
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1477
			return false;
1478
		}
1479
1480
		// Store the option and return true if updated
1481
		return update_option( 'jetpack_active_plan', $results['plan'] );
1482
	}
1483
1484
	/**
1485
	 * Get the plan that this Jetpack site is currently using
1486
	 *
1487
	 * @uses get_option()
1488
	 *
1489
	 * @access public
1490
	 * @static
1491
	 *
1492
	 * @return array Active Jetpack plan details
1493
	 */
1494
	public static function get_active_plan() {
1495
		global $active_plan_cache;
1496
1497
		// this can be expensive to compute so we cache for the duration of a request
1498
		if ( is_array( $active_plan_cache ) && ! empty( $active_plan_cache ) ) {
1499
			return $active_plan_cache;
1500
		}
1501
1502
		$plan = get_option( 'jetpack_active_plan', array() );
1503
1504
		// Set the default options
1505
		$plan = wp_parse_args( $plan, array(
1506
			'product_slug' => 'jetpack_free',
1507
			'class'        => 'free',
1508
			'features'     => array(
1509
				'active' => array()
1510
			),
1511
		) );
1512
1513
		$supports = array();
1514
1515
		// Define what paid modules are supported by personal plans
1516
		$personal_plans = array(
1517
			'jetpack_personal',
1518
			'jetpack_personal_monthly',
1519
			'personal-bundle',
1520
			'personal-bundle-2y',
1521
		);
1522
1523
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1524
			// special support value, not a module but a separate plugin
1525
			$supports[] = 'akismet';
1526
			$plan['class'] = 'personal';
1527
		}
1528
1529
		// Define what paid modules are supported by premium plans
1530
		$premium_plans = array(
1531
			'jetpack_premium',
1532
			'jetpack_premium_monthly',
1533
			'value_bundle',
1534
			'value_bundle-2y',
1535
		);
1536
1537 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1538
			$supports[] = 'akismet';
1539
			$supports[] = 'simple-payments';
1540
			$supports[] = 'vaultpress';
1541
			$plan['class'] = 'premium';
1542
		}
1543
1544
		// Define what paid modules are supported by professional plans
1545
		$business_plans = array(
1546
			'jetpack_business',
1547
			'jetpack_business_monthly',
1548
			'business-bundle',
1549
			'business-bundle-2y',
1550
			'vip',
1551
		);
1552
1553 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1554
			$supports[] = 'akismet';
1555
			$supports[] = 'simple-payments';
1556
			$supports[] = 'vaultpress';
1557
			$plan['class'] = 'business';
1558
		}
1559
1560
		// get available features
1561
		foreach ( self::get_available_modules() as $module_slug ) {
1562
			$module = self::get_module( $module_slug );
1563
			if ( ! isset( $module ) || ! is_array( $module ) ) {
1564
				continue;
1565
			}
1566
			if ( in_array( 'free', $module['plan_classes'] ) || in_array( $plan['class'], $module['plan_classes'] ) ) {
1567
				$supports[] = $module_slug;
1568
			}
1569
		}
1570
1571
		$plan['supports'] = $supports;
1572
1573
		$active_plan_cache = $plan;
1574
1575
		return $plan;
1576
	}
1577
1578
	/**
1579
	 * Determine whether the active plan supports a particular feature
1580
	 *
1581
	 * @uses Jetpack::get_active_plan()
1582
	 *
1583
	 * @access public
1584
	 * @static
1585
	 *
1586
	 * @return bool True if plan supports feature, false if not
1587
	 */
1588
	public static function active_plan_supports( $feature ) {
1589
		$plan = Jetpack::get_active_plan();
1590
1591
		// Manually mapping WordPress.com features to Jetpack module slugs
1592
		foreach ( $plan['features']['active'] as $wpcom_feature ) {
1593
			switch ( $wpcom_feature ) {
1594
				case 'wordads-jetpack';
1595
1596
				// WordAds are supported for this site
1597
				if ( 'wordads' === $feature ) {
1598
					return true;
1599
				}
1600
				break;
1601
			}
1602
		}
1603
1604
		if (
1605
			in_array( $feature, $plan['supports'] )
1606
			|| in_array( $feature, $plan['features']['active'] )
1607
		) {
1608
			return true;
1609
		}
1610
1611
		return false;
1612
	}
1613
1614
	/**
1615
	 * Is Jetpack in development (offline) mode?
1616
	 */
1617
	public static function is_development_mode() {
1618
		$development_mode = false;
1619
1620
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1621
			$development_mode = JETPACK_DEV_DEBUG;
1622
		} elseif ( $site_url = site_url() ) {
1623
			$development_mode = false === strpos( $site_url, '.' );
1624
		}
1625
1626
		/**
1627
		 * Filters Jetpack's development mode.
1628
		 *
1629
		 * @see https://jetpack.com/support/development-mode/
1630
		 *
1631
		 * @since 2.2.1
1632
		 *
1633
		 * @param bool $development_mode Is Jetpack's development mode active.
1634
		 */
1635
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1636
		return $development_mode;
1637
	}
1638
1639
	/**
1640
	 * Whether the site is currently onboarding or not.
1641
	 * A site is considered as being onboarded if it currently has an onboarding token.
1642
	 *
1643
	 * @since 5.8
1644
	 *
1645
	 * @access public
1646
	 * @static
1647
	 *
1648
	 * @return bool True if the site is currently onboarding, false otherwise
1649
	 */
1650
	public static function is_onboarding() {
1651
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1652
	}
1653
1654
	/**
1655
	* Get Jetpack development mode notice text and notice class.
1656
	*
1657
	* Mirrors the checks made in Jetpack::is_development_mode
1658
	*
1659
	*/
1660
	public static function show_development_mode_notice() {
1661
		if ( Jetpack::is_development_mode() ) {
1662
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1663
				$notice = sprintf(
1664
					/* translators: %s is a URL */
1665
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1666
					'https://jetpack.com/support/development-mode/'
1667
				);
1668
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1669
				$notice = sprintf(
1670
					/* translators: %s is a URL */
1671
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1672
					'https://jetpack.com/support/development-mode/'
1673
				);
1674
			} else {
1675
				$notice = sprintf(
1676
					/* translators: %s is a URL */
1677
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1678
					'https://jetpack.com/support/development-mode/'
1679
				);
1680
			}
1681
1682
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1683
		}
1684
1685
		// Throw up a notice if using a development version and as for feedback.
1686
		if ( Jetpack::is_development_version() ) {
1687
			/* translators: %s is a URL */
1688
			$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/' );
1689
1690
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1691
		}
1692
		// Throw up a notice if using staging mode
1693
		if ( Jetpack::is_staging_site() ) {
1694
			/* translators: %s is a URL */
1695
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1696
1697
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1698
		}
1699
	}
1700
1701
	/**
1702
	 * Whether Jetpack's version maps to a public release, or a development version.
1703
	 */
1704
	public static function is_development_version() {
1705
		/**
1706
		 * Allows filtering whether this is a development version of Jetpack.
1707
		 *
1708
		 * This filter is especially useful for tests.
1709
		 *
1710
		 * @since 4.3.0
1711
		 *
1712
		 * @param bool $development_version Is this a develoment version of Jetpack?
1713
		 */
1714
		return (bool) apply_filters(
1715
			'jetpack_development_version',
1716
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1717
		);
1718
	}
1719
1720
	/**
1721
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1722
	 */
1723
	public static function is_user_connected( $user_id = false ) {
1724
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1725
		if ( ! $user_id ) {
1726
			return false;
1727
		}
1728
1729
		return (bool) Jetpack_Data::get_access_token( $user_id );
1730
	}
1731
1732
	/**
1733
	 * Get the wpcom user data of the current|specified connected user.
1734
	 */
1735
	public static function get_connected_user_data( $user_id = null ) {
1736
		if ( ! $user_id ) {
1737
			$user_id = get_current_user_id();
1738
		}
1739
1740
		$transient_key = "jetpack_connected_user_data_$user_id";
1741
1742
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1743
			return $cached_user_data;
1744
		}
1745
1746
		Jetpack::load_xml_rpc_client();
1747
		$xml = new Jetpack_IXR_Client( array(
1748
			'user_id' => $user_id,
1749
		) );
1750
		$xml->query( 'wpcom.getUser' );
1751
		if ( ! $xml->isError() ) {
1752
			$user_data = $xml->getResponse();
1753
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1754
			return $user_data;
1755
		}
1756
1757
		return false;
1758
	}
1759
1760
	/**
1761
	 * Get the wpcom email of the current|specified connected user.
1762
	 */
1763 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1764
		if ( ! $user_id ) {
1765
			$user_id = get_current_user_id();
1766
		}
1767
		Jetpack::load_xml_rpc_client();
1768
		$xml = new Jetpack_IXR_Client( array(
1769
			'user_id' => $user_id,
1770
		) );
1771
		$xml->query( 'wpcom.getUserEmail' );
1772
		if ( ! $xml->isError() ) {
1773
			return $xml->getResponse();
1774
		}
1775
		return false;
1776
	}
1777
1778
	/**
1779
	 * Get the wpcom email of the master user.
1780
	 */
1781
	public static function get_master_user_email() {
1782
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1783
		if ( $master_user_id ) {
1784
			return self::get_connected_user_email( $master_user_id );
1785
		}
1786
		return '';
1787
	}
1788
1789
	function current_user_is_connection_owner() {
1790
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1791
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1792
	}
1793
1794
	/**
1795
	 * Gets current user IP address.
1796
	 *
1797
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1798
	 *
1799
	 * @return string                  Current user IP address.
1800
	 */
1801
	public static function current_user_ip( $check_all_headers = false ) {
1802
		if ( $check_all_headers ) {
1803
			foreach ( array(
1804
				'HTTP_CF_CONNECTING_IP',
1805
				'HTTP_CLIENT_IP',
1806
				'HTTP_X_FORWARDED_FOR',
1807
				'HTTP_X_FORWARDED',
1808
				'HTTP_X_CLUSTER_CLIENT_IP',
1809
				'HTTP_FORWARDED_FOR',
1810
				'HTTP_FORWARDED',
1811
				'HTTP_VIA',
1812
			) as $key ) {
1813
				if ( ! empty( $_SERVER[ $key ] ) ) {
1814
					return $_SERVER[ $key ];
1815
				}
1816
			}
1817
		}
1818
1819
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1820
	}
1821
1822
	/**
1823
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1824
	 */
1825
	function extra_oembed_providers() {
1826
		// Cloudup: https://dev.cloudup.com/#oembed
1827
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1828
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1829
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1830
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1831
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1832
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1833
	}
1834
1835
	/**
1836
	 * Synchronize connected user role changes
1837
	 */
1838
	function user_role_change( $user_id ) {
1839
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1840
		Jetpack_Sync_Users::user_role_change( $user_id );
1841
	}
1842
1843
	/**
1844
	 * Loads the currently active modules.
1845
	 */
1846
	public static function load_modules() {
1847
		if (
1848
			! self::is_active()
1849
			&& ! self::is_development_mode()
1850
			&& ! self::is_onboarding()
1851
			&& (
1852
				! is_multisite()
1853
				|| ! get_site_option( 'jetpack_protect_active' )
1854
			)
1855
		) {
1856
			return;
1857
		}
1858
1859
		$version = Jetpack_Options::get_option( 'version' );
1860 View Code Duplication
		if ( ! $version ) {
1861
			$version = $old_version = JETPACK__VERSION . ':' . time();
1862
			/** This action is documented in class.jetpack.php */
1863
			do_action( 'updating_jetpack_version', $version, false );
1864
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1865
		}
1866
		list( $version ) = explode( ':', $version );
1867
1868
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1869
1870
		$modules_data = array();
1871
1872
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1873
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1874
			$updated_modules = array();
1875
			foreach ( $modules as $module ) {
1876
				$modules_data[ $module ] = Jetpack::get_module( $module );
1877
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1878
					continue;
1879
				}
1880
1881
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1882
					continue;
1883
				}
1884
1885
				$updated_modules[] = $module;
1886
			}
1887
1888
			$modules = array_diff( $modules, $updated_modules );
1889
		}
1890
1891
		$is_development_mode = Jetpack::is_development_mode();
1892
1893
		foreach ( $modules as $index => $module ) {
1894
			// If we're in dev mode, disable modules requiring a connection
1895
			if ( $is_development_mode ) {
1896
				// Prime the pump if we need to
1897
				if ( empty( $modules_data[ $module ] ) ) {
1898
					$modules_data[ $module ] = Jetpack::get_module( $module );
1899
				}
1900
				// If the module requires a connection, but we're in local mode, don't include it.
1901
				if ( $modules_data[ $module ]['requires_connection'] ) {
1902
					continue;
1903
				}
1904
			}
1905
1906
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1907
				continue;
1908
			}
1909
1910
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1911
				unset( $modules[ $index ] );
1912
				self::update_active_modules( array_values( $modules ) );
1913
				continue;
1914
			}
1915
1916
			/**
1917
			 * Fires when a specific module is loaded.
1918
			 * The dynamic part of the hook, $module, is the module slug.
1919
			 *
1920
			 * @since 1.1.0
1921
			 */
1922
			do_action( 'jetpack_module_loaded_' . $module );
1923
		}
1924
1925
		/**
1926
		 * Fires when all the modules are loaded.
1927
		 *
1928
		 * @since 1.1.0
1929
		 */
1930
		do_action( 'jetpack_modules_loaded' );
1931
1932
		// 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.
1933
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1934
	}
1935
1936
	/**
1937
	 * Check if Jetpack's REST API compat file should be included
1938
	 * @action plugins_loaded
1939
	 * @return null
1940
	 */
1941
	public function check_rest_api_compat() {
1942
		/**
1943
		 * Filters the list of REST API compat files to be included.
1944
		 *
1945
		 * @since 2.2.5
1946
		 *
1947
		 * @param array $args Array of REST API compat files to include.
1948
		 */
1949
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1950
1951
		if ( function_exists( 'bbpress' ) )
1952
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1953
1954
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1955
			require_once $_jetpack_rest_api_compat_include;
1956
	}
1957
1958
	/**
1959
	 * Gets all plugins currently active in values, regardless of whether they're
1960
	 * traditionally activated or network activated.
1961
	 *
1962
	 * @todo Store the result in core's object cache maybe?
1963
	 */
1964
	public static function get_active_plugins() {
1965
		$active_plugins = (array) get_option( 'active_plugins', array() );
1966
1967
		if ( is_multisite() ) {
1968
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1969
			// whereas active_plugins stores them in the values.
1970
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1971
			if ( $network_plugins ) {
1972
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1973
			}
1974
		}
1975
1976
		sort( $active_plugins );
1977
1978
		return array_unique( $active_plugins );
1979
	}
1980
1981
	/**
1982
	 * Gets and parses additional plugin data to send with the heartbeat data
1983
	 *
1984
	 * @since 3.8.1
1985
	 *
1986
	 * @return array Array of plugin data
1987
	 */
1988
	public static function get_parsed_plugin_data() {
1989
		if ( ! function_exists( 'get_plugins' ) ) {
1990
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1991
		}
1992
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1993
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1994
		$active_plugins = Jetpack::get_active_plugins();
1995
1996
		$plugins = array();
1997
		foreach ( $all_plugins as $path => $plugin_data ) {
1998
			$plugins[ $path ] = array(
1999
					'is_active' => in_array( $path, $active_plugins ),
2000
					'file'      => $path,
2001
					'name'      => $plugin_data['Name'],
2002
					'version'   => $plugin_data['Version'],
2003
					'author'    => $plugin_data['Author'],
2004
			);
2005
		}
2006
2007
		return $plugins;
2008
	}
2009
2010
	/**
2011
	 * Gets and parses theme data to send with the heartbeat data
2012
	 *
2013
	 * @since 3.8.1
2014
	 *
2015
	 * @return array Array of theme data
2016
	 */
2017
	public static function get_parsed_theme_data() {
2018
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2019
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2020
2021
		$themes = array();
2022
		foreach ( $all_themes as $slug => $theme_data ) {
2023
			$theme_headers = array();
2024
			foreach ( $header_keys as $header_key ) {
2025
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2026
			}
2027
2028
			$themes[ $slug ] = array(
2029
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2030
					'slug' => $slug,
2031
					'theme_root' => $theme_data->get_theme_root_uri(),
2032
					'parent' => $theme_data->parent(),
2033
					'headers' => $theme_headers
2034
			);
2035
		}
2036
2037
		return $themes;
2038
	}
2039
2040
	/**
2041
	 * Checks whether a specific plugin is active.
2042
	 *
2043
	 * We don't want to store these in a static variable, in case
2044
	 * there are switch_to_blog() calls involved.
2045
	 */
2046
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2047
		return in_array( $plugin, self::get_active_plugins() );
2048
	}
2049
2050
	/**
2051
	 * Check if Jetpack's Open Graph tags should be used.
2052
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2053
	 *
2054
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2055
	 * @action plugins_loaded
2056
	 * @return null
2057
	 */
2058
	public function check_open_graph() {
2059
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2060
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2061
		}
2062
2063
		$active_plugins = self::get_active_plugins();
2064
2065
		if ( ! empty( $active_plugins ) ) {
2066
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2067
				if ( in_array( $plugin, $active_plugins ) ) {
2068
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2069
					break;
2070
				}
2071
			}
2072
		}
2073
2074
		/**
2075
		 * Allow the addition of Open Graph Meta Tags to all pages.
2076
		 *
2077
		 * @since 2.0.3
2078
		 *
2079
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2080
		 */
2081
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2082
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2083
		}
2084
	}
2085
2086
	/**
2087
	 * Check if Jetpack's Twitter tags should be used.
2088
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2089
	 *
2090
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2091
	 * @action plugins_loaded
2092
	 * @return null
2093
	 */
2094
	public function check_twitter_tags() {
2095
2096
		$active_plugins = self::get_active_plugins();
2097
2098
		if ( ! empty( $active_plugins ) ) {
2099
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2100
				if ( in_array( $plugin, $active_plugins ) ) {
2101
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2102
					break;
2103
				}
2104
			}
2105
		}
2106
2107
		/**
2108
		 * Allow Twitter Card Meta tags to be disabled.
2109
		 *
2110
		 * @since 2.6.0
2111
		 *
2112
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2113
		 */
2114
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2115
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2116
		}
2117
	}
2118
2119
	/**
2120
	 * Allows plugins to submit security reports.
2121
 	 *
2122
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2123
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2124
	 * @param array   $args         See definitions above
2125
	 */
2126
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2127
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2128
	}
2129
2130
/* Jetpack Options API */
2131
2132
	public static function get_option_names( $type = 'compact' ) {
2133
		return Jetpack_Options::get_option_names( $type );
2134
	}
2135
2136
	/**
2137
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2138
 	 *
2139
	 * @param string $name    Option name
2140
	 * @param mixed  $default (optional)
2141
	 */
2142
	public static function get_option( $name, $default = false ) {
2143
		return Jetpack_Options::get_option( $name, $default );
2144
	}
2145
2146
	/**
2147
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2148
 	 *
2149
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2150
	 * @param string $name  Option name
2151
	 * @param mixed  $value Option value
2152
	 */
2153
	public static function update_option( $name, $value ) {
2154
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2155
		return Jetpack_Options::update_option( $name, $value );
2156
	}
2157
2158
	/**
2159
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2160
 	 *
2161
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2162
	 * @param array $array array( option name => option value, ... )
2163
	 */
2164
	public static function update_options( $array ) {
2165
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2166
		return Jetpack_Options::update_options( $array );
2167
	}
2168
2169
	/**
2170
	 * Deletes the given option.  May be passed multiple option names as an array.
2171
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2172
	 *
2173
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2174
	 * @param string|array $names
2175
	 */
2176
	public static function delete_option( $names ) {
2177
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2178
		return Jetpack_Options::delete_option( $names );
2179
	}
2180
2181
	/**
2182
	 * Enters a user token into the user_tokens option
2183
	 *
2184
	 * @param int $user_id
2185
	 * @param string $token
2186
	 * return bool
2187
	 */
2188
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2189
		// not designed for concurrent updates
2190
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2191
		if ( ! is_array( $user_tokens ) )
2192
			$user_tokens = array();
2193
		$user_tokens[$user_id] = $token;
2194
		if ( $is_master_user ) {
2195
			$master_user = $user_id;
2196
			$options     = compact( 'user_tokens', 'master_user' );
2197
		} else {
2198
			$options = compact( 'user_tokens' );
2199
		}
2200
		return Jetpack_Options::update_options( $options );
2201
	}
2202
2203
	/**
2204
	 * Returns an array of all PHP files in the specified absolute path.
2205
	 * Equivalent to glob( "$absolute_path/*.php" ).
2206
	 *
2207
	 * @param string $absolute_path The absolute path of the directory to search.
2208
	 * @return array Array of absolute paths to the PHP files.
2209
	 */
2210
	public static function glob_php( $absolute_path ) {
2211
		if ( function_exists( 'glob' ) ) {
2212
			return glob( "$absolute_path/*.php" );
2213
		}
2214
2215
		$absolute_path = untrailingslashit( $absolute_path );
2216
		$files = array();
2217
		if ( ! $dir = @opendir( $absolute_path ) ) {
2218
			return $files;
2219
		}
2220
2221
		while ( false !== $file = readdir( $dir ) ) {
2222
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2223
				continue;
2224
			}
2225
2226
			$file = "$absolute_path/$file";
2227
2228
			if ( ! is_file( $file ) ) {
2229
				continue;
2230
			}
2231
2232
			$files[] = $file;
2233
		}
2234
2235
		closedir( $dir );
2236
2237
		return $files;
2238
	}
2239
2240
	public static function activate_new_modules( $redirect = false ) {
2241
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2242
			return;
2243
		}
2244
2245
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2246 View Code Duplication
		if ( ! $jetpack_old_version ) {
2247
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2248
			/** This action is documented in class.jetpack.php */
2249
			do_action( 'updating_jetpack_version', $version, false );
2250
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2251
		}
2252
2253
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2254
2255
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2256
			return;
2257
		}
2258
2259
		$active_modules     = Jetpack::get_active_modules();
2260
		$reactivate_modules = array();
2261
		foreach ( $active_modules as $active_module ) {
2262
			$module = Jetpack::get_module( $active_module );
2263
			if ( ! isset( $module['changed'] ) ) {
2264
				continue;
2265
			}
2266
2267
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2268
				continue;
2269
			}
2270
2271
			$reactivate_modules[] = $active_module;
2272
			Jetpack::deactivate_module( $active_module );
2273
		}
2274
2275
		$new_version = JETPACK__VERSION . ':' . time();
2276
		/** This action is documented in class.jetpack.php */
2277
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2278
		Jetpack_Options::update_options(
2279
			array(
2280
				'version'     => $new_version,
2281
				'old_version' => $jetpack_old_version,
2282
			)
2283
		);
2284
2285
		Jetpack::state( 'message', 'modules_activated' );
2286
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2287
2288
		if ( $redirect ) {
2289
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2290
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2291
				$page = $_GET['page'];
2292
			}
2293
2294
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2295
			exit;
2296
		}
2297
	}
2298
2299
	/**
2300
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2301
	 * Make sure to tuck away module "library" files in a sub-directory.
2302
	 */
2303
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2304
		static $modules = null;
2305
2306
		if ( ! isset( $modules ) ) {
2307
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2308
			// Use the cache if we're on the front-end and it's available...
2309
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2310
				$modules = $available_modules_option[ JETPACK__VERSION ];
2311
			} else {
2312
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2313
2314
				$modules = array();
2315
2316
				foreach ( $files as $file ) {
2317
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2318
						continue;
2319
					}
2320
2321
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2322
				}
2323
2324
				Jetpack_Options::update_option( 'available_modules', array(
2325
					JETPACK__VERSION => $modules,
2326
				) );
2327
			}
2328
		}
2329
2330
		/**
2331
		 * Filters the array of modules available to be activated.
2332
		 *
2333
		 * @since 2.4.0
2334
		 *
2335
		 * @param array $modules Array of available modules.
2336
		 * @param string $min_version Minimum version number required to use modules.
2337
		 * @param string $max_version Maximum version number required to use modules.
2338
		 */
2339
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2340
2341
		if ( ! $min_version && ! $max_version ) {
2342
			return array_keys( $mods );
2343
		}
2344
2345
		$r = array();
2346
		foreach ( $mods as $slug => $introduced ) {
2347
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2348
				continue;
2349
			}
2350
2351
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2352
				continue;
2353
			}
2354
2355
			$r[] = $slug;
2356
		}
2357
2358
		return $r;
2359
	}
2360
2361
	/**
2362
	 * Default modules loaded on activation.
2363
	 */
2364
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2365
		$return = array();
2366
2367
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2368
			$module_data = Jetpack::get_module( $module );
2369
2370
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2371
				case 'yes' :
2372
					$return[] = $module;
2373
					break;
2374
				case 'public' :
2375
					if ( Jetpack_Options::get_option( 'public' ) ) {
2376
						$return[] = $module;
2377
					}
2378
					break;
2379
				case 'no' :
2380
				default :
2381
					break;
2382
			}
2383
		}
2384
		/**
2385
		 * Filters the array of default modules.
2386
		 *
2387
		 * @since 2.5.0
2388
		 *
2389
		 * @param array $return Array of default modules.
2390
		 * @param string $min_version Minimum version number required to use modules.
2391
		 * @param string $max_version Maximum version number required to use modules.
2392
		 */
2393
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2394
	}
2395
2396
	/**
2397
	 * Checks activated modules during auto-activation to determine
2398
	 * if any of those modules are being deprecated.  If so, close
2399
	 * them out, and add any replacement modules.
2400
	 *
2401
	 * Runs at priority 99 by default.
2402
	 *
2403
	 * This is run late, so that it can still activate a module if
2404
	 * the new module is a replacement for another that the user
2405
	 * currently has active, even if something at the normal priority
2406
	 * would kibosh everything.
2407
	 *
2408
	 * @since 2.6
2409
	 * @uses jetpack_get_default_modules filter
2410
	 * @param array $modules
2411
	 * @return array
2412
	 */
2413
	function handle_deprecated_modules( $modules ) {
2414
		$deprecated_modules = array(
2415
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2416
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2417
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2418
		);
2419
2420
		// Don't activate SSO if they never completed activating WPCC.
2421
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2422
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2423
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2424
				$deprecated_modules['wpcc'] = null;
2425
			}
2426
		}
2427
2428
		foreach ( $deprecated_modules as $module => $replacement ) {
2429
			if ( Jetpack::is_module_active( $module ) ) {
2430
				self::deactivate_module( $module );
2431
				if ( $replacement ) {
2432
					$modules[] = $replacement;
2433
				}
2434
			}
2435
		}
2436
2437
		return array_unique( $modules );
2438
	}
2439
2440
	/**
2441
	 * Checks activated plugins during auto-activation to determine
2442
	 * if any of those plugins are in the list with a corresponding module
2443
	 * that is not compatible with the plugin. The module will not be allowed
2444
	 * to auto-activate.
2445
	 *
2446
	 * @since 2.6
2447
	 * @uses jetpack_get_default_modules filter
2448
	 * @param array $modules
2449
	 * @return array
2450
	 */
2451
	function filter_default_modules( $modules ) {
2452
2453
		$active_plugins = self::get_active_plugins();
2454
2455
		if ( ! empty( $active_plugins ) ) {
2456
2457
			// For each module we'd like to auto-activate...
2458
			foreach ( $modules as $key => $module ) {
2459
				// If there are potential conflicts for it...
2460
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2461
					// For each potential conflict...
2462
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2463
						// If that conflicting plugin is active...
2464
						if ( in_array( $plugin, $active_plugins ) ) {
2465
							// Remove that item from being auto-activated.
2466
							unset( $modules[ $key ] );
2467
						}
2468
					}
2469
				}
2470
			}
2471
		}
2472
2473
		return $modules;
2474
	}
2475
2476
	/**
2477
	 * Extract a module's slug from its full path.
2478
	 */
2479
	public static function get_module_slug( $file ) {
2480
		return str_replace( '.php', '', basename( $file ) );
2481
	}
2482
2483
	/**
2484
	 * Generate a module's path from its slug.
2485
	 */
2486
	public static function get_module_path( $slug ) {
2487
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2488
	}
2489
2490
	/**
2491
	 * Load module data from module file. Headers differ from WordPress
2492
	 * plugin headers to avoid them being identified as standalone
2493
	 * plugins on the WordPress plugins page.
2494
	 */
2495
	public static function get_module( $module ) {
2496
		$headers = array(
2497
			'name'                      => 'Module Name',
2498
			'description'               => 'Module Description',
2499
			'jumpstart_desc'            => 'Jumpstart Description',
2500
			'sort'                      => 'Sort Order',
2501
			'recommendation_order'      => 'Recommendation Order',
2502
			'introduced'                => 'First Introduced',
2503
			'changed'                   => 'Major Changes In',
2504
			'deactivate'                => 'Deactivate',
2505
			'free'                      => 'Free',
2506
			'requires_connection'       => 'Requires Connection',
2507
			'auto_activate'             => 'Auto Activate',
2508
			'module_tags'               => 'Module Tags',
2509
			'feature'                   => 'Feature',
2510
			'additional_search_queries' => 'Additional Search Queries',
2511
			'plan_classes'              => 'Plans',
2512
		);
2513
2514
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2515
2516
		$mod = Jetpack::get_file_data( $file, $headers );
2517
		if ( empty( $mod['name'] ) ) {
2518
			return false;
2519
		}
2520
2521
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2522
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2523
		$mod['deactivate']              = empty( $mod['deactivate'] );
2524
		$mod['free']                    = empty( $mod['free'] );
2525
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2526
2527
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2528
			$mod['auto_activate'] = 'No';
2529
		} else {
2530
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2531
		}
2532
2533
		if ( $mod['module_tags'] ) {
2534
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2535
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2536
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2537
		} else {
2538
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2539
		}
2540
2541 View Code Duplication
		if ( $mod['plan_classes'] ) {
2542
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2543
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2544
		} else {
2545
			$mod['plan_classes'] = array( 'free' );
2546
		}
2547
2548 View Code Duplication
		if ( $mod['feature'] ) {
2549
			$mod['feature'] = explode( ',', $mod['feature'] );
2550
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2551
		} else {
2552
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2553
		}
2554
2555
		/**
2556
		 * Filters the feature array on a module.
2557
		 *
2558
		 * This filter allows you to control where each module is filtered: Recommended,
2559
		 * Jumpstart, and the default "Other" listing.
2560
		 *
2561
		 * @since 3.5.0
2562
		 *
2563
		 * @param array   $mod['feature'] The areas to feature this module:
2564
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2565
		 *     'Recommended' shows on the main Jetpack admin screen.
2566
		 *     'Other' should be the default if no other value is in the array.
2567
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2568
		 * @param array   $mod All the currently assembled module data.
2569
		 */
2570
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2571
2572
		/**
2573
		 * Filter the returned data about a module.
2574
		 *
2575
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2576
		 * so please be careful.
2577
		 *
2578
		 * @since 3.6.0
2579
		 *
2580
		 * @param array   $mod    The details of the requested module.
2581
		 * @param string  $module The slug of the module, e.g. sharedaddy
2582
		 * @param string  $file   The path to the module source file.
2583
		 */
2584
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2585
	}
2586
2587
	/**
2588
	 * Like core's get_file_data implementation, but caches the result.
2589
	 */
2590
	public static function get_file_data( $file, $headers ) {
2591
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2592
		$file_name = basename( $file );
2593
2594
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2595
2596
		$file_data_option = get_transient( $cache_key );
2597
2598
		if ( false === $file_data_option ) {
2599
			$file_data_option = array();
2600
		}
2601
2602
		$key           = md5( $file_name . serialize( $headers ) );
2603
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2604
2605
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2606
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2607
			return $file_data_option[ $key ];
2608
		}
2609
2610
		$data = get_file_data( $file, $headers );
2611
2612
		$file_data_option[ $key ] = $data;
2613
2614
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2615
2616
		return $data;
2617
	}
2618
2619
2620
	/**
2621
	 * Return translated module tag.
2622
	 *
2623
	 * @param string $tag Tag as it appears in each module heading.
2624
	 *
2625
	 * @return mixed
2626
	 */
2627
	public static function translate_module_tag( $tag ) {
2628
		return jetpack_get_module_i18n_tag( $tag );
2629
	}
2630
2631
	/**
2632
	 * Get i18n strings as a JSON-encoded string
2633
	 *
2634
	 * @return string The locale as JSON
2635
	 */
2636
	public static function get_i18n_data_json() {
2637
		$i18n_json = JETPACK__PLUGIN_DIR . 'languages/json/jetpack-' . jetpack_get_user_locale() . '.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 json_encode( array(
2648
			'' => array(
2649
				'domain' => 'jetpack',
2650
				'lang'   => is_admin() ? get_user_locale() : get_locale(),
2651
			),
2652
		) );
2653
	}
2654
2655
	/**
2656
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2657
	 *
2658
	 * @since 3.9.2
2659
	 *
2660
	 * @param array $modules
2661
	 *
2662
	 * @return string|void
2663
	 */
2664
	public static function get_translated_modules( $modules ) {
2665
		foreach ( $modules as $index => $module ) {
2666
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2667
			if ( isset( $module['name'] ) ) {
2668
				$modules[ $index ]['name'] = $i18n_module['name'];
2669
			}
2670
			if ( isset( $module['description'] ) ) {
2671
				$modules[ $index ]['description'] = $i18n_module['description'];
2672
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2673
			}
2674
		}
2675
		return $modules;
2676
	}
2677
2678
	/**
2679
	 * Get a list of activated modules as an array of module slugs.
2680
	 */
2681
	public static function get_active_modules() {
2682
		$active = Jetpack_Options::get_option( 'active_modules' );
2683
2684
		if ( ! is_array( $active ) ) {
2685
			$active = array();
2686
		}
2687
2688
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2689
			$active[] = 'vaultpress';
2690
		} else {
2691
			$active = array_diff( $active, array( 'vaultpress' ) );
2692
		}
2693
2694
		//If protect is active on the main site of a multisite, it should be active on all sites.
2695
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2696
			$active[] = 'protect';
2697
		}
2698
2699
		/**
2700
		 * Allow filtering of the active modules.
2701
		 *
2702
		 * Gives theme and plugin developers the power to alter the modules that
2703
		 * are activated on the fly.
2704
		 *
2705
		 * @since 5.8.0
2706
		 *
2707
		 * @param array $active Array of active module slugs.
2708
		 */
2709
		$active = apply_filters( 'jetpack_active_modules', $active );
2710
2711
		return array_unique( $active );
2712
	}
2713
2714
	/**
2715
	 * Check whether or not a Jetpack module is active.
2716
	 *
2717
	 * @param string $module The slug of a Jetpack module.
2718
	 * @return bool
2719
	 *
2720
	 * @static
2721
	 */
2722
	public static function is_module_active( $module ) {
2723
		return in_array( $module, self::get_active_modules() );
2724
	}
2725
2726
	public static function is_module( $module ) {
2727
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2728
	}
2729
2730
	/**
2731
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2732
	 *
2733
	 * @param bool $catch True to start catching, False to stop.
2734
	 *
2735
	 * @static
2736
	 */
2737
	public static function catch_errors( $catch ) {
2738
		static $display_errors, $error_reporting;
2739
2740
		if ( $catch ) {
2741
			$display_errors  = @ini_set( 'display_errors', 1 );
2742
			$error_reporting = @error_reporting( E_ALL );
2743
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2744
		} else {
2745
			@ini_set( 'display_errors', $display_errors );
2746
			@error_reporting( $error_reporting );
2747
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2748
		}
2749
	}
2750
2751
	/**
2752
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2753
	 */
2754
	public static function catch_errors_on_shutdown() {
2755
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2756
	}
2757
2758
	/**
2759
	 * Rewrite any string to make paths easier to read.
2760
	 *
2761
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2762
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2763
	 *
2764
	 * @param $string
2765
	 * @return mixed
2766
	 */
2767
	public static function alias_directories( $string ) {
2768
		// ABSPATH has a trailing slash.
2769
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2770
		// WP_CONTENT_DIR does not have a trailing slash.
2771
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2772
2773
		return $string;
2774
	}
2775
2776
	public static function activate_default_modules(
2777
		$min_version = false,
2778
		$max_version = false,
2779
		$other_modules = array(),
2780
		$redirect = true,
2781
		$send_state_messages = true
2782
	) {
2783
		$jetpack = Jetpack::init();
2784
2785
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2786
		$modules = array_merge( $other_modules, $modules );
2787
2788
		// Look for standalone plugins and disable if active.
2789
2790
		$to_deactivate = array();
2791
		foreach ( $modules as $module ) {
2792
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2793
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2794
			}
2795
		}
2796
2797
		$deactivated = array();
2798
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2799
			list( $probable_file, $probable_title ) = $deactivate_me;
2800
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2801
				$deactivated[] = $module;
2802
			}
2803
		}
2804
2805
		if ( $deactivated && $redirect ) {
2806
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2807
2808
			$url = add_query_arg(
2809
				array(
2810
					'action'   => 'activate_default_modules',
2811
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2812
				),
2813
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2814
			);
2815
			wp_safe_redirect( $url );
2816
			exit;
2817
		}
2818
2819
		/**
2820
		 * Fires before default modules are activated.
2821
		 *
2822
		 * @since 1.9.0
2823
		 *
2824
		 * @param string $min_version Minimum version number required to use modules.
2825
		 * @param string $max_version Maximum version number required to use modules.
2826
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2827
		 */
2828
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2829
2830
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2831
		Jetpack::restate();
2832
		Jetpack::catch_errors( true );
2833
2834
		$active = Jetpack::get_active_modules();
2835
2836
		foreach ( $modules as $module ) {
2837
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2838
				$active[] = $module;
2839
				self::update_active_modules( $active );
2840
				continue;
2841
			}
2842
2843
			if ( $send_state_messages && in_array( $module, $active ) ) {
2844
				$module_info = Jetpack::get_module( $module );
2845 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2846
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2847
					if ( $active_state = Jetpack::state( $state ) ) {
2848
						$active_state = explode( ',', $active_state );
2849
					} else {
2850
						$active_state = array();
2851
					}
2852
					$active_state[] = $module;
2853
					Jetpack::state( $state, implode( ',', $active_state ) );
2854
				}
2855
				continue;
2856
			}
2857
2858
			$file = Jetpack::get_module_path( $module );
2859
			if ( ! file_exists( $file ) ) {
2860
				continue;
2861
			}
2862
2863
			// we'll override this later if the plugin can be included without fatal error
2864
			if ( $redirect ) {
2865
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2866
			}
2867
2868
			if ( $send_state_messages ) {
2869
				Jetpack::state( 'error', 'module_activation_failed' );
2870
				Jetpack::state( 'module', $module );
2871
			}
2872
2873
			ob_start();
2874
			require_once $file;
2875
2876
			$active[] = $module;
2877
2878 View Code Duplication
			if ( $send_state_messages ) {
2879
2880
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2881
				if ( $active_state = Jetpack::state( $state ) ) {
2882
					$active_state = explode( ',', $active_state );
2883
				} else {
2884
					$active_state = array();
2885
				}
2886
				$active_state[] = $module;
2887
				Jetpack::state( $state, implode( ',', $active_state ) );
2888
			}
2889
2890
			Jetpack::update_active_modules( $active );
2891
2892
			ob_end_clean();
2893
		}
2894
2895
		if ( $send_state_messages ) {
2896
			Jetpack::state( 'error', false );
2897
			Jetpack::state( 'module', false );
2898
		}
2899
2900
		Jetpack::catch_errors( false );
2901
		/**
2902
		 * Fires when default modules are activated.
2903
		 *
2904
		 * @since 1.9.0
2905
		 *
2906
		 * @param string $min_version Minimum version number required to use modules.
2907
		 * @param string $max_version Maximum version number required to use modules.
2908
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2909
		 */
2910
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2911
	}
2912
2913
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2914
		/**
2915
		 * Fires before a module is activated.
2916
		 *
2917
		 * @since 2.6.0
2918
		 *
2919
		 * @param string $module Module slug.
2920
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2921
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2922
		 */
2923
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2924
2925
		$jetpack = Jetpack::init();
2926
2927
		if ( ! strlen( $module ) )
2928
			return false;
2929
2930
		if ( ! Jetpack::is_module( $module ) )
2931
			return false;
2932
2933
		// If it's already active, then don't do it again
2934
		$active = Jetpack::get_active_modules();
2935
		foreach ( $active as $act ) {
2936
			if ( $act == $module )
2937
				return true;
2938
		}
2939
2940
		$module_data = Jetpack::get_module( $module );
2941
2942
		if ( ! Jetpack::is_active() ) {
2943
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2944
				return false;
2945
2946
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2947
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2948
				return false;
2949
		}
2950
2951
		// Check and see if the old plugin is active
2952
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2953
			// Deactivate the old plugin
2954
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2955
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2956
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2957
				Jetpack::state( 'deactivated_plugins', $module );
2958
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2959
				exit;
2960
			}
2961
		}
2962
2963
		// Protect won't work with mis-configured IPs
2964
		if ( 'protect' === $module ) {
2965
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2966
			if ( ! jetpack_protect_get_ip() ) {
2967
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2968
				return false;
2969
			}
2970
		}
2971
2972
		if ( ! Jetpack::active_plan_supports( $module ) ) {
2973
			return false;
2974
		}
2975
2976
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2977
		Jetpack::state( 'module', $module );
2978
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2979
2980
		Jetpack::catch_errors( true );
2981
		ob_start();
2982
		require Jetpack::get_module_path( $module );
2983
		/** This action is documented in class.jetpack.php */
2984
		do_action( 'jetpack_activate_module', $module );
2985
		$active[] = $module;
2986
		Jetpack::update_active_modules( $active );
2987
2988
		Jetpack::state( 'error', false ); // the override
2989
		ob_end_clean();
2990
		Jetpack::catch_errors( false );
2991
2992
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2993 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2994
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2995
2996
			//Jump start is being dismissed send data to MC Stats
2997
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2998
2999
			$jetpack->do_stats( 'server_side' );
3000
		}
3001
3002
		if ( $redirect ) {
3003
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3004
		}
3005
		if ( $exit ) {
3006
			exit;
3007
		}
3008
		return true;
3009
	}
3010
3011
	function activate_module_actions( $module ) {
3012
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3013
	}
3014
3015
	public static function deactivate_module( $module ) {
3016
		/**
3017
		 * Fires when a module is deactivated.
3018
		 *
3019
		 * @since 1.9.0
3020
		 *
3021
		 * @param string $module Module slug.
3022
		 */
3023
		do_action( 'jetpack_pre_deactivate_module', $module );
3024
3025
		$jetpack = Jetpack::init();
3026
3027
		$active = Jetpack::get_active_modules();
3028
		$new    = array_filter( array_diff( $active, (array) $module ) );
3029
3030
		// A flag for Jump Start so it's not shown again.
3031 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3032
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3033
3034
			//Jump start is being dismissed send data to MC Stats
3035
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
3036
3037
			$jetpack->do_stats( 'server_side' );
3038
		}
3039
3040
		return self::update_active_modules( $new );
3041
	}
3042
3043
	public static function enable_module_configurable( $module ) {
3044
		$module = Jetpack::get_module_slug( $module );
3045
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3046
	}
3047
3048
	public static function module_configuration_url( $module ) {
3049
		$module = Jetpack::get_module_slug( $module );
3050
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
3051
	}
3052
3053
	public static function module_configuration_load( $module, $method ) {
3054
		$module = Jetpack::get_module_slug( $module );
3055
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
3056
	}
3057
3058
	public static function module_configuration_head( $module, $method ) {
3059
		$module = Jetpack::get_module_slug( $module );
3060
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
3061
	}
3062
3063
	public static function module_configuration_screen( $module, $method ) {
3064
		$module = Jetpack::get_module_slug( $module );
3065
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
3066
	}
3067
3068
	public static function module_configuration_activation_screen( $module, $method ) {
3069
		$module = Jetpack::get_module_slug( $module );
3070
		add_action( 'display_activate_module_setting_' . $module, $method );
3071
	}
3072
3073
/* Installation */
3074
3075
	public static function bail_on_activation( $message, $deactivate = true ) {
3076
?>
3077
<!doctype html>
3078
<html>
3079
<head>
3080
<meta charset="<?php bloginfo( 'charset' ); ?>">
3081
<style>
3082
* {
3083
	text-align: center;
3084
	margin: 0;
3085
	padding: 0;
3086
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3087
}
3088
p {
3089
	margin-top: 1em;
3090
	font-size: 18px;
3091
}
3092
</style>
3093
<body>
3094
<p><?php echo esc_html( $message ); ?></p>
3095
</body>
3096
</html>
3097
<?php
3098
		if ( $deactivate ) {
3099
			$plugins = get_option( 'active_plugins' );
3100
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3101
			$update  = false;
3102
			foreach ( $plugins as $i => $plugin ) {
3103
				if ( $plugin === $jetpack ) {
3104
					$plugins[$i] = false;
3105
					$update = true;
3106
				}
3107
			}
3108
3109
			if ( $update ) {
3110
				update_option( 'active_plugins', array_filter( $plugins ) );
3111
			}
3112
		}
3113
		exit;
3114
	}
3115
3116
	/**
3117
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3118
	 * @static
3119
	 */
3120
	public static function plugin_activation( $network_wide ) {
3121
		Jetpack_Options::update_option( 'activated', 1 );
3122
3123
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3124
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3125
		}
3126
3127
		if ( $network_wide )
3128
			Jetpack::state( 'network_nag', true );
3129
3130
		// For firing one-off events (notices) immediately after activation
3131
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3132
3133
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3134
3135
		Jetpack::plugin_initialize();
3136
	}
3137
3138
	public static function get_activation_source( $referer_url ) {
3139
3140
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3141
			return array( 'wp-cli', null );
3142
		}
3143
3144
		$referer = parse_url( $referer_url );
3145
3146
		$source_type = 'unknown';
3147
		$source_query = null;
3148
3149
		if ( ! is_array( $referer ) ) {
3150
			return array( $source_type, $source_query );
3151
		}
3152
3153
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3154
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3155
3156
		if ( isset( $referer['query'] ) ) {
3157
			parse_str( $referer['query'], $query_parts );
3158
		} else {
3159
			$query_parts = array();
3160
		}
3161
3162
		if ( $plugins_path === $referer['path'] ) {
3163
			$source_type = 'list';
3164
		} elseif ( $plugins_install_path === $referer['path'] ) {
3165
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3166
			switch( $tab ) {
3167
				case 'popular':
3168
					$source_type = 'popular';
3169
					break;
3170
				case 'recommended':
3171
					$source_type = 'recommended';
3172
					break;
3173
				case 'favorites':
3174
					$source_type = 'favorites';
3175
					break;
3176
				case 'search':
3177
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3178
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3179
					break;
3180
				default:
3181
					$source_type = 'featured';
3182
			}
3183
		}
3184
3185
		return array( $source_type, $source_query );
3186
	}
3187
3188
	/**
3189
	 * Runs before bumping version numbers up to a new version
3190
	 * @param  string $version    Version:timestamp
3191
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3192
	 * @return null              [description]
3193
	 */
3194
	public static function do_version_bump( $version, $old_version ) {
3195
3196
		if ( ! $old_version ) { // For new sites
3197
			// Setting up jetpack manage
3198
			Jetpack::activate_manage();
3199
		}
3200
	}
3201
3202
	/**
3203
	 * Sets the internal version number and activation state.
3204
	 * @static
3205
	 */
3206
	public static function plugin_initialize() {
3207
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3208
			Jetpack_Options::update_option( 'activated', 2 );
3209
		}
3210
3211 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3212
			$version = $old_version = JETPACK__VERSION . ':' . time();
3213
			/** This action is documented in class.jetpack.php */
3214
			do_action( 'updating_jetpack_version', $version, false );
3215
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3216
		}
3217
3218
		Jetpack::load_modules();
3219
3220
		Jetpack_Options::delete_option( 'do_activate' );
3221
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3222
	}
3223
3224
	/**
3225
	 * Removes all connection options
3226
	 * @static
3227
	 */
3228
	public static function plugin_deactivation( ) {
3229
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3230
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3231
			Jetpack_Network::init()->deactivate();
3232
		} else {
3233
			Jetpack::disconnect( false );
3234
			//Jetpack_Heartbeat::init()->deactivate();
3235
		}
3236
	}
3237
3238
	/**
3239
	 * Disconnects from the Jetpack servers.
3240
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3241
	 * @static
3242
	 */
3243
	public static function disconnect( $update_activated_state = true ) {
3244
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3245
		Jetpack::clean_nonces( true );
3246
3247
		// If the site is in an IDC because sync is not allowed,
3248
		// let's make sure to not disconnect the production site.
3249
		if ( ! self::validate_sync_error_idc_option() ) {
3250
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3251
			Jetpack::load_xml_rpc_client();
3252
			$xml = new Jetpack_IXR_Client();
3253
			$xml->query( 'jetpack.deregister' );
3254
		}
3255
3256
		Jetpack_Options::delete_option(
3257
			array(
3258
				'blog_token',
3259
				'user_token',
3260
				'user_tokens',
3261
				'master_user',
3262
				'time_diff',
3263
				'fallback_no_verify_ssl_certs',
3264
			)
3265
		);
3266
3267
		Jetpack_IDC::clear_all_idc_options();
3268
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3269
3270
		if ( $update_activated_state ) {
3271
			Jetpack_Options::update_option( 'activated', 4 );
3272
		}
3273
3274
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3275
			// Check then record unique disconnection if site has never been disconnected previously
3276
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3277
				$jetpack_unique_connection['disconnected'] = 1;
3278
			} else {
3279
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3280
					//track unique disconnect
3281
					$jetpack = Jetpack::init();
3282
3283
					$jetpack->stat( 'connections', 'unique-disconnect' );
3284
					$jetpack->do_stats( 'server_side' );
3285
				}
3286
				// increment number of times disconnected
3287
				$jetpack_unique_connection['disconnected'] += 1;
3288
			}
3289
3290
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3291
		}
3292
3293
		// Delete cached connected user data
3294
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3295
		delete_transient( $transient_key );
3296
3297
		// Delete all the sync related data. Since it could be taking up space.
3298
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3299
		Jetpack_Sync_Sender::get_instance()->uninstall();
3300
3301
		// Disable the Heartbeat cron
3302
		Jetpack_Heartbeat::init()->deactivate();
3303
	}
3304
3305
	/**
3306
	 * Unlinks the current user from the linked WordPress.com user
3307
	 */
3308
	public static function unlink_user( $user_id = null ) {
3309
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3310
			return false;
3311
3312
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3313
3314
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3315
			return false;
3316
3317
		if ( ! isset( $tokens[ $user_id ] ) )
3318
			return false;
3319
3320
		Jetpack::load_xml_rpc_client();
3321
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3322
		$xml->query( 'jetpack.unlink_user', $user_id );
3323
3324
		unset( $tokens[ $user_id ] );
3325
3326
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3327
3328
		/**
3329
		 * Fires after the current user has been unlinked from WordPress.com.
3330
		 *
3331
		 * @since 4.1.0
3332
		 *
3333
		 * @param int $user_id The current user's ID.
3334
		 */
3335
		do_action( 'jetpack_unlinked_user', $user_id );
3336
3337
		return true;
3338
	}
3339
3340
	/**
3341
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3342
	 */
3343
	public static function try_registration() {
3344
		// The user has agreed to the TOS at some point by now.
3345
		Jetpack_Options::update_option( 'tos_agreed', true );
3346
3347
		// Let's get some testing in beta versions and such.
3348
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3349
			// Before attempting to connect, let's make sure that the domains are viable.
3350
			$domains_to_check = array_unique( array(
3351
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3352
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3353
			) );
3354
			foreach ( $domains_to_check as $domain ) {
3355
				$result = Jetpack_Data::is_usable_domain( $domain );
3356
				if ( is_wp_error( $result ) ) {
3357
					return $result;
3358
				}
3359
			}
3360
		}
3361
3362
		$result = Jetpack::register();
3363
3364
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3365
		if ( ! $result || is_wp_error( $result ) ) {
3366
			return $result;
3367
		} else {
3368
			return true;
3369
		}
3370
	}
3371
3372
	/**
3373
	 * Tracking an internal event log. Try not to put too much chaff in here.
3374
	 *
3375
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3376
	 */
3377
	public static function log( $code, $data = null ) {
3378
		// only grab the latest 200 entries
3379
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3380
3381
		// Append our event to the log
3382
		$log_entry = array(
3383
			'time'    => time(),
3384
			'user_id' => get_current_user_id(),
3385
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3386
			'code'    => $code,
3387
		);
3388
		// Don't bother storing it unless we've got some.
3389
		if ( ! is_null( $data ) ) {
3390
			$log_entry['data'] = $data;
3391
		}
3392
		$log[] = $log_entry;
3393
3394
		// Try add_option first, to make sure it's not autoloaded.
3395
		// @todo: Add an add_option method to Jetpack_Options
3396
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3397
			Jetpack_Options::update_option( 'log', $log );
3398
		}
3399
3400
		/**
3401
		 * Fires when Jetpack logs an internal event.
3402
		 *
3403
		 * @since 3.0.0
3404
		 *
3405
		 * @param array $log_entry {
3406
		 *	Array of details about the log entry.
3407
		 *
3408
		 *	@param string time Time of the event.
3409
		 *	@param int user_id ID of the user who trigerred the event.
3410
		 *	@param int blog_id Jetpack Blog ID.
3411
		 *	@param string code Unique name for the event.
3412
		 *	@param string data Data about the event.
3413
		 * }
3414
		 */
3415
		do_action( 'jetpack_log_entry', $log_entry );
3416
	}
3417
3418
	/**
3419
	 * Get the internal event log.
3420
	 *
3421
	 * @param $event (string) - only return the specific log events
3422
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3423
	 *
3424
	 * @return array of log events || WP_Error for invalid params
3425
	 */
3426
	public static function get_log( $event = false, $num = false ) {
3427
		if ( $event && ! is_string( $event ) ) {
3428
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3429
		}
3430
3431
		if ( $num && ! is_numeric( $num ) ) {
3432
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3433
		}
3434
3435
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3436
3437
		// If nothing set - act as it did before, otherwise let's start customizing the output
3438
		if ( ! $num && ! $event ) {
3439
			return $entire_log;
3440
		} else {
3441
			$entire_log = array_reverse( $entire_log );
3442
		}
3443
3444
		$custom_log_output = array();
3445
3446
		if ( $event ) {
3447
			foreach ( $entire_log as $log_event ) {
3448
				if ( $event == $log_event[ 'code' ] ) {
3449
					$custom_log_output[] = $log_event;
3450
				}
3451
			}
3452
		} else {
3453
			$custom_log_output = $entire_log;
3454
		}
3455
3456
		if ( $num ) {
3457
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3458
		}
3459
3460
		return $custom_log_output;
3461
	}
3462
3463
	/**
3464
	 * Log modification of important settings.
3465
	 */
3466
	public static function log_settings_change( $option, $old_value, $value ) {
3467
		switch( $option ) {
3468
			case 'jetpack_sync_non_public_post_stati':
3469
				self::log( $option, $value );
3470
				break;
3471
		}
3472
	}
3473
3474
	/**
3475
	 * Return stat data for WPCOM sync
3476
	 */
3477
	public static function get_stat_data( $encode = true, $extended = true ) {
3478
		$data = Jetpack_Heartbeat::generate_stats_array();
3479
3480
		if ( $extended ) {
3481
			$additional_data = self::get_additional_stat_data();
3482
			$data = array_merge( $data, $additional_data );
3483
		}
3484
3485
		if ( $encode ) {
3486
			return json_encode( $data );
3487
		}
3488
3489
		return $data;
3490
	}
3491
3492
	/**
3493
	 * Get additional stat data to sync to WPCOM
3494
	 */
3495
	public static function get_additional_stat_data( $prefix = '' ) {
3496
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3497
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3498
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3499
		$return["{$prefix}site-count"]     = 0;
3500
3501
		if ( function_exists( 'get_blog_count' ) ) {
3502
			$return["{$prefix}site-count"] = get_blog_count();
3503
		}
3504
		return $return;
3505
	}
3506
3507
	private static function get_site_user_count() {
3508
		global $wpdb;
3509
3510
		if ( function_exists( 'wp_is_large_network' ) ) {
3511
			if ( wp_is_large_network( 'users' ) ) {
3512
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3513
			}
3514
		}
3515 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3516
			// It wasn't there, so regenerate the data and save the transient
3517
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3518
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3519
		}
3520
		return $user_count;
3521
	}
3522
3523
	/* Admin Pages */
3524
3525
	function admin_init() {
3526
		// If the plugin is not connected, display a connect message.
3527
		if (
3528
			// the plugin was auto-activated and needs its candy
3529
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3530
		||
3531
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3532
			! Jetpack_Options::get_option( 'activated' )
3533
		) {
3534
			Jetpack::plugin_initialize();
3535
		}
3536
3537
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3538
			Jetpack_Connection_Banner::init();
3539
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3540
			// Upgrade: 1.1 -> 1.1.1
3541
			// Check and see if host can verify the Jetpack servers' SSL certificate
3542
			$args = array();
3543
			Jetpack_Client::_wp_remote_request(
3544
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3545
				$args,
3546
				true
3547
			);
3548
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3549
			// Show the notice on the Dashboard only for now
3550
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3551
		}
3552
3553
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3554
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3555
		}
3556
3557
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3558
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3559
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3560
3561
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3562
			// Artificially throw errors in certain whitelisted cases during plugin activation
3563
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3564
		}
3565
3566
		// Jetpack Manage Activation Screen from .com
3567
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3568
3569
		// Add custom column in wp-admin/users.php to show whether user is linked.
3570
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3571
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3572
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3573
	}
3574
3575
	function admin_body_class( $admin_body_class = '' ) {
3576
		$classes = explode( ' ', trim( $admin_body_class ) );
3577
3578
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3579
3580
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3581
		return " $admin_body_class ";
3582
	}
3583
3584
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3585
		return $admin_body_class . ' jetpack-pagestyles ';
3586
	}
3587
3588
	/**
3589
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3590
	 *
3591
	 * @return null
3592
	 */
3593
	function prepare_manage_jetpack_notice() {
3594
3595
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3596
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3597
	}
3598
3599
	function manage_activate_screen() {
3600
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3601
	}
3602
	/**
3603
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3604
	 * This function artificially throws errors for such cases (whitelisted).
3605
	 *
3606
	 * @param string $plugin The activated plugin.
3607
	 */
3608
	function throw_error_on_activate_plugin( $plugin ) {
3609
		$active_modules = Jetpack::get_active_modules();
3610
3611
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3612
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3613
			$throw = false;
3614
3615
			// Try and make sure it really was the stats plugin
3616
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3617
				if ( 'stats.php' == basename( $plugin ) ) {
3618
					$throw = true;
3619
				}
3620
			} else {
3621
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3622
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3623
					$throw = true;
3624
				}
3625
			}
3626
3627
			if ( $throw ) {
3628
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3629
			}
3630
		}
3631
	}
3632
3633
	function intercept_plugin_error_scrape_init() {
3634
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3635
	}
3636
3637
	function intercept_plugin_error_scrape( $action, $result ) {
3638
		if ( ! $result ) {
3639
			return;
3640
		}
3641
3642
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3643
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3644
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3645
			}
3646
		}
3647
	}
3648
3649
	function add_remote_request_handlers() {
3650
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3651
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3652
	}
3653
3654
	function remote_request_handlers() {
3655
		$action = current_filter();
3656
3657
		switch ( current_filter() ) {
3658
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3659
			$response = $this->upload_handler();
3660
			break;
3661
3662
		case 'wp_ajax_nopriv_jetpack_update_file' :
3663
			$response = $this->upload_handler( true );
3664
			break;
3665
		default :
3666
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3667
			break;
3668
		}
3669
3670
		if ( ! $response ) {
3671
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3672
		}
3673
3674
		if ( is_wp_error( $response ) ) {
3675
			$status_code       = $response->get_error_data();
3676
			$error             = $response->get_error_code();
3677
			$error_description = $response->get_error_message();
3678
3679
			if ( ! is_int( $status_code ) ) {
3680
				$status_code = 400;
3681
			}
3682
3683
			status_header( $status_code );
3684
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3685
		}
3686
3687
		status_header( 200 );
3688
		if ( true === $response ) {
3689
			exit;
3690
		}
3691
3692
		die( json_encode( (object) $response ) );
3693
	}
3694
3695
	/**
3696
	 * Uploads a file gotten from the global $_FILES.
3697
	 * If `$update_media_item` is true and `post_id` is defined
3698
	 * the attachment file of the media item (gotten through of the post_id)
3699
	 * will be updated instead of add a new one.
3700
	 *
3701
	 * @param  boolean $update_media_item - update media attachment
3702
	 * @return array - An array describing the uploadind files process
3703
	 */
3704
	function upload_handler( $update_media_item = false ) {
3705
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3706
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3707
		}
3708
3709
		$user = wp_authenticate( '', '' );
3710
		if ( ! $user || is_wp_error( $user ) ) {
3711
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3712
		}
3713
3714
		wp_set_current_user( $user->ID );
3715
3716
		if ( ! current_user_can( 'upload_files' ) ) {
3717
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3718
		}
3719
3720
		if ( empty( $_FILES ) ) {
3721
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3722
		}
3723
3724
		foreach ( array_keys( $_FILES ) as $files_key ) {
3725
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3726
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3727
			}
3728
		}
3729
3730
		$media_keys = array_keys( $_FILES['media'] );
3731
3732
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3733
		if ( ! $token || is_wp_error( $token ) ) {
3734
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3735
		}
3736
3737
		$uploaded_files = array();
3738
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3739
		unset( $GLOBALS['post'] );
3740
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3741
			$file = array();
3742
			foreach ( $media_keys as $media_key ) {
3743
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3744
			}
3745
3746
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3747
3748
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3749
			if ( $hmac_provided !== $hmac_file ) {
3750
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3751
				continue;
3752
			}
3753
3754
			$_FILES['.jetpack.upload.'] = $file;
3755
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3756
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3757
				$post_id = 0;
3758
			}
3759
3760
			if ( $update_media_item ) {
3761
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3762
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3763
				}
3764
3765
				$media_array = $_FILES['media'];
3766
3767
				$file_array['name'] = $media_array['name'][0];
3768
				$file_array['type'] = $media_array['type'][0];
3769
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3770
				$file_array['error'] = $media_array['error'][0];
3771
				$file_array['size'] = $media_array['size'][0];
3772
3773
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3774
3775
				if ( is_wp_error( $edited_media_item ) ) {
3776
					return $edited_media_item;
3777
				}
3778
3779
				$response = (object) array(
3780
					'id'   => (string) $post_id,
3781
					'file' => (string) $edited_media_item->post_title,
3782
					'url'  => (string) wp_get_attachment_url( $post_id ),
3783
					'type' => (string) $edited_media_item->post_mime_type,
3784
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3785
				);
3786
3787
				return (array) array( $response );
3788
			}
3789
3790
			$attachment_id = media_handle_upload(
3791
				'.jetpack.upload.',
3792
				$post_id,
3793
				array(),
3794
				array(
3795
					'action' => 'jetpack_upload_file',
3796
				)
3797
			);
3798
3799
			if ( ! $attachment_id ) {
3800
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3801
			} elseif ( is_wp_error( $attachment_id ) ) {
3802
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3803
			} else {
3804
				$attachment = get_post( $attachment_id );
3805
				$uploaded_files[$index] = (object) array(
3806
					'id'   => (string) $attachment_id,
3807
					'file' => $attachment->post_title,
3808
					'url'  => wp_get_attachment_url( $attachment_id ),
3809
					'type' => $attachment->post_mime_type,
3810
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3811
				);
3812
				// Zip files uploads are not supported unless they are done for installation purposed
3813
				// lets delete them in case something goes wrong in this whole process
3814
				if ( 'application/zip' === $attachment->post_mime_type ) {
3815
					// Schedule a cleanup for 2 hours from now in case of failed install.
3816
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3817
				}
3818
			}
3819
		}
3820
		if ( ! is_null( $global_post ) ) {
3821
			$GLOBALS['post'] = $global_post;
3822
		}
3823
3824
		return $uploaded_files;
3825
	}
3826
3827
	/**
3828
	 * Add help to the Jetpack page
3829
	 *
3830
	 * @since Jetpack (1.2.3)
3831
	 * @return false if not the Jetpack page
3832
	 */
3833
	function admin_help() {
3834
		$current_screen = get_current_screen();
3835
3836
		// Overview
3837
		$current_screen->add_help_tab(
3838
			array(
3839
				'id'		=> 'home',
3840
				'title'		=> __( 'Home', 'jetpack' ),
3841
				'content'	=>
3842
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3843
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3844
					'<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>',
3845
			)
3846
		);
3847
3848
		// Screen Content
3849
		if ( current_user_can( 'manage_options' ) ) {
3850
			$current_screen->add_help_tab(
3851
				array(
3852
					'id'		=> 'settings',
3853
					'title'		=> __( 'Settings', 'jetpack' ),
3854
					'content'	=>
3855
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3856
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3857
						'<ol>' .
3858
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3859
							'<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>' .
3860
						'</ol>' .
3861
						'<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>'
3862
				)
3863
			);
3864
		}
3865
3866
		// Help Sidebar
3867
		$current_screen->set_help_sidebar(
3868
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3869
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3870
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3871
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3872
		);
3873
	}
3874
3875
	function admin_menu_css() {
3876
		wp_enqueue_style( 'jetpack-icons' );
3877
	}
3878
3879
	function admin_menu_order() {
3880
		return true;
3881
	}
3882
3883
	function enqueue_gutenberg_locale() {
3884
		wp_add_inline_script(
3885
			'wp-i18n',
3886
			'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
3887
		);
3888
	}
3889
3890 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3891
		$jp_menu_order = array();
3892
3893
		foreach ( $menu_order as $index => $item ) {
3894
			if ( $item != 'jetpack' ) {
3895
				$jp_menu_order[] = $item;
3896
			}
3897
3898
			if ( $index == 0 ) {
3899
				$jp_menu_order[] = 'jetpack';
3900
			}
3901
		}
3902
3903
		return $jp_menu_order;
3904
	}
3905
3906
	function admin_head() {
3907 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3908
			/** This action is documented in class.jetpack-admin-page.php */
3909
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3910
	}
3911
3912
	function admin_banner_styles() {
3913
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3914
3915
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3916
			wp_register_style(
3917
				'jetpack-dops-style',
3918
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3919
				array(),
3920
				JETPACK__VERSION
3921
			);
3922
		}
3923
3924
		wp_enqueue_style(
3925
			'jetpack',
3926
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3927
			array( 'jetpack-dops-style' ),
3928
			 JETPACK__VERSION . '-20121016'
3929
		);
3930
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3931
		wp_style_add_data( 'jetpack', 'suffix', $min );
3932
	}
3933
3934
	function plugin_action_links( $actions ) {
3935
3936
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3937
3938
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3939
			return array_merge(
3940
				$jetpack_home,
3941
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3942
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3943
				$actions
3944
				);
3945
			}
3946
3947
		return array_merge( $jetpack_home, $actions );
3948
	}
3949
3950
	/**
3951
	 * This is the first banner
3952
	 * It should be visible only to user that can update the option
3953
	 * Are not connected
3954
	 *
3955
	 * @return null
3956
	 */
3957
	function admin_jetpack_manage_notice() {
3958
		$screen = get_current_screen();
3959
3960
		// Don't show the connect notice on the jetpack settings page.
3961
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3962
			return;
3963
		}
3964
3965
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3966
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3967
		/**
3968
		 * I think it would be great to have different wordsing depending on where you are
3969
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3970
		 * etc..
3971
		 */
3972
3973
		?>
3974
		<div id="message" class="updated jp-banner">
3975
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3976
				<div class="jp-banner__description-container">
3977
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3978
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3979
					<p class="jp-banner__button-container">
3980
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3981
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3982
					</p>
3983
				</div>
3984
		</div>
3985
		<?php
3986
	}
3987
3988
	/**
3989
	 * Returns the url that the user clicks to remove the notice for the big banner
3990
	 * @return string
3991
	 */
3992
	function opt_out_jetpack_manage_url() {
3993
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3994
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3995
	}
3996
	/**
3997
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3998
	 * @return string
3999
	 */
4000
	function opt_in_jetpack_manage_url() {
4001
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
4002
	}
4003
4004
	function opt_in_jetpack_manage_notice() {
4005
		?>
4006
		<div class="wrap">
4007
			<div id="message" class="jetpack-message is-opt-in">
4008
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'https://jetpack.com/support/site-management' ); ?>
4009
			</div>
4010
		</div>
4011
		<?php
4012
4013
	}
4014
	/**
4015
	 * Determines whether to show the notice of not true = display notice
4016
	 * @return bool
4017
	 */
4018
	function can_display_jetpack_manage_notice() {
4019
		// never display the notice to users that can't do anything about it anyways
4020
		if( ! current_user_can( 'jetpack_manage_modules' ) )
4021
			return false;
4022
4023
		// don't display if we are in development more
4024
		if( Jetpack::is_development_mode() ) {
4025
			return false;
4026
		}
4027
		// don't display if the site is private
4028
		if(  ! Jetpack_Options::get_option( 'public' ) )
4029
			return false;
4030
4031
		/**
4032
		 * Should the Jetpack Remote Site Management notice be displayed.
4033
		 *
4034
		 * @since 3.3.0
4035
		 *
4036
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
4037
		 */
4038
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
4039
	}
4040
4041
	/*
4042
	 * Registration flow:
4043
	 * 1 - ::admin_page_load() action=register
4044
	 * 2 - ::try_registration()
4045
	 * 3 - ::register()
4046
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4047
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4048
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4049
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4050
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4051
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4052
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4053
	 *       jetpack_id, jetpack_secret, jetpack_public
4054
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4055
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4056
	 * 5 - user logs in with WP.com account
4057
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4058
	 *		- Jetpack_Client_Server::authorize()
4059
	 *		- Jetpack_Client_Server::get_token()
4060
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4061
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4062
	 *			- which responds with access_token, token_type, scope
4063
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
4064
	 *		- Jetpack::activate_default_modules()
4065
	 *     		- Deactivates deprecated plugins
4066
	 *     		- Activates all default modules
4067
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4068
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4069
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4070
	 *     Done!
4071
	 */
4072
4073
	/**
4074
	 * Handles the page load events for the Jetpack admin page
4075
	 */
4076
	function admin_page_load() {
4077
		$error = false;
4078
4079
		// Make sure we have the right body class to hook stylings for subpages off of.
4080
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4081
4082
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4083
			// Should only be used in intermediate redirects to preserve state across redirects
4084
			Jetpack::restate();
4085
		}
4086
4087
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4088
			// User clicked in the iframe to link their accounts
4089
			if ( ! Jetpack::is_user_connected() ) {
4090
				$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4091
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4092
4093
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4094
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4095
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4096
4097
				if ( isset( $_GET['notes_iframe'] ) )
4098
					$connect_url .= '&notes_iframe';
4099
				wp_redirect( $connect_url );
4100
				exit;
4101
			} else {
4102
				if ( ! isset( $_GET['calypso_env'] ) ) {
4103
					Jetpack::state( 'message', 'already_authorized' );
4104
					wp_safe_redirect( Jetpack::admin_url() );
4105
					exit;
4106
				} else {
4107
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
4108
					$connect_url .= '&already_authorized=true';
4109
					wp_redirect( $connect_url );
4110
					exit;
4111
				}
4112
			}
4113
		}
4114
4115
4116
		if ( isset( $_GET['action'] ) ) {
4117
			switch ( $_GET['action'] ) {
4118
			case 'authorize':
4119
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4120
					Jetpack::state( 'message', 'already_authorized' );
4121
					wp_safe_redirect( Jetpack::admin_url() );
4122
					exit;
4123
				}
4124
				Jetpack::log( 'authorize' );
4125
				$client_server = new Jetpack_Client_Server;
4126
				$client_server->client_authorize();
4127
				exit;
4128
			case 'register' :
4129
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4130
					$error = 'cheatin';
4131
					break;
4132
				}
4133
				check_admin_referer( 'jetpack-register' );
4134
				Jetpack::log( 'register' );
4135
				Jetpack::maybe_set_version_option();
4136
				$registered = Jetpack::try_registration();
4137
				if ( is_wp_error( $registered ) ) {
4138
					$error = $registered->get_error_code();
4139
					Jetpack::state( 'error', $error );
4140
					Jetpack::state( 'error', $registered->get_error_message() );
4141
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4142
						'error_code' => $error,
4143
						'error_message' => $registered->get_error_message()
4144
					) );
4145
					break;
4146
				}
4147
4148
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4149
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4150
4151
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4152
					'from' => $from
4153
				) );
4154
4155
				$url = $this->build_connect_url( true, $redirect, $from );
4156
4157
				if ( ! empty( $_GET['onboarding'] ) ) {
4158
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4159
				}
4160
4161
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4162
					$url = add_query_arg( 'auth_approved', 'true', $url );
4163
				}
4164
4165
				wp_redirect( $url );
4166
				exit;
4167
			case 'activate' :
4168
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4169
					$error = 'cheatin';
4170
					break;
4171
				}
4172
4173
				$module = stripslashes( $_GET['module'] );
4174
				check_admin_referer( "jetpack_activate-$module" );
4175
				Jetpack::log( 'activate', $module );
4176
				if ( ! Jetpack::activate_module( $module ) ) {
4177
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4178
				}
4179
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4180
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4181
				exit;
4182
			case 'activate_default_modules' :
4183
				check_admin_referer( 'activate_default_modules' );
4184
				Jetpack::log( 'activate_default_modules' );
4185
				Jetpack::restate();
4186
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4187
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4188
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4189
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4190
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4191
				exit;
4192
			case 'disconnect' :
4193
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4194
					$error = 'cheatin';
4195
					break;
4196
				}
4197
4198
				check_admin_referer( 'jetpack-disconnect' );
4199
				Jetpack::log( 'disconnect' );
4200
				Jetpack::disconnect();
4201
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4202
				exit;
4203
			case 'reconnect' :
4204
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4205
					$error = 'cheatin';
4206
					break;
4207
				}
4208
4209
				check_admin_referer( 'jetpack-reconnect' );
4210
				Jetpack::log( 'reconnect' );
4211
				$this->disconnect();
4212
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4213
				exit;
4214 View Code Duplication
			case 'deactivate' :
4215
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4216
					$error = 'cheatin';
4217
					break;
4218
				}
4219
4220
				$modules = stripslashes( $_GET['module'] );
4221
				check_admin_referer( "jetpack_deactivate-$modules" );
4222
				foreach ( explode( ',', $modules ) as $module ) {
4223
					Jetpack::log( 'deactivate', $module );
4224
					Jetpack::deactivate_module( $module );
4225
					Jetpack::state( 'message', 'module_deactivated' );
4226
				}
4227
				Jetpack::state( 'module', $modules );
4228
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4229
				exit;
4230
			case 'unlink' :
4231
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4232
				check_admin_referer( 'jetpack-unlink' );
4233
				Jetpack::log( 'unlink' );
4234
				$this->unlink_user();
4235
				Jetpack::state( 'message', 'unlinked' );
4236
				if ( 'sub-unlink' == $redirect ) {
4237
					wp_safe_redirect( admin_url() );
4238
				} else {
4239
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4240
				}
4241
				exit;
4242
			case 'onboard' :
4243
				if ( ! current_user_can( 'manage_options' ) ) {
4244
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4245
				} else {
4246
					Jetpack::create_onboarding_token();
4247
					$url = $this->build_connect_url( true );
4248
4249
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4250
						$url = add_query_arg( 'onboarding', $token, $url );
4251
					}
4252
4253
					$calypso_env = ! empty( $_GET[ 'calypso_env' ] ) ? $_GET[ 'calypso_env' ] : false;
4254
					if ( $calypso_env ) {
4255
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4256
					}
4257
4258
					wp_redirect( $url );
4259
					exit;
4260
				}
4261
				exit;
4262
			default:
4263
				/**
4264
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4265
				 *
4266
				 * @since 2.6.0
4267
				 *
4268
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4269
				 */
4270
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4271
			}
4272
		}
4273
4274
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4275
			self::activate_new_modules( true );
4276
		}
4277
4278
		$message_code = Jetpack::state( 'message' );
4279
		if ( Jetpack::state( 'optin-manage' ) ) {
4280
			$activated_manage = $message_code;
4281
			$message_code = 'jetpack-manage';
4282
		}
4283
4284
		switch ( $message_code ) {
4285
		case 'jetpack-manage':
4286
			$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>';
4287
			if ( $activated_manage ) {
4288
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4289
			}
4290
			break;
4291
4292
		}
4293
4294
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4295
4296
		if ( ! empty( $deactivated_plugins ) ) {
4297
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4298
			$deactivated_titles  = array();
4299
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4300
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4301
					continue;
4302
				}
4303
4304
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4305
			}
4306
4307
			if ( $deactivated_titles ) {
4308
				if ( $this->message ) {
4309
					$this->message .= "<br /><br />\n";
4310
				}
4311
4312
				$this->message .= wp_sprintf(
4313
					_n(
4314
						'Jetpack contains the most recent version of the old %l plugin.',
4315
						'Jetpack contains the most recent versions of the old %l plugins.',
4316
						count( $deactivated_titles ),
4317
						'jetpack'
4318
					),
4319
					$deactivated_titles
4320
				);
4321
4322
				$this->message .= "<br />\n";
4323
4324
				$this->message .= _n(
4325
					'The old version has been deactivated and can be removed from your site.',
4326
					'The old versions have been deactivated and can be removed from your site.',
4327
					count( $deactivated_titles ),
4328
					'jetpack'
4329
				);
4330
			}
4331
		}
4332
4333
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4334
4335
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4336
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4337
		}
4338
4339 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4340
			/**
4341
			 * Fires when a module configuration page is loaded.
4342
			 * The dynamic part of the hook is the configure parameter from the URL.
4343
			 *
4344
			 * @since 1.1.0
4345
			 */
4346
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4347
		}
4348
4349
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4350
	}
4351
4352
	function admin_notices() {
4353
4354
		if ( $this->error ) {
4355
?>
4356
<div id="message" class="jetpack-message jetpack-err">
4357
	<div class="squeezer">
4358
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4359
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4360
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4361
<?php	endif; ?>
4362
	</div>
4363
</div>
4364
<?php
4365
		}
4366
4367
		if ( $this->message ) {
4368
?>
4369
<div id="message" class="jetpack-message">
4370
	<div class="squeezer">
4371
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4372
	</div>
4373
</div>
4374
<?php
4375
		}
4376
4377
		if ( $this->privacy_checks ) :
4378
			$module_names = $module_slugs = array();
4379
4380
			$privacy_checks = explode( ',', $this->privacy_checks );
4381
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4382
			foreach ( $privacy_checks as $module_slug ) {
4383
				$module = Jetpack::get_module( $module_slug );
4384
				if ( ! $module ) {
4385
					continue;
4386
				}
4387
4388
				$module_slugs[] = $module_slug;
4389
				$module_names[] = "<strong>{$module['name']}</strong>";
4390
			}
4391
4392
			$module_slugs = join( ',', $module_slugs );
4393
?>
4394
<div id="message" class="jetpack-message jetpack-err">
4395
	<div class="squeezer">
4396
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4397
		<p><?php
4398
			echo wp_kses(
4399
				wptexturize(
4400
					wp_sprintf(
4401
						_nx(
4402
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4403
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4404
							count( $privacy_checks ),
4405
							'%l = list of Jetpack module/feature names',
4406
							'jetpack'
4407
						),
4408
						$module_names
4409
					)
4410
				),
4411
				array( 'strong' => true )
4412
			);
4413
4414
			echo "\n<br />\n";
4415
4416
			echo wp_kses(
4417
				sprintf(
4418
					_nx(
4419
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4420
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4421
						count( $privacy_checks ),
4422
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4423
						'jetpack'
4424
					),
4425
					wp_nonce_url(
4426
						Jetpack::admin_url(
4427
							array(
4428
								'page'   => 'jetpack',
4429
								'action' => 'deactivate',
4430
								'module' => urlencode( $module_slugs ),
4431
							)
4432
						),
4433
						"jetpack_deactivate-$module_slugs"
4434
					),
4435
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4436
				),
4437
				array( 'a' => array( 'href' => true, 'title' => true ) )
4438
			);
4439
		?></p>
4440
	</div>
4441
</div>
4442
<?php endif;
4443
	// only display the notice if the other stuff is not there
4444
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4445
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4446
			$this->opt_in_jetpack_manage_notice();
4447
		}
4448
	}
4449
4450
	/**
4451
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4452
	 */
4453
	function stat( $group, $detail ) {
4454
		if ( ! isset( $this->stats[ $group ] ) )
4455
			$this->stats[ $group ] = array();
4456
		$this->stats[ $group ][] = $detail;
4457
	}
4458
4459
	/**
4460
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4461
	 */
4462
	function do_stats( $method = '' ) {
4463
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4464
			foreach ( $this->stats as $group => $stats ) {
4465
				if ( is_array( $stats ) && count( $stats ) ) {
4466
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4467
					if ( 'server_side' === $method ) {
4468
						self::do_server_side_stat( $args );
4469
					} else {
4470
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4471
					}
4472
				}
4473
				unset( $this->stats[ $group ] );
4474
			}
4475
		}
4476
	}
4477
4478
	/**
4479
	 * Runs stats code for a one-off, server-side.
4480
	 *
4481
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4482
	 *
4483
	 * @return bool If it worked.
4484
	 */
4485
	static function do_server_side_stat( $args ) {
4486
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4487
		if ( is_wp_error( $response ) )
4488
			return false;
4489
4490
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4491
			return false;
4492
4493
		return true;
4494
	}
4495
4496
	/**
4497
	 * Builds the stats url.
4498
	 *
4499
	 * @param $args array|string The arguments to append to the URL.
4500
	 *
4501
	 * @return string The URL to be pinged.
4502
	 */
4503
	static function build_stats_url( $args ) {
4504
		$defaults = array(
4505
			'v'    => 'wpcom2',
4506
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4507
		);
4508
		$args     = wp_parse_args( $args, $defaults );
4509
		/**
4510
		 * Filter the URL used as the Stats tracking pixel.
4511
		 *
4512
		 * @since 2.3.2
4513
		 *
4514
		 * @param string $url Base URL used as the Stats tracking pixel.
4515
		 */
4516
		$base_url = apply_filters(
4517
			'jetpack_stats_base_url',
4518
			'https://pixel.wp.com/g.gif'
4519
		);
4520
		$url      = add_query_arg( $args, $base_url );
4521
		return $url;
4522
	}
4523
4524
	static function translate_current_user_to_role() {
4525
		foreach ( self::$capability_translations as $role => $cap ) {
4526
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4527
				return $role;
4528
			}
4529
		}
4530
4531
		return false;
4532
	}
4533
4534
	static function translate_user_to_role( $user ) {
4535
		foreach ( self::$capability_translations as $role => $cap ) {
4536
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4537
				return $role;
4538
			}
4539
		}
4540
4541
		return false;
4542
    }
4543
4544
	static function translate_role_to_cap( $role ) {
4545
		if ( ! isset( self::$capability_translations[$role] ) ) {
4546
			return false;
4547
		}
4548
4549
		return self::$capability_translations[$role];
4550
	}
4551
4552
	static function sign_role( $role, $user_id = null ) {
4553
		if ( empty( $user_id ) ) {
4554
			$user_id = (int) get_current_user_id();
4555
		}
4556
4557
		if ( ! $user_id  ) {
4558
			return false;
4559
		}
4560
4561
		$token = Jetpack_Data::get_access_token();
4562
		if ( ! $token || is_wp_error( $token ) ) {
4563
			return false;
4564
		}
4565
4566
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4567
	}
4568
4569
4570
	/**
4571
	 * Builds a URL to the Jetpack connection auth page
4572
	 *
4573
	 * @since 3.9.5
4574
	 *
4575
	 * @param bool $raw If true, URL will not be escaped.
4576
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4577
	 *                              If string, will be a custom redirect.
4578
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4579
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4580
	 *
4581
	 * @return string Connect URL
4582
	 */
4583
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4584
		$site_id = Jetpack_Options::get_option( 'id' );
4585
		$token = Jetpack_Options::get_option( 'blog_token' );
4586
4587
		if ( $register || ! $token || ! $site_id ) {
4588
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4589
4590
			if ( ! empty( $redirect ) ) {
4591
				$url = add_query_arg(
4592
					'redirect',
4593
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4594
					$url
4595
				);
4596
			}
4597
4598
			if( is_network_admin() ) {
4599
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4600
			}
4601
		} else {
4602
4603
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4604
			// because otherwise this logic can get us in to a loop.
4605
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4606
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4607
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4608
4609
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4610
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4611
					'1.1'
4612
				);
4613
4614
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4615
					// Generating a register URL instead to refresh the existing token
4616
					return $this->build_connect_url( $raw, $redirect, $from, true );
4617
				}
4618
			}
4619
4620
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4621
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4622
			}
4623
4624
			$role = self::translate_current_user_to_role();
4625
			$signed_role = self::sign_role( $role );
4626
4627
			$user = wp_get_current_user();
4628
4629
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4630
			$redirect = $redirect
4631
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4632
				: $jetpack_admin_page;
4633
4634
			if( isset( $_REQUEST['is_multisite'] ) ) {
4635
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4636
			}
4637
4638
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4639
4640
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4641
				? get_site_icon_url()
4642
				: false;
4643
4644
			/**
4645
			 * Filter the type of authorization.
4646
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4647
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4648
			 *
4649
			 * @since 4.3.3
4650
			 *
4651
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4652
			 */
4653
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4654
4655
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4656
4657
			$args = urlencode_deep(
4658
				array(
4659
					'response_type' => 'code',
4660
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4661
					'redirect_uri'  => add_query_arg(
4662
						array(
4663
							'action'   => 'authorize',
4664
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4665
							'redirect' => urlencode( $redirect ),
4666
						),
4667
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4668
					),
4669
					'state'         => $user->ID,
4670
					'scope'         => $signed_role,
4671
					'user_email'    => $user->user_email,
4672
					'user_login'    => $user->user_login,
4673
					'is_active'     => Jetpack::is_active(),
4674
					'jp_version'    => JETPACK__VERSION,
4675
					'auth_type'     => $auth_type,
4676
					'secret'        => $secrets['secret_1'],
4677
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4678
					'blogname'      => get_option( 'blogname' ),
4679
					'site_url'      => site_url(),
4680
					'home_url'      => home_url(),
4681
					'site_icon'     => $site_icon,
4682
					'site_lang'     => get_locale(),
4683
					'_ui'           => $tracks_identity['_ui'],
4684
					'_ut'           => $tracks_identity['_ut']
4685
				)
4686
			);
4687
4688
			self::apply_activation_source_to_args( $args );
4689
4690
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4691
		}
4692
4693
		if ( $from ) {
4694
			$url = add_query_arg( 'from', $from, $url );
4695
		}
4696
4697
4698
		if ( isset( $_GET['calypso_env'] ) ) {
4699
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4700
		}
4701
4702
		return $raw ? $url : esc_url( $url );
4703
	}
4704
4705
	public static function apply_activation_source_to_args( &$args ) {
4706
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4707
4708
		if ( $activation_source_name ) {
4709
			$args['_as'] = urlencode( $activation_source_name );
4710
		}
4711
4712
		if ( $activation_source_keyword ) {
4713
			$args['_ak'] = urlencode( $activation_source_keyword );
4714
		}
4715
	}
4716
4717
	function build_reconnect_url( $raw = false ) {
4718
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4719
		return $raw ? $url : esc_url( $url );
4720
	}
4721
4722
	public static function admin_url( $args = null ) {
4723
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4724
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4725
		return $url;
4726
	}
4727
4728
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4729
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4730
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4731
	}
4732
4733
	function dismiss_jetpack_notice() {
4734
4735
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4736
			return;
4737
		}
4738
4739
		switch( $_GET['jetpack-notice'] ) {
4740
			case 'dismiss':
4741
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4742
4743
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4744
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4745
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4746
				}
4747
				break;
4748 View Code Duplication
			case 'jetpack-manage-opt-out':
4749
4750
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4751
					// Don't show the banner again
4752
4753
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4754
					// redirect back to the page that had the notice
4755
					if ( wp_get_referer() ) {
4756
						wp_safe_redirect( wp_get_referer() );
4757
					} else {
4758
						// Take me to Jetpack
4759
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4760
					}
4761
				}
4762
				break;
4763 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4764
4765
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4766
					// Don't show the banner again
4767
4768
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4769
					// redirect back to the page that had the notice
4770
					if ( wp_get_referer() ) {
4771
						wp_safe_redirect( wp_get_referer() );
4772
					} else {
4773
						// Take me to Jetpack
4774
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4775
					}
4776
				}
4777
				break;
4778
			case 'jetpack-manage-opt-in':
4779
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4780
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4781
4782
					$redirection_url = Jetpack::admin_url();
4783
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4784
4785
					// Don't redirect form the Jetpack Setting Page
4786
					$referer_parsed = parse_url ( wp_get_referer() );
4787
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4788
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4789
						// Take the user to Jetpack home except when on the setting page
4790
						$redirection_url = wp_get_referer();
4791
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4792
					}
4793
					// Also update the JSON API FULL MANAGEMENT Option
4794
					Jetpack::activate_module( 'manage', false, false );
4795
4796
					// Special Message when option in.
4797
					Jetpack::state( 'optin-manage', 'true' );
4798
					// Activate the Module if not activated already
4799
4800
					// Redirect properly
4801
					wp_safe_redirect( $redirection_url );
4802
4803
				}
4804
				break;
4805
		}
4806
	}
4807
4808
	public static function admin_screen_configure_module( $module_id ) {
4809
4810
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4811
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4812
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4813
				/**
4814
				 * Fires to diplay a custom module activation screen.
4815
				 *
4816
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4817
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4818
				 *
4819
				 * @module manage
4820
				 *
4821
				 * @since 3.8.0
4822
				 *
4823
				 * @param int $module_id Module ID.
4824
				 */
4825
				do_action( 'display_activate_module_setting_' . $module_id );
4826
			} else {
4827
				self::display_activate_module_link( $module_id );
4828
			}
4829
4830
			return false;
4831
		} ?>
4832
4833
		<div id="jp-settings-screen" style="position: relative">
4834
			<h3>
4835
			<?php
4836
				$module = Jetpack::get_module( $module_id );
4837
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4838
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4839
			?>
4840
			</h3>
4841
			<?php
4842
				/**
4843
				 * Fires within the displayed message when a feature configuation is updated.
4844
				 *
4845
				 * @since 3.4.0
4846
				 *
4847
				 * @param int $module_id Module ID.
4848
				 */
4849
				do_action( 'jetpack_notices_update_settings', $module_id );
4850
				/**
4851
				 * Fires when a feature configuation screen is loaded.
4852
				 * The dynamic part of the hook, $module_id, is the module ID.
4853
				 *
4854
				 * @since 1.1.0
4855
				 */
4856
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4857
			?>
4858
		</div><?php
4859
	}
4860
4861
	/**
4862
	 * Display link to activate the module to see the settings screen.
4863
	 * @param  string $module_id
4864
	 * @return null
4865
	 */
4866
	public static function display_activate_module_link( $module_id ) {
4867
4868
		$info =  Jetpack::get_module( $module_id );
4869
		$extra = '';
4870
		$activate_url = wp_nonce_url(
4871
				Jetpack::admin_url(
4872
					array(
4873
						'page'   => 'jetpack',
4874
						'action' => 'activate',
4875
						'module' => $module_id,
4876
					)
4877
				),
4878
				"jetpack_activate-$module_id"
4879
			);
4880
4881
		?>
4882
4883
		<div class="wrap configure-module">
4884
			<div id="jp-settings-screen">
4885
				<?php
4886
				if ( $module_id == 'json-api' ) {
4887
4888
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4889
4890
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4891
4892
					$info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'https://jetpack.com/support/site-management' );
4893
4894
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4895
				} ?>
4896
4897
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4898
				<div class="narrow">
4899
					<p><?php echo  $info['description']; ?></p>
4900
					<?php if( $extra ) { ?>
4901
					<p><?php echo esc_html( $extra ); ?></p>
4902
					<?php } ?>
4903
					<p>
4904
						<?php
4905
						if( wp_get_referer() ) {
4906
							printf( __( '<a class="button-primary" href="%s">Activate Now</a> or <a href="%s" >return to previous page</a>.', 'jetpack' ) , $activate_url, wp_get_referer() );
4907
						} else {
4908
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4909
						} ?>
4910
					</p>
4911
				</div>
4912
4913
			</div>
4914
		</div>
4915
4916
		<?php
4917
	}
4918
4919
	public static function sort_modules( $a, $b ) {
4920
		if ( $a['sort'] == $b['sort'] )
4921
			return 0;
4922
4923
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4924
	}
4925
4926
	function ajax_recheck_ssl() {
4927
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4928
		$result = Jetpack::permit_ssl( true );
4929
		wp_send_json( array(
4930
			'enabled' => $result,
4931
			'message' => get_transient( 'jetpack_https_test_message' )
4932
		) );
4933
	}
4934
4935
/* Client API */
4936
4937
	/**
4938
	 * Returns the requested Jetpack API URL
4939
	 *
4940
	 * @return string
4941
	 */
4942
	public static function api_url( $relative_url ) {
4943
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4944
	}
4945
4946
	/**
4947
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4948
	 */
4949
	public static function fix_url_for_bad_hosts( $url ) {
4950
		if ( 0 !== strpos( $url, 'https://' ) ) {
4951
			return $url;
4952
		}
4953
4954
		switch ( JETPACK_CLIENT__HTTPS ) {
4955
			case 'ALWAYS' :
4956
				return $url;
4957
			case 'NEVER' :
4958
				return set_url_scheme( $url, 'http' );
4959
			// default : case 'AUTO' :
4960
		}
4961
4962
		// we now return the unmodified SSL URL by default, as a security precaution
4963
		return $url;
4964
	}
4965
4966
	/**
4967
	 * Create a random secret for validating onboarding payload
4968
	 *
4969
	 * @return string Secret token
4970
	 */
4971
	public static function create_onboarding_token() {
4972
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4973
			$token = wp_generate_password( 32, false );
4974
			Jetpack_Options::update_option( 'onboarding', $token );
4975
		}
4976
4977
		return $token;
4978
	}
4979
4980
	/**
4981
	 * Remove the onboarding token
4982
	 *
4983
	 * @return bool True on success, false on failure
4984
	 */
4985
	public static function invalidate_onboarding_token() {
4986
		return Jetpack_Options::delete_option( 'onboarding' );
4987
	}
4988
4989
	/**
4990
	 * Validate an onboarding token for a specific action
4991
	 *
4992
	 * @return boolean True if token/action pair is accepted, false if not
4993
	 */
4994
	public static function validate_onboarding_token_action( $token, $action ) {
4995
		// Compare tokens, bail if tokens do not match
4996
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
4997
			return false;
4998
		}
4999
5000
		// List of valid actions we can take
5001
		$valid_actions = array(
5002
			'/jetpack/v4/settings',
5003
		);
5004
5005
		// Whitelist the action
5006
		if ( ! in_array( $action, $valid_actions ) ) {
5007
			return false;
5008
		}
5009
5010
		return true;
5011
	}
5012
5013
	/**
5014
	 * Checks to see if the URL is using SSL to connect with Jetpack
5015
	 *
5016
	 * @since 2.3.3
5017
	 * @return boolean
5018
	 */
5019
	public static function permit_ssl( $force_recheck = false ) {
5020
		// Do some fancy tests to see if ssl is being supported
5021
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5022
			$message = '';
5023
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5024
				$ssl = 0;
5025
			} else {
5026
				switch ( JETPACK_CLIENT__HTTPS ) {
5027
					case 'NEVER':
5028
						$ssl = 0;
5029
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5030
						break;
5031
					case 'ALWAYS':
5032
					case 'AUTO':
5033
					default:
5034
						$ssl = 1;
5035
						break;
5036
				}
5037
5038
				// If it's not 'NEVER', test to see
5039
				if ( $ssl ) {
5040
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5041
						$ssl = 0;
5042
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5043
					} else {
5044
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5045
						if ( is_wp_error( $response ) ) {
5046
							$ssl = 0;
5047
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5048
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5049
							$ssl = 0;
5050
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5051
						}
5052
					}
5053
				}
5054
			}
5055
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5056
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5057
		}
5058
5059
		return (bool) $ssl;
5060
	}
5061
5062
	/*
5063
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5064
	 */
5065
	public function alert_auto_ssl_fail() {
5066
		if ( ! current_user_can( 'manage_options' ) )
5067
			return;
5068
5069
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5070
		?>
5071
5072
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5073
			<div class="jp-banner__content">
5074
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5075
				<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>
5076
				<p>
5077
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5078
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5079
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5080
				</p>
5081
				<p>
5082
					<?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' ),
5083
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
5084
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
5085
				</p>
5086
			</div>
5087
		</div>
5088
		<style>
5089
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5090
		</style>
5091
		<script type="text/javascript">
5092
			jQuery( document ).ready( function( $ ) {
5093
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5094
					var $this = $( this );
5095
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5096
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5097
					e.preventDefault();
5098
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5099
					$.post( ajaxurl, data )
5100
					  .done( function( response ) {
5101
					  	if ( response.enabled ) {
5102
					  		$( '#jetpack-ssl-warning' ).hide();
5103
					  	} else {
5104
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5105
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5106
					  	}
5107
					  }.bind( $this ) );
5108
				} );
5109
			} );
5110
		</script>
5111
5112
		<?php
5113
	}
5114
5115
	/**
5116
	 * Returns the Jetpack XML-RPC API
5117
	 *
5118
	 * @return string
5119
	 */
5120
	public static function xmlrpc_api_url() {
5121
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
5122
		return untrailingslashit( $base ) . '/xmlrpc.php';
5123
	}
5124
5125
	/**
5126
	 * Creates two secret tokens and the end of life timestamp for them.
5127
	 *
5128
	 * Note these tokens are unique per call, NOT static per site for connecting.
5129
	 *
5130
	 * @since 2.6
5131
	 * @return array
5132
	 */
5133
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5134
		if ( ! $user_id ) {
5135
			$user_id = get_current_user_id();
5136
		}
5137
5138
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
5139
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5140
5141
		if (
5142
			isset( $secrets[ $secret_name ] ) &&
5143
			$secrets[ $secret_name ]['exp'] > time()
5144
		) {
5145
			return $secrets[ $secret_name ];
5146
		}
5147
5148
		$secret_value = array(
5149
			'secret_1'  => wp_generate_password( 32, false ),
5150
			'secret_2'  => wp_generate_password( 32, false ),
5151
			'exp'       => time() + $exp,
5152
		);
5153
5154
		$secrets[ $secret_name ] = $secret_value;
5155
5156
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5157
		return $secrets[ $secret_name ];
5158
	}
5159
5160
	public static function get_secrets( $action, $user_id ) {
5161
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5162
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5163
5164
		if ( ! isset( $secrets[ $secret_name ] ) ) {
5165
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5166
		}
5167
5168
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
5169
			self::delete_secrets( $action, $user_id );
5170
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5171
		}
5172
5173
		return $secrets[ $secret_name ];
5174
	}
5175
5176
	public static function delete_secrets( $action, $user_id ) {
5177
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5178
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5179
		if ( isset( $secrets[ $secret_name ] ) ) {
5180
			unset( $secrets[ $secret_name ] );
5181
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5182
		}
5183
	}
5184
5185
	/**
5186
	 * Builds the timeout limit for queries talking with the wpcom servers.
5187
	 *
5188
	 * Based on local php max_execution_time in php.ini
5189
	 *
5190
	 * @since 2.6
5191
	 * @return int
5192
	 * @deprecated
5193
	 **/
5194
	public function get_remote_query_timeout_limit() {
5195
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5196
		return Jetpack::get_max_execution_time();
5197
	}
5198
5199
	/**
5200
	 * Builds the timeout limit for queries talking with the wpcom servers.
5201
	 *
5202
	 * Based on local php max_execution_time in php.ini
5203
	 *
5204
	 * @since 5.4
5205
	 * @return int
5206
	 **/
5207
	public static function get_max_execution_time() {
5208
		$timeout = (int) ini_get( 'max_execution_time' );
5209
5210
		// Ensure exec time set in php.ini
5211
		if ( ! $timeout ) {
5212
			$timeout = 30;
5213
		}
5214
		return $timeout;
5215
	}
5216
5217
	/**
5218
	 * Sets a minimum request timeout, and returns the current timeout
5219
	 *
5220
	 * @since 5.4
5221
	 **/
5222
	public static function set_min_time_limit( $min_timeout ) {
5223
		$timeout = self::get_max_execution_time();
5224
		if ( $timeout < $min_timeout ) {
5225
			$timeout = $min_timeout;
5226
			set_time_limit( $timeout );
5227
		}
5228
		return $timeout;
5229
	}
5230
5231
5232
	/**
5233
	 * Takes the response from the Jetpack register new site endpoint and
5234
	 * verifies it worked properly.
5235
	 *
5236
	 * @since 2.6
5237
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5238
	 **/
5239
	public function validate_remote_register_response( $response ) {
5240
	  if ( is_wp_error( $response ) ) {
5241
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5242
		}
5243
5244
		$code   = wp_remote_retrieve_response_code( $response );
5245
		$entity = wp_remote_retrieve_body( $response );
5246
		if ( $entity )
5247
			$registration_response = json_decode( $entity );
5248
		else
5249
			$registration_response = false;
5250
5251
		$code_type = intval( $code / 100 );
5252
		if ( 5 == $code_type ) {
5253
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5254
		} elseif ( 408 == $code ) {
5255
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5256
		} elseif ( ! empty( $registration_response->error ) ) {
5257
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5258
				$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' );
5259
			} else {
5260
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5261
			}
5262
5263
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5264
		} elseif ( 200 != $code ) {
5265
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5266
		}
5267
5268
		// Jetpack ID error block
5269
		if ( empty( $registration_response->jetpack_id ) ) {
5270
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5271
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5272
			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 );
5273
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5274
			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 );
5275
		}
5276
5277
	    return $registration_response;
5278
	}
5279
	/**
5280
	 * @return bool|WP_Error
5281
	 */
5282
	public static function register() {
5283
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5284
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5285
		$secrets = Jetpack::generate_secrets( 'register' );
5286
5287 View Code Duplication
		if (
5288
			empty( $secrets['secret_1'] ) ||
5289
			empty( $secrets['secret_2'] ) ||
5290
			empty( $secrets['exp'] )
5291
		) {
5292
			return new Jetpack_Error( 'missing_secrets' );
5293
		}
5294
5295
		// better to try (and fail) to set a higher timeout than this system
5296
		// supports than to have register fail for more users than it should
5297
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5298
5299
		$gmt_offset = get_option( 'gmt_offset' );
5300
		if ( ! $gmt_offset ) {
5301
			$gmt_offset = 0;
5302
		}
5303
5304
		$stats_options = get_option( 'stats_options' );
5305
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5306
5307
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5308
5309
		$args = array(
5310
			'method'  => 'POST',
5311
			'body'    => array(
5312
				'siteurl'         => site_url(),
5313
				'home'            => home_url(),
5314
				'gmt_offset'      => $gmt_offset,
5315
				'timezone_string' => (string) get_option( 'timezone_string' ),
5316
				'site_name'       => (string) get_option( 'blogname' ),
5317
				'secret_1'        => $secrets['secret_1'],
5318
				'secret_2'        => $secrets['secret_2'],
5319
				'site_lang'       => get_locale(),
5320
				'timeout'         => $timeout,
5321
				'stats_id'        => $stats_id,
5322
				'state'           => get_current_user_id(),
5323
				'_ui'             => $tracks_identity['_ui'],
5324
				'_ut'             => $tracks_identity['_ut'],
5325
				'jetpack_version' => JETPACK__VERSION
5326
			),
5327
			'headers' => array(
5328
				'Accept' => 'application/json',
5329
			),
5330
			'timeout' => $timeout,
5331
		);
5332
5333
		self::apply_activation_source_to_args( $args['body'] );
5334
5335
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5336
5337
		// Make sure the response is valid and does not contain any Jetpack errors
5338
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5339
		if ( is_wp_error( $registration_details ) ) {
5340
			return $registration_details;
5341
		} elseif ( ! $registration_details ) {
5342
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5343
		}
5344
5345 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5346
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5347
		}
5348
5349
		if ( isset( $registration_details->jetpack_public ) ) {
5350
			$jetpack_public = (int) $registration_details->jetpack_public;
5351
		} else {
5352
			$jetpack_public = false;
5353
		}
5354
5355
		Jetpack_Options::update_options(
5356
			array(
5357
				'id'         => (int)    $registration_details->jetpack_id,
5358
				'blog_token' => (string) $registration_details->jetpack_secret,
5359
				'public'     => $jetpack_public,
5360
			)
5361
		);
5362
5363
		/**
5364
		 * Fires when a site is registered on WordPress.com.
5365
		 *
5366
		 * @since 3.7.0
5367
		 *
5368
		 * @param int $json->jetpack_id Jetpack Blog ID.
5369
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5370
		 * @param int|bool $jetpack_public Is the site public.
5371
		 */
5372
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5373
5374
		// Initialize Jump Start for the first and only time.
5375
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5376
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5377
5378
			$jetpack = Jetpack::init();
5379
5380
			$jetpack->stat( 'jumpstart', 'unique-views' );
5381
			$jetpack->do_stats( 'server_side' );
5382
		};
5383
5384
		return true;
5385
	}
5386
5387
	/**
5388
	 * If the db version is showing something other that what we've got now, bump it to current.
5389
	 *
5390
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5391
	 */
5392
	public static function maybe_set_version_option() {
5393
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5394
		if ( JETPACK__VERSION != $version ) {
5395
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5396
5397
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5398
				/** This action is documented in class.jetpack.php */
5399
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5400
			}
5401
5402
			return true;
5403
		}
5404
		return false;
5405
	}
5406
5407
/* Client Server API */
5408
5409
	/**
5410
	 * Loads the Jetpack XML-RPC client
5411
	 */
5412
	public static function load_xml_rpc_client() {
5413
		require_once ABSPATH . WPINC . '/class-IXR.php';
5414
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5415
	}
5416
5417
	/**
5418
	 * Resets the saved authentication state in between testing requests.
5419
	 */
5420
	public function reset_saved_auth_state() {
5421
		$this->xmlrpc_verification = null;
5422
		$this->rest_authentication_status = null;
5423
	}
5424
5425
	function verify_xml_rpc_signature() {
5426
		if ( $this->xmlrpc_verification ) {
5427
			return $this->xmlrpc_verification;
5428
		}
5429
5430
		// It's not for us
5431
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5432
			return false;
5433
		}
5434
5435
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5436
		if (
5437
			empty( $token_key )
5438
		||
5439
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5440
		) {
5441
			return false;
5442
		}
5443
5444
		if ( '0' === $user_id ) {
5445
			$token_type = 'blog';
5446
			$user_id = 0;
5447
		} else {
5448
			$token_type = 'user';
5449
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5450
				return false;
5451
			}
5452
			$user_id = (int) $user_id;
5453
5454
			$user = new WP_User( $user_id );
5455
			if ( ! $user || ! $user->exists() ) {
5456
				return false;
5457
			}
5458
		}
5459
5460
		$token = Jetpack_Data::get_access_token( $user_id );
5461
		if ( ! $token ) {
5462
			return false;
5463
		}
5464
5465
		$token_check = "$token_key.";
5466
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
5467
			return false;
5468
		}
5469
5470
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5471
5472
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5473
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5474
			$post_data   = $_POST;
5475
			$file_hashes = array();
5476
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5477
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5478
					continue;
5479
				}
5480
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5481
				$file_hashes[$post_data_key] = $post_data_value;
5482
			}
5483
5484
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5485
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5486
				$post_data[$post_data_key] = $post_data_value;
5487
			}
5488
5489
			ksort( $post_data );
5490
5491
			$body = http_build_query( stripslashes_deep( $post_data ) );
5492
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5493
			$body = file_get_contents( 'php://input' );
5494
		} else {
5495
			$body = null;
5496
		}
5497
5498
		$signature = $jetpack_signature->sign_current_request(
5499
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5500
		);
5501
5502
		if ( ! $signature ) {
5503
			return false;
5504
		} else if ( is_wp_error( $signature ) ) {
5505
			return $signature;
5506
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
5507
			return false;
5508
		}
5509
5510
		$timestamp = (int) $_GET['timestamp'];
5511
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5512
5513
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5514
			return false;
5515
		}
5516
5517
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5518
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5519
			if ( ! empty( $_GET['onboarding'] ) ) {
5520
				$jpo = $_GET;
5521
			} else {
5522
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5523
			}
5524
5525
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5526
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5527
5528
			if (
5529
				isset( $jpo_user ) && isset( $jpo_token ) &&
5530
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5531
				isset( $_GET['rest_route'] ) &&
5532
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5533
			) {
5534
				$jpUser = get_user_by( 'email', $jpo_user );
5535
				if ( is_a( $jpUser, 'WP_User' ) ) {
5536
					wp_set_current_user( $jpUser->ID );
5537
					$user_can = is_multisite()
5538
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5539
						: current_user_can( 'manage_options' );
5540
					if ( $user_can ) {
5541
						$token_type = 'user';
5542
						$token->external_user_id = $jpUser->ID;
5543
					}
5544
				}
5545
			}
5546
		}
5547
5548
		$this->xmlrpc_verification = array(
5549
			'type'    => $token_type,
5550
			'user_id' => $token->external_user_id,
5551
		);
5552
5553
		return $this->xmlrpc_verification;
5554
	}
5555
5556
	/**
5557
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5558
	 */
5559
	function authenticate_jetpack( $user, $username, $password ) {
5560
		if ( is_a( $user, 'WP_User' ) ) {
5561
			return $user;
5562
		}
5563
5564
		$token_details = $this->verify_xml_rpc_signature();
5565
5566
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5567
			return $user;
5568
		}
5569
5570
		if ( 'user' !== $token_details['type'] ) {
5571
			return $user;
5572
		}
5573
5574
		if ( ! $token_details['user_id'] ) {
5575
			return $user;
5576
		}
5577
5578
		nocache_headers();
5579
5580
		return new WP_User( $token_details['user_id'] );
5581
	}
5582
5583
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5584
	// Uses the existing XMLRPC request signing implementation.
5585
	function wp_rest_authenticate( $user ) {
5586
		if ( ! empty( $user ) ) {
5587
			// Another authentication method is in effect.
5588
			return $user;
5589
		}
5590
5591
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5592
			// Nothing to do for this authentication method.
5593
			return null;
5594
		}
5595
5596
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5597
			// Nothing to do for this authentication method.
5598
			return null;
5599
		}
5600
5601
		// Ensure that we always have the request body available.  At this
5602
		// point, the WP REST API code to determine the request body has not
5603
		// run yet.  That code may try to read from 'php://input' later, but
5604
		// this can only be done once per request in PHP versions prior to 5.6.
5605
		// So we will go ahead and perform this read now if needed, and save
5606
		// the request body where both the Jetpack signature verification code
5607
		// and the WP REST API code can see it.
5608
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5609
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5610
		}
5611
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5612
5613
		// Only support specific request parameters that have been tested and
5614
		// are known to work with signature verification.  A different method
5615
		// can be passed to the WP REST API via the '?_method=' parameter if
5616
		// needed.
5617
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5618
			$this->rest_authentication_status = new WP_Error(
5619
				'rest_invalid_request',
5620
				__( 'This request method is not supported.', 'jetpack' ),
5621
				array( 'status' => 400 )
5622
			);
5623
			return null;
5624
		}
5625
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5626
			$this->rest_authentication_status = new WP_Error(
5627
				'rest_invalid_request',
5628
				__( 'This request method does not support body parameters.', 'jetpack' ),
5629
				array( 'status' => 400 )
5630
			);
5631
			return null;
5632
		}
5633
5634
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
5635
			$content_type = $_SERVER['CONTENT_TYPE'];
5636
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
5637
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
5638
		}
5639
5640
		if (
5641
			isset( $content_type ) &&
5642
			$content_type !== 'application/x-www-form-urlencoded' &&
5643
			$content_type !== 'application/json'
5644
		) {
5645
			$this->rest_authentication_status = new WP_Error(
5646
				'rest_invalid_request',
5647
				__( 'This Content-Type is not supported.', 'jetpack' ),
5648
				array( 'status' => 400 )
5649
			);
5650
			return null;
5651
		}
5652
5653
		$verified = $this->verify_xml_rpc_signature();
5654
5655
		if ( is_wp_error( $verified ) ) {
5656
			$this->rest_authentication_status = $verified;
5657
			return null;
5658
		}
5659
5660
		if (
5661
			$verified &&
5662
			isset( $verified['type'] ) &&
5663
			'user' === $verified['type'] &&
5664
			! empty( $verified['user_id'] )
5665
		) {
5666
			// Authentication successful.
5667
			$this->rest_authentication_status = true;
5668
			return $verified['user_id'];
5669
		}
5670
5671
		// Something else went wrong.  Probably a signature error.
5672
		$this->rest_authentication_status = new WP_Error(
5673
			'rest_invalid_signature',
5674
			__( 'The request is not signed correctly.', 'jetpack' ),
5675
			array( 'status' => 400 )
5676
		);
5677
		return null;
5678
	}
5679
5680
	/**
5681
	 * Report authentication status to the WP REST API.
5682
	 *
5683
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5684
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5685
	 */
5686
	public function wp_rest_authentication_errors( $value ) {
5687
		if ( $value !== null ) {
5688
			return $value;
5689
		}
5690
		return $this->rest_authentication_status;
5691
	}
5692
5693
	function add_nonce( $timestamp, $nonce ) {
5694
		global $wpdb;
5695
		static $nonces_used_this_request = array();
5696
5697
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5698
			return $nonces_used_this_request["$timestamp:$nonce"];
5699
		}
5700
5701
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5702
		$timestamp = (int) $timestamp;
5703
		$nonce     = esc_sql( $nonce );
5704
5705
		// Raw query so we can avoid races: add_option will also update
5706
		$show_errors = $wpdb->show_errors( false );
5707
5708
		$old_nonce = $wpdb->get_row(
5709
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5710
		);
5711
5712
		if ( is_null( $old_nonce ) ) {
5713
			$return = $wpdb->query(
5714
				$wpdb->prepare(
5715
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5716
					"jetpack_nonce_{$timestamp}_{$nonce}",
5717
					time(),
5718
					'no'
5719
				)
5720
			);
5721
		} else {
5722
			$return = false;
5723
		}
5724
5725
		$wpdb->show_errors( $show_errors );
5726
5727
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5728
5729
		return $return;
5730
	}
5731
5732
	/**
5733
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5734
	 * Capture it here so we can verify the signature later.
5735
	 */
5736
	function xmlrpc_methods( $methods ) {
5737
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5738
		return $methods;
5739
	}
5740
5741
	function public_xmlrpc_methods( $methods ) {
5742
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5743
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5744
		}
5745
		return $methods;
5746
	}
5747
5748
	function jetpack_getOptions( $args ) {
5749
		global $wp_xmlrpc_server;
5750
5751
		$wp_xmlrpc_server->escape( $args );
5752
5753
		$username	= $args[1];
5754
		$password	= $args[2];
5755
5756
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5757
			return $wp_xmlrpc_server->error;
5758
		}
5759
5760
		$options = array();
5761
		$user_data = $this->get_connected_user_data();
5762
		if ( is_array( $user_data ) ) {
5763
			$options['jetpack_user_id'] = array(
5764
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5765
				'readonly'      => true,
5766
				'value'         => $user_data['ID'],
5767
			);
5768
			$options['jetpack_user_login'] = array(
5769
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5770
				'readonly'      => true,
5771
				'value'         => $user_data['login'],
5772
			);
5773
			$options['jetpack_user_email'] = array(
5774
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5775
				'readonly'      => true,
5776
				'value'         => $user_data['email'],
5777
			);
5778
			$options['jetpack_user_site_count'] = array(
5779
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5780
				'readonly'      => true,
5781
				'value'         => $user_data['site_count'],
5782
			);
5783
		}
5784
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5785
		$args = stripslashes_deep( $args );
5786
		return $wp_xmlrpc_server->wp_getOptions( $args );
5787
	}
5788
5789
	function xmlrpc_options( $options ) {
5790
		$jetpack_client_id = false;
5791
		if ( self::is_active() ) {
5792
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5793
		}
5794
		$options['jetpack_version'] = array(
5795
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5796
				'readonly'      => true,
5797
				'value'         => JETPACK__VERSION,
5798
		);
5799
5800
		$options['jetpack_client_id'] = array(
5801
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5802
				'readonly'      => true,
5803
				'value'         => $jetpack_client_id,
5804
		);
5805
		return $options;
5806
	}
5807
5808
	public static function clean_nonces( $all = false ) {
5809
		global $wpdb;
5810
5811
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5812
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5813
5814
		if ( true !== $all ) {
5815
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5816
			$sql_args[] = time() - 3600;
5817
		}
5818
5819
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5820
5821
		$sql = $wpdb->prepare( $sql, $sql_args );
5822
5823
		for ( $i = 0; $i < 1000; $i++ ) {
5824
			if ( ! $wpdb->query( $sql ) ) {
5825
				break;
5826
			}
5827
		}
5828
	}
5829
5830
	/**
5831
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5832
	 * SET: state( $key, $value );
5833
	 * GET: $value = state( $key );
5834
	 *
5835
	 * @param string $key
5836
	 * @param string $value
5837
	 * @param bool $restate private
5838
	 */
5839
	public static function state( $key = null, $value = null, $restate = false ) {
5840
		static $state = array();
5841
		static $path, $domain;
5842
		if ( ! isset( $path ) ) {
5843
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5844
			$admin_url = Jetpack::admin_url();
5845
			$bits      = parse_url( $admin_url );
5846
5847
			if ( is_array( $bits ) ) {
5848
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5849
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5850
			} else {
5851
				$path = $domain = null;
5852
			}
5853
		}
5854
5855
		// Extract state from cookies and delete cookies
5856
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5857
			$yum = $_COOKIE[ 'jetpackState' ];
5858
			unset( $_COOKIE[ 'jetpackState' ] );
5859
			foreach ( $yum as $k => $v ) {
5860
				if ( strlen( $v ) )
5861
					$state[ $k ] = $v;
5862
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5863
			}
5864
		}
5865
5866
		if ( $restate ) {
5867
			foreach ( $state as $k => $v ) {
5868
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5869
			}
5870
			return;
5871
		}
5872
5873
		// Get a state variable
5874
		if ( isset( $key ) && ! isset( $value ) ) {
5875
			if ( array_key_exists( $key, $state ) )
5876
				return $state[ $key ];
5877
			return null;
5878
		}
5879
5880
		// Set a state variable
5881
		if ( isset ( $key ) && isset( $value ) ) {
5882
			if( is_array( $value ) && isset( $value[0] ) ) {
5883
				$value = $value[0];
5884
			}
5885
			$state[ $key ] = $value;
5886
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5887
		}
5888
	}
5889
5890
	public static function restate() {
5891
		Jetpack::state( null, null, true );
5892
	}
5893
5894
	public static function check_privacy( $file ) {
5895
		static $is_site_publicly_accessible = null;
5896
5897
		if ( is_null( $is_site_publicly_accessible ) ) {
5898
			$is_site_publicly_accessible = false;
5899
5900
			Jetpack::load_xml_rpc_client();
5901
			$rpc = new Jetpack_IXR_Client();
5902
5903
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5904
			if ( $success ) {
5905
				$response = $rpc->getResponse();
5906
				if ( $response ) {
5907
					$is_site_publicly_accessible = true;
5908
				}
5909
			}
5910
5911
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5912
		}
5913
5914
		if ( $is_site_publicly_accessible ) {
5915
			return;
5916
		}
5917
5918
		$module_slug = self::get_module_slug( $file );
5919
5920
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5921
		if ( ! $privacy_checks ) {
5922
			$privacy_checks = $module_slug;
5923
		} else {
5924
			$privacy_checks .= ",$module_slug";
5925
		}
5926
5927
		Jetpack::state( 'privacy_checks', $privacy_checks );
5928
	}
5929
5930
	/**
5931
	 * Helper method for multicall XMLRPC.
5932
	 */
5933
	public static function xmlrpc_async_call() {
5934
		global $blog_id;
5935
		static $clients = array();
5936
5937
		$client_blog_id = is_multisite() ? $blog_id : 0;
5938
5939
		if ( ! isset( $clients[$client_blog_id] ) ) {
5940
			Jetpack::load_xml_rpc_client();
5941
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5942
			if ( function_exists( 'ignore_user_abort' ) ) {
5943
				ignore_user_abort( true );
5944
			}
5945
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5946
		}
5947
5948
		$args = func_get_args();
5949
5950
		if ( ! empty( $args[0] ) ) {
5951
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5952
		} elseif ( is_multisite() ) {
5953
			foreach ( $clients as $client_blog_id => $client ) {
5954
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5955
					continue;
5956
				}
5957
5958
				$switch_success = switch_to_blog( $client_blog_id, true );
5959
				if ( ! $switch_success ) {
5960
					continue;
5961
				}
5962
5963
				flush();
5964
				$client->query();
5965
5966
				restore_current_blog();
5967
			}
5968
		} else {
5969
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5970
				flush();
5971
				$clients[0]->query();
5972
			}
5973
		}
5974
	}
5975
5976
	public static function staticize_subdomain( $url ) {
5977
5978
		// Extract hostname from URL
5979
		$host = parse_url( $url, PHP_URL_HOST );
5980
5981
		// Explode hostname on '.'
5982
		$exploded_host = explode( '.', $host );
5983
5984
		// Retrieve the name and TLD
5985
		if ( count( $exploded_host ) > 1 ) {
5986
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5987
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5988
			// Rebuild domain excluding subdomains
5989
			$domain = $name . '.' . $tld;
5990
		} else {
5991
			$domain = $host;
5992
		}
5993
		// Array of Automattic domains
5994
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5995
5996
		// Return $url if not an Automattic domain
5997
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5998
			return $url;
5999
		}
6000
6001
		if ( is_ssl() ) {
6002
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
6003
		}
6004
6005
		srand( crc32( basename( $url ) ) );
6006
		$static_counter = rand( 0, 2 );
6007
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
6008
6009
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
6010
	}
6011
6012
/* JSON API Authorization */
6013
6014
	/**
6015
	 * Handles the login action for Authorizing the JSON API
6016
	 */
6017
	function login_form_json_api_authorization() {
6018
		$this->verify_json_api_authorization_request();
6019
6020
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
6021
6022
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
6023
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
6024
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
6025
	}
6026
6027
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
6028
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
6029
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6030
			return $url;
6031
		}
6032
6033
		$parsed_url = parse_url( $url );
6034
		$url = strtok( $url, '?' );
6035
		$url = "$url?{$_SERVER['QUERY_STRING']}";
6036
		if ( ! empty( $parsed_url['query'] ) )
6037
			$url .= "&{$parsed_url['query']}";
6038
6039
		return $url;
6040
	}
6041
6042
	// Make sure the POSTed request is handled by the same action
6043
	function preserve_action_in_login_form_for_json_api_authorization() {
6044
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6045
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6046
	}
6047
6048
	// If someone logs in to approve API access, store the Access Code in usermeta
6049
	function store_json_api_authorization_token( $user_login, $user ) {
6050
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6051
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6052
		$token = wp_generate_password( 32, false );
6053
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6054
	}
6055
6056
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
6057
	function allow_wpcom_public_api_domain( $domains ) {
6058
		$domains[] = 'public-api.wordpress.com';
6059
		return $domains;
6060
	}
6061
6062
	// Add all wordpress.com environments to the safe redirect whitelist
6063
	function allow_wpcom_environments( $domains ) {
6064
		$domains[] = 'wordpress.com';
6065
		$domains[] = 'wpcalypso.wordpress.com';
6066
		$domains[] = 'horizon.wordpress.com';
6067
		$domains[] = 'calypso.localhost';
6068
		return $domains;
6069
	}
6070
6071
	// Add the Access Code details to the public-api.wordpress.com redirect
6072
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6073
		return add_query_arg(
6074
			urlencode_deep(
6075
				array(
6076
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6077
					'jetpack-user-id' => (int) $user->ID,
6078
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6079
				)
6080
			),
6081
			$redirect_to
6082
		);
6083
	}
6084
6085
6086
	/**
6087
	 * Verifies the request by checking the signature
6088
	 *
6089
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6090
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6091
	 *
6092
	 * @param null|array $environment
6093
	 */
6094
	function verify_json_api_authorization_request( $environment = null ) {
6095
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
6096
6097
		$environment = is_null( $environment )
6098
			? $_REQUEST
6099
			: $environment;
6100
6101
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
6102
		$token = Jetpack_Data::get_access_token( $envUserId );
6103
		if ( ! $token || empty( $token->secret ) ) {
6104
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
6105
		}
6106
6107
		$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' );
6108
6109
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6110
6111
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6112
			$signature = $jetpack_signature->sign_request(
6113
				$environment['token'],
6114
				$environment['timestamp'],
6115
				$environment['nonce'],
6116
				'',
6117
				'GET',
6118
				$environment['jetpack_json_api_original_query'],
6119
				null,
6120
				true
6121
			);
6122
		} else {
6123
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
6124
		}
6125
6126
		if ( ! $signature ) {
6127
			wp_die( $die_error );
6128
		} else if ( is_wp_error( $signature ) ) {
6129
			wp_die( $die_error );
6130
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
6131
			if ( is_ssl() ) {
6132
				// 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
6133
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
6134
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
6135
					wp_die( $die_error );
6136
				}
6137
			} else {
6138
				wp_die( $die_error );
6139
			}
6140
		}
6141
6142
		$timestamp = (int) $environment['timestamp'];
6143
		$nonce     = stripslashes( (string) $environment['nonce'] );
6144
6145
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
6146
			// De-nonce the nonce, at least for 5 minutes.
6147
			// 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)
6148
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6149
			if ( $old_nonce_time < time() - 300 ) {
6150
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
6151
			}
6152
		}
6153
6154
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6155
		$data_filters = array(
6156
			'state'        => 'opaque',
6157
			'client_id'    => 'int',
6158
			'client_title' => 'string',
6159
			'client_image' => 'url',
6160
		);
6161
6162
		foreach ( $data_filters as $key => $sanitation ) {
6163
			if ( ! isset( $data->$key ) ) {
6164
				wp_die( $die_error );
6165
			}
6166
6167
			switch ( $sanitation ) {
6168
			case 'int' :
6169
				$this->json_api_authorization_request[$key] = (int) $data->$key;
6170
				break;
6171
			case 'opaque' :
6172
				$this->json_api_authorization_request[$key] = (string) $data->$key;
6173
				break;
6174
			case 'string' :
6175
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6176
				break;
6177
			case 'url' :
6178
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6179
				break;
6180
			}
6181
		}
6182
6183
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6184
			wp_die( $die_error );
6185
		}
6186
	}
6187
6188
	function login_message_json_api_authorization( $message ) {
6189
		return '<p class="message">' . sprintf(
6190
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
6191
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6192
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6193
	}
6194
6195
	/**
6196
	 * Get $content_width, but with a <s>twist</s> filter.
6197
	 */
6198
	public static function get_content_width() {
6199
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
6200
		/**
6201
		 * Filter the Content Width value.
6202
		 *
6203
		 * @since 2.2.3
6204
		 *
6205
		 * @param string $content_width Content Width value.
6206
		 */
6207
		return apply_filters( 'jetpack_content_width', $content_width );
6208
	}
6209
6210
	/**
6211
	 * Pings the WordPress.com Mirror Site for the specified options.
6212
	 *
6213
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6214
	 *
6215
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6216
	 */
6217
	public function get_cloud_site_options( $option_names ) {
6218
		$option_names = array_filter( (array) $option_names, 'is_string' );
6219
6220
		Jetpack::load_xml_rpc_client();
6221
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6222
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6223
		if ( $xml->isError() ) {
6224
			return array(
6225
				'error_code' => $xml->getErrorCode(),
6226
				'error_msg'  => $xml->getErrorMessage(),
6227
			);
6228
		}
6229
		$cloud_site_options = $xml->getResponse();
6230
6231
		return $cloud_site_options;
6232
	}
6233
6234
	/**
6235
	 * Checks if the site is currently in an identity crisis.
6236
	 *
6237
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6238
	 */
6239
	public static function check_identity_crisis() {
6240
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6241
			return false;
6242
		}
6243
6244
		return Jetpack_Options::get_option( 'sync_error_idc' );
6245
	}
6246
6247
	/**
6248
	 * Checks whether the home and siteurl specifically are whitelisted
6249
	 * Written so that we don't have re-check $key and $value params every time
6250
	 * we want to check if this site is whitelisted, for example in footer.php
6251
	 *
6252
	 * @since  3.8.0
6253
	 * @return bool True = already whitelisted False = not whitelisted
6254
	 */
6255
	public static function is_staging_site() {
6256
		$is_staging = false;
6257
6258
		$known_staging = array(
6259
			'urls' => array(
6260
				'#\.staging\.wpengine\.com$#i', // WP Engine
6261
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6262
				),
6263
			'constants' => array(
6264
				'IS_WPE_SNAPSHOT',      // WP Engine
6265
				'KINSTA_DEV_ENV',       // Kinsta.com
6266
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6267
				'JETPACK_STAGING_MODE', // Generic
6268
				)
6269
			);
6270
		/**
6271
		 * Filters the flags of known staging sites.
6272
		 *
6273
		 * @since 3.9.0
6274
		 *
6275
		 * @param array $known_staging {
6276
		 *     An array of arrays that each are used to check if the current site is staging.
6277
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6278
		 *     @type array $constants PHP constants of known staging/developement environments.
6279
		 *  }
6280
		 */
6281
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6282
6283
		if ( isset( $known_staging['urls'] ) ) {
6284
			foreach ( $known_staging['urls'] as $url ){
6285
				if ( preg_match( $url, site_url() ) ) {
6286
					$is_staging = true;
6287
					break;
6288
				}
6289
			}
6290
		}
6291
6292
		if ( isset( $known_staging['constants'] ) ) {
6293
			foreach ( $known_staging['constants'] as $constant ) {
6294
				if ( defined( $constant ) && constant( $constant ) ) {
6295
					$is_staging = true;
6296
				}
6297
			}
6298
		}
6299
6300
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6301
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6302
			$is_staging = true;
6303
		}
6304
6305
		/**
6306
		 * Filters is_staging_site check.
6307
		 *
6308
		 * @since 3.9.0
6309
		 *
6310
		 * @param bool $is_staging If the current site is a staging site.
6311
		 */
6312
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6313
	}
6314
6315
	/**
6316
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6317
	 *
6318
	 * @since 4.4.0
6319
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6320
	 *
6321
	 * @return bool
6322
	 */
6323
	public static function validate_sync_error_idc_option() {
6324
		$is_valid = false;
6325
6326
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6327
		if ( false === $idc_allowed ) {
6328
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6329
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6330
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6331
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6332
				$transient_duration = HOUR_IN_SECONDS;
6333
			} else {
6334
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6335
				$idc_allowed = '1';
6336
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6337
			}
6338
6339
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6340
		}
6341
6342
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6343
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6344
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6345
			$local_options = self::get_sync_error_idc_option();
6346
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6347
				$is_valid = true;
6348
			}
6349
		}
6350
6351
		/**
6352
		 * Filters whether the sync_error_idc option is valid.
6353
		 *
6354
		 * @since 4.4.0
6355
		 *
6356
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6357
		 */
6358
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6359
6360
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6361
			// Since the option exists, and did not validate, delete it
6362
			Jetpack_Options::delete_option( 'sync_error_idc' );
6363
		}
6364
6365
		return $is_valid;
6366
	}
6367
6368
	/**
6369
	 * Normalizes a url by doing three things:
6370
	 *  - Strips protocol
6371
	 *  - Strips www
6372
	 *  - Adds a trailing slash
6373
	 *
6374
	 * @since 4.4.0
6375
	 * @param string $url
6376
	 * @return WP_Error|string
6377
	 */
6378
	public static function normalize_url_protocol_agnostic( $url ) {
6379
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6380
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6381
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6382
		}
6383
6384
		// Strip www and protocols
6385
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6386
		return $url;
6387
	}
6388
6389
	/**
6390
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6391
	 *
6392
	 * @since 4.4.0
6393
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6394
	 *
6395
	 * @param array $response
6396
	 * @return array Array of the local urls, wpcom urls, and error code
6397
	 */
6398
	public static function get_sync_error_idc_option( $response = array() ) {
6399
		// Since the local options will hit the database directly, store the values
6400
		// in a transient to allow for autoloading and caching on subsequent views.
6401
		$local_options = get_transient( 'jetpack_idc_local' );
6402
		if ( false === $local_options ) {
6403
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6404
			$local_options = array(
6405
				'home'    => Jetpack_Sync_Functions::home_url(),
6406
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6407
			);
6408
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6409
		}
6410
6411
		$options = array_merge( $local_options, $response );
6412
6413
		$returned_values = array();
6414
		foreach( $options as $key => $option ) {
6415
			if ( 'error_code' === $key ) {
6416
				$returned_values[ $key ] = $option;
6417
				continue;
6418
			}
6419
6420
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6421
				continue;
6422
			}
6423
6424
			$returned_values[ $key ] = $normalized_url;
6425
		}
6426
6427
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6428
6429
		return $returned_values;
6430
	}
6431
6432
	/**
6433
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6434
	 * If set to true, the site will be put into staging mode.
6435
	 *
6436
	 * @since 4.3.2
6437
	 * @return bool
6438
	 */
6439
	public static function sync_idc_optin() {
6440
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6441
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6442
		} else {
6443
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6444
		}
6445
6446
		/**
6447
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6448
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6449
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6450
		 *
6451
		 * @since 4.3.2
6452
		 *
6453
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6454
		 */
6455
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6456
	}
6457
6458
	/**
6459
	 * Maybe Use a .min.css stylesheet, maybe not.
6460
	 *
6461
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6462
	 */
6463
	public static function maybe_min_asset( $url, $path, $plugin ) {
6464
		// Short out on things trying to find actual paths.
6465
		if ( ! $path || empty( $plugin ) ) {
6466
			return $url;
6467
		}
6468
6469
		$path = ltrim( $path, '/' );
6470
6471
		// Strip out the abspath.
6472
		$base = dirname( plugin_basename( $plugin ) );
6473
6474
		// Short out on non-Jetpack assets.
6475
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6476
			return $url;
6477
		}
6478
6479
		// File name parsing.
6480
		$file              = "{$base}/{$path}";
6481
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6482
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6483
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6484
		$extension         = array_shift( $file_name_parts_r );
6485
6486
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6487
			// Already pointing at the minified version.
6488
			if ( 'min' === $file_name_parts_r[0] ) {
6489
				return $url;
6490
			}
6491
6492
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6493
			if ( file_exists( $min_full_path ) ) {
6494
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6495
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6496
				if ( 'css' === $extension ) {
6497
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6498
					self::$min_assets[ $key ] = $path;
6499
				}
6500
			}
6501
		}
6502
6503
		return $url;
6504
	}
6505
6506
	/**
6507
	 * If the asset is minified, let's flag .min as the suffix.
6508
	 *
6509
	 * Attached to `style_loader_src` filter.
6510
	 *
6511
	 * @param string $tag The tag that would link to the external asset.
6512
	 * @param string $handle The registered handle of the script in question.
6513
	 * @param string $href The url of the asset in question.
6514
	 */
6515
	public static function set_suffix_on_min( $src, $handle ) {
6516
		if ( false === strpos( $src, '.min.css' ) ) {
6517
			return $src;
6518
		}
6519
6520
		if ( ! empty( self::$min_assets ) ) {
6521
			foreach ( self::$min_assets as $file => $path ) {
6522
				if ( false !== strpos( $src, $file ) ) {
6523
					wp_style_add_data( $handle, 'suffix', '.min' );
6524
					return $src;
6525
				}
6526
			}
6527
		}
6528
6529
		return $src;
6530
	}
6531
6532
	/**
6533
	 * Maybe inlines a stylesheet.
6534
	 *
6535
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6536
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6537
	 *
6538
	 * Attached to `style_loader_tag` filter.
6539
	 *
6540
	 * @param string $tag The tag that would link to the external asset.
6541
	 * @param string $handle The registered handle of the script in question.
6542
	 *
6543
	 * @return string
6544
	 */
6545
	public static function maybe_inline_style( $tag, $handle ) {
6546
		global $wp_styles;
6547
		$item = $wp_styles->registered[ $handle ];
6548
6549
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6550
			return $tag;
6551
		}
6552
6553
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6554
			$href = $matches[1];
6555
			// Strip off query string
6556
			if ( $pos = strpos( $href, '?' ) ) {
6557
				$href = substr( $href, 0, $pos );
6558
			}
6559
			// Strip off fragment
6560
			if ( $pos = strpos( $href, '#' ) ) {
6561
				$href = substr( $href, 0, $pos );
6562
			}
6563
		} else {
6564
			return $tag;
6565
		}
6566
6567
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6568
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6569
			return $tag;
6570
		}
6571
6572
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6573
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6574
			// And this isn't the pass that actually deals with the RTL version...
6575
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6576
				// Short out, as the RTL version will deal with it in a moment.
6577
				return $tag;
6578
			}
6579
		}
6580
6581
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6582
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6583
		if ( $css ) {
6584
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6585
			if ( empty( $item->extra['after'] ) ) {
6586
				wp_add_inline_style( $handle, $css );
6587
			} else {
6588
				array_unshift( $item->extra['after'], $css );
6589
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6590
			}
6591
		}
6592
6593
		return $tag;
6594
	}
6595
6596
	/**
6597
	 * Loads a view file from the views
6598
	 *
6599
	 * Data passed in with the $data parameter will be available in the
6600
	 * template file as $data['value']
6601
	 *
6602
	 * @param string $template - Template file to load
6603
	 * @param array $data - Any data to pass along to the template
6604
	 * @return boolean - If template file was found
6605
	 **/
6606
	public function load_view( $template, $data = array() ) {
6607
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6608
6609
		if( file_exists( $views_dir . $template ) ) {
6610
			require_once( $views_dir . $template );
6611
			return true;
6612
		}
6613
6614
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6615
		return false;
6616
	}
6617
6618
	/**
6619
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6620
	 */
6621
	public function deprecated_hooks() {
6622
		global $wp_filter;
6623
6624
		/*
6625
		 * Format:
6626
		 * deprecated_filter_name => replacement_name
6627
		 *
6628
		 * If there is no replacement, use null for replacement_name
6629
		 */
6630
		$deprecated_list = array(
6631
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6632
			'wpl_sharing_2014_1'                                     => null,
6633
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6634
			'jetpack_identity_crisis_options_to_check'               => null,
6635
			'update_option_jetpack_single_user_site'                 => null,
6636
			'audio_player_default_colors'                            => null,
6637
			'add_option_jetpack_featured_images_enabled'             => null,
6638
			'add_option_jetpack_update_details'                      => null,
6639
			'add_option_jetpack_updates'                             => null,
6640
			'add_option_jetpack_network_name'                        => null,
6641
			'add_option_jetpack_network_allow_new_registrations'     => null,
6642
			'add_option_jetpack_network_add_new_users'               => null,
6643
			'add_option_jetpack_network_site_upload_space'           => null,
6644
			'add_option_jetpack_network_upload_file_types'           => null,
6645
			'add_option_jetpack_network_enable_administration_menus' => null,
6646
			'add_option_jetpack_is_multi_site'                       => null,
6647
			'add_option_jetpack_is_main_network'                     => null,
6648
			'add_option_jetpack_main_network_site'                   => null,
6649
			'jetpack_sync_all_registered_options'                    => null,
6650
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6651
			'jetpack_is_post_mailable'                               => null,
6652
			'jetpack_seo_site_host'                                  => null,
6653
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6654
			'jetpack_holiday_snow_option_name'                       => null,
6655
			'jetpack_holiday_chance_of_snow'                         => null,
6656
			'jetpack_holiday_snow_js_url'                            => null,
6657
			'jetpack_is_holiday_snow_season'                         => null,
6658
			'jetpack_holiday_snow_option_updated'                    => null,
6659
			'jetpack_holiday_snowing'                                => null,
6660
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6661
			'jetpack_cache_plans'                                    => null,
6662
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6663
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6664
			'jetpack_enable_site_verification'                       => null,
6665
		);
6666
6667
		// This is a silly loop depth. Better way?
6668
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6669
			if ( has_action( $hook ) ) {
6670
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6671
					foreach( $values AS $hooked ) {
6672
						if ( is_callable( $hooked['function'] ) ) {
6673
							$function_name = 'an anonymous function';
6674
						} else {
6675
							$function_name = $hooked['function'];
6676
						}
6677
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6678
					}
6679
				}
6680
			}
6681
		}
6682
	}
6683
6684
	/**
6685
	 * Converts any url in a stylesheet, to the correct absolute url.
6686
	 *
6687
	 * Considerations:
6688
	 *  - Normal, relative URLs     `feh.png`
6689
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6690
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6691
	 *  - Absolute URLs             `http://domain.com/feh.png`
6692
	 *  - Domain root relative URLs `/feh.png`
6693
	 *
6694
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6695
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6696
	 *
6697
	 * @return mixed|string
6698
	 */
6699
	public static function absolutize_css_urls( $css, $css_file_url ) {
6700
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6701
		$css_dir = dirname( $css_file_url );
6702
		$p       = parse_url( $css_dir );
6703
		$domain  = sprintf(
6704
					'%1$s//%2$s%3$s%4$s',
6705
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6706
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6707
					$p['host'],
6708
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6709
				);
6710
6711
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6712
			$find = $replace = array();
6713
			foreach ( $matches as $match ) {
6714
				$url = trim( $match['path'], "'\" \t" );
6715
6716
				// If this is a data url, we don't want to mess with it.
6717
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6718
					continue;
6719
				}
6720
6721
				// If this is an absolute or protocol-agnostic url,
6722
				// we don't want to mess with it.
6723
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6724
					continue;
6725
				}
6726
6727
				switch ( substr( $url, 0, 1 ) ) {
6728
					case '/':
6729
						$absolute = $domain . $url;
6730
						break;
6731
					default:
6732
						$absolute = $css_dir . '/' . $url;
6733
				}
6734
6735
				$find[]    = $match[0];
6736
				$replace[] = sprintf( 'url("%s")', $absolute );
6737
			}
6738
			$css = str_replace( $find, $replace, $css );
6739
		}
6740
6741
		return $css;
6742
	}
6743
6744
	/**
6745
	 * This methods removes all of the registered css files on the front end
6746
	 * from Jetpack in favor of using a single file. In effect "imploding"
6747
	 * all the files into one file.
6748
	 *
6749
	 * Pros:
6750
	 * - Uses only ONE css asset connection instead of 15
6751
	 * - Saves a minimum of 56k
6752
	 * - Reduces server load
6753
	 * - Reduces time to first painted byte
6754
	 *
6755
	 * Cons:
6756
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6757
	 *		should not cause any issues with themes.
6758
	 * - Plugins/themes dequeuing styles no longer do anything. See
6759
	 *		jetpack_implode_frontend_css filter for a workaround
6760
	 *
6761
	 * For some situations developers may wish to disable css imploding and
6762
	 * instead operate in legacy mode where each file loads seperately and
6763
	 * can be edited individually or dequeued. This can be accomplished with
6764
	 * the following line:
6765
	 *
6766
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6767
	 *
6768
	 * @since 3.2
6769
	 **/
6770
	public function implode_frontend_css( $travis_test = false ) {
6771
		$do_implode = true;
6772
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6773
			$do_implode = false;
6774
		}
6775
6776
		/**
6777
		 * Allow CSS to be concatenated into a single jetpack.css file.
6778
		 *
6779
		 * @since 3.2.0
6780
		 *
6781
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6782
		 */
6783
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6784
6785
		// Do not use the imploded file when default behaviour was altered through the filter
6786
		if ( ! $do_implode ) {
6787
			return;
6788
		}
6789
6790
		// We do not want to use the imploded file in dev mode, or if not connected
6791
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6792
			if ( ! $travis_test ) {
6793
				return;
6794
			}
6795
		}
6796
6797
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6798
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6799
			return;
6800
		}
6801
6802
		/*
6803
		 * Now we assume Jetpack is connected and able to serve the single
6804
		 * file.
6805
		 *
6806
		 * In the future there will be a check here to serve the file locally
6807
		 * or potentially from the Jetpack CDN
6808
		 *
6809
		 * For now:
6810
		 * - Enqueue a single imploded css file
6811
		 * - Zero out the style_loader_tag for the bundled ones
6812
		 * - Be happy, drink scotch
6813
		 */
6814
6815
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6816
6817
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6818
6819
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6820
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6821
	}
6822
6823
	function concat_remove_style_loader_tag( $tag, $handle ) {
6824
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6825
			$tag = '';
6826
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6827
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6828
			}
6829
		}
6830
6831
		return $tag;
6832
	}
6833
6834
	/*
6835
	 * Check the heartbeat data
6836
	 *
6837
	 * Organizes the heartbeat data by severity.  For example, if the site
6838
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6839
	 *
6840
	 * Data will be added to "caution" array, if it either:
6841
	 *  - Out of date Jetpack version
6842
	 *  - Out of date WP version
6843
	 *  - Out of date PHP version
6844
	 *
6845
	 * $return array $filtered_data
6846
	 */
6847
	public static function jetpack_check_heartbeat_data() {
6848
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6849
6850
		$good    = array();
6851
		$caution = array();
6852
		$bad     = array();
6853
6854
		foreach ( $raw_data as $stat => $value ) {
6855
6856
			// Check jetpack version
6857
			if ( 'version' == $stat ) {
6858
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6859
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6860
					continue;
6861
				}
6862
			}
6863
6864
			// Check WP version
6865
			if ( 'wp-version' == $stat ) {
6866
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6867
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6868
					continue;
6869
				}
6870
			}
6871
6872
			// Check PHP version
6873
			if ( 'php-version' == $stat ) {
6874
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6875
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6876
					continue;
6877
				}
6878
			}
6879
6880
			// Check ID crisis
6881
			if ( 'identitycrisis' == $stat ) {
6882
				if ( 'yes' == $value ) {
6883
					$bad[ $stat ] = $value;
6884
					continue;
6885
				}
6886
			}
6887
6888
			// The rest are good :)
6889
			$good[ $stat ] = $value;
6890
		}
6891
6892
		$filtered_data = array(
6893
			'good'    => $good,
6894
			'caution' => $caution,
6895
			'bad'     => $bad
6896
		);
6897
6898
		return $filtered_data;
6899
	}
6900
6901
6902
	/*
6903
	 * This method is used to organize all options that can be reset
6904
	 * without disconnecting Jetpack.
6905
	 *
6906
	 * It is used in class.jetpack-cli.php to reset options
6907
	 *
6908
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6909
	 *
6910
	 * @return array of options to delete.
6911
	 */
6912
	public static function get_jetpack_options_for_reset() {
6913
		return Jetpack_Options::get_options_for_reset();
6914
	}
6915
6916
	/**
6917
	 * Check if an option of a Jetpack module has been updated.
6918
	 *
6919
	 * If any module option has been updated before Jump Start has been dismissed,
6920
	 * update the 'jumpstart' option so we can hide Jump Start.
6921
	 *
6922
	 * @param string $option_name
6923
	 *
6924
	 * @return bool
6925
	 */
6926
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6927
		// Bail if Jump Start has already been dismissed
6928
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6929
			return false;
6930
		}
6931
6932
		$jetpack = Jetpack::init();
6933
6934
		// Manual build of module options
6935
		$option_names = self::get_jetpack_options_for_reset();
6936
6937
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6938
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6939
6940
			//Jump start is being dismissed send data to MC Stats
6941
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6942
6943
			$jetpack->do_stats( 'server_side' );
6944
		}
6945
6946
	}
6947
6948
	/*
6949
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6950
	 * so we can bring them directly to their site in calypso.
6951
	 *
6952
	 * @param string | url
6953
	 * @return string | url without the guff
6954
	 */
6955
	public static function build_raw_urls( $url ) {
6956
		$strip_http = '/.*?:\/\//i';
6957
		$url = preg_replace( $strip_http, '', $url  );
6958
		$url = str_replace( '/', '::', $url );
6959
		return $url;
6960
	}
6961
6962
	/**
6963
	 * Stores and prints out domains to prefetch for page speed optimization.
6964
	 *
6965
	 * @param mixed $new_urls
6966
	 */
6967
	public static function dns_prefetch( $new_urls = null ) {
6968
		static $prefetch_urls = array();
6969
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6970
			echo "\r\n";
6971
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6972
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6973
			}
6974
		} elseif ( ! empty( $new_urls ) ) {
6975
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6976
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6977
			}
6978
			foreach ( (array) $new_urls as $this_new_url ) {
6979
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6980
			}
6981
			$prefetch_urls = array_unique( $prefetch_urls );
6982
		}
6983
	}
6984
6985
	public function wp_dashboard_setup() {
6986
		if ( self::is_active() ) {
6987
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6988
		}
6989
6990
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6991
			wp_add_dashboard_widget(
6992
				'jetpack_summary_widget',
6993
				esc_html__( 'Site Stats', 'jetpack' ),
6994
				array( __CLASS__, 'dashboard_widget' )
6995
			);
6996
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6997
6998
			// If we're inactive and not in development mode, sort our box to the top.
6999
			if ( ! self::is_active() && ! self::is_development_mode() ) {
7000
				global $wp_meta_boxes;
7001
7002
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7003
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7004
7005
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7006
			}
7007
		}
7008
	}
7009
7010
	/**
7011
	 * @param mixed $result Value for the user's option
7012
	 * @return mixed
7013
	 */
7014
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7015
		if ( ! is_array( $sorted ) ) {
7016
			return $sorted;
7017
		}
7018
7019
		foreach ( $sorted as $box_context => $ids ) {
7020
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7021
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7022
				continue;
7023
			}
7024
7025
			$ids_array = explode( ',', $ids );
7026
			$key = array_search( 'dashboard_stats', $ids_array );
7027
7028
			if ( false !== $key ) {
7029
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7030
				$ids_array[ $key ] = 'jetpack_summary_widget';
7031
				$sorted[ $box_context ] = implode( ',', $ids_array );
7032
				// We've found it, stop searching, and just return.
7033
				break;
7034
			}
7035
		}
7036
7037
		return $sorted;
7038
	}
7039
7040
	public static function dashboard_widget() {
7041
		/**
7042
		 * Fires when the dashboard is loaded.
7043
		 *
7044
		 * @since 3.4.0
7045
		 */
7046
		do_action( 'jetpack_dashboard_widget' );
7047
	}
7048
7049
	public static function dashboard_widget_footer() {
7050
		?>
7051
		<footer>
7052
7053
		<div class="protect">
7054
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
7055
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
7056
				<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>
7057
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
7058
				<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' ); ?>">
7059
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
7060
				</a>
7061
			<?php else : ?>
7062
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
7063
			<?php endif; ?>
7064
		</div>
7065
7066
		<div class="akismet">
7067
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7068
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
7069
				<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>
7070
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7071
				<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">
7072
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
7073
				</a>
7074
			<?php else : ?>
7075
				<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>
7076
			<?php endif; ?>
7077
		</div>
7078
7079
		</footer>
7080
		<?php
7081
	}
7082
7083
	/**
7084
	 * Return string containing the Jetpack logo.
7085
	 *
7086
	 * @since 3.9.0
7087
	 *
7088
	 * @return string
7089
	 */
7090
	public static function get_jp_emblem() {
7091
		return '<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 32 32"><path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/></svg>';
7092
	}
7093
7094
	/*
7095
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7096
	 */
7097
	function jetpack_icon_user_connected( $columns ) {
7098
		$columns['user_jetpack'] = '';
7099
		return $columns;
7100
	}
7101
7102
	/*
7103
	 * Show Jetpack icon if the user is linked.
7104
	 */
7105
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7106
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
7107
			$emblem_html = sprintf(
7108
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7109
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7110
				Jetpack::get_jp_emblem()
7111
			);
7112
			return $emblem_html;
7113
		}
7114
7115
		return $val;
7116
	}
7117
7118
	/*
7119
	 * Style the Jetpack user column
7120
	 */
7121
	function jetpack_user_col_style() {
7122
		global $current_screen;
7123
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
7124
			<style>
7125
				.fixed .column-user_jetpack {
7126
					width: 21px;
7127
				}
7128
				.jp-emblem-user-admin svg {
7129
					width: 20px;
7130
					height: 20px;
7131
				}
7132
				.jp-emblem-user-admin path {
7133
					fill: #00BE28;
7134
				}
7135
			</style>
7136
		<?php }
7137
	}
7138
7139
	/**
7140
	 * Checks if Akismet is active and working.
7141
	 *
7142
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7143
	 * that implied usage of methods present since more recent version.
7144
	 * See https://github.com/Automattic/jetpack/pull/9585
7145
	 *
7146
	 * @since  5.1.0
7147
	 *
7148
	 * @return bool True = Akismet available. False = Aksimet not available.
7149
	 */
7150
	public static function is_akismet_active() {
7151
		if ( method_exists( 'Akismet' , 'http_post' ) ) {
7152
			$akismet_key = Akismet::get_api_key();
7153
			if ( ! $akismet_key ) {
7154
				return false;
7155
			}
7156
			$cached_key_verification = get_transient( 'jetpack_akismet_key_is_valid' );
7157
7158
			// We cache the result of the Akismet key verification for ten minutes.
7159
			if ( in_array( $cached_key_verification, array( 'valid', 'invalid' ) ) ) {
7160
				$akismet_key_state = $cached_key_verification;
7161
			} else {
7162
				$akismet_key_state = Akismet::verify_key( $akismet_key );
7163
				if ( 'failed' === $akismet_key_state ) {
7164
					return false;
7165
				}
7166
				set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7167
			}
7168
7169
			return ( 'valid' === $akismet_key_state );
7170
		}
7171
		return false;
7172
	}
7173
7174
	/**
7175
	 * Checks if one or more function names is in debug_backtrace
7176
	 *
7177
	 * @param $names Mixed string name of function or array of string names of functions
7178
	 *
7179
	 * @return bool
7180
	 */
7181
	public static function is_function_in_backtrace( $names ) {
7182
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility
7183
		if ( ! is_array( $names ) ) {
7184
			$names = array( $names );
7185
		}
7186
		$names_as_keys = array_flip( $names );
7187
7188
		//Do check in constant O(1) time for PHP5.5+
7189
		if ( function_exists( 'array_column' ) ) {
7190
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility
7191
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
7192
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
7193
			return ! empty ( $intersection );
7194
		}
7195
7196
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
7197
		foreach ( $backtrace as $call ) {
7198
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
7199
				return true;
7200
			}
7201
		}
7202
		return false;
7203
	}
7204
7205
	/**
7206
	 * Given a minified path, and a non-minified path, will return
7207
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7208
	 *
7209
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7210
	 * root Jetpack directory.
7211
	 *
7212
	 * @since 5.6.0
7213
	 *
7214
	 * @param string $min_path
7215
	 * @param string $non_min_path
7216
	 * @return string The URL to the file
7217
	 */
7218
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7219
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
7220
			? $non_min_path
7221
			: $min_path;
7222
7223
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7224
	}
7225
7226
	/**
7227
	 * Checks for whether Jetpack Rewind is enabled.
7228
	 * Will return true if the state of Rewind is anything except "unavailable".
7229
	 * @return bool|int|mixed
7230
	 */
7231
	public static function is_rewind_enabled() {
7232
		if ( ! Jetpack::is_active() ) {
7233
			return false;
7234
		}
7235
7236
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7237
		if ( false === $rewind_enabled ) {
7238
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7239
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7240
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7241
				&& ! empty( $rewind_data['state'] )
7242
				&& 'active' === $rewind_data['state'] )
7243
				? 1
7244
				: 0;
7245
7246
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7247
		}
7248
		return $rewind_enabled;
7249
	}
7250
7251
	/**
7252
	 * Checks whether or not TOS has been agreed upon.
7253
	 * Will return true if a user has clicked to register, or is already connected.
7254
	 */
7255
	public static function jetpack_tos_agreed() {
7256
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7257
	}
7258
7259
	/**
7260
	 * Handles activating default modules as well general cleanup for the new connection.
7261
	 *
7262
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7263
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7264
	 * @return void
7265
	 */
7266
	public static function handle_post_authorization_actions( $activate_sso = false, $redirect_on_activation_error = false ) {
7267
		$other_modules = $activate_sso
7268
			? array( 'sso' )
7269
			: array();
7270
7271 View Code Duplication
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7272
			Jetpack::delete_active_modules();
7273
7274
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, false );
7275
		} else {
7276
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, false );
7277
		}
7278
7279
		// Since this is a fresh connection, be sure to clear out IDC options
7280
		Jetpack_IDC::clear_all_idc_options();
7281
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7282
7283
		// Start nonce cleaner
7284
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7285
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7286
7287
		Jetpack::state( 'message', 'authorized' );
7288
	}
7289
7290
	/**
7291
	 * Check if Gutenberg editor is available
7292
	 *
7293
	 * @since 6.5.0
7294
	 *
7295
	 * @return bool
7296
	 */
7297
	public static function is_gutenberg_available() {
7298
		return function_exists( 'register_block_type' );
7299
	}
7300
7301
	/**
7302
	 * Load Gutenberg editor blocks.
7303
	 *
7304
	 * This section meant for unstable phase of developing Jetpack's
7305
	 * Gutenberg extensions. If still around after Sep. 15, 2018 then
7306
	 * please file an issue to remove it; if nobody responds within one
7307
	 * week then please delete the code.
7308
	 *
7309
	 *
7310
	 * Loading blocks is disabled by default and enabled via filter:
7311
	 *   add_filter( 'jetpack_gutenberg', '__return_true', 10 );
7312
	 *
7313
	 * When enabled, blocks are loaded from CDN by default. To load locally instead:
7314
	 *   add_filter( 'jetpack_gutenberg_cdn', '__return_false', 10 );
7315
	 *
7316
	 * Note that when loaded locally, you need to build the files yourself:
7317
	 * - _inc/blocks/jetpack-editor.js
7318
	 * - _inc/blocks/jetpack-editor.css
7319
	 *
7320
	 * CDN cache is busted once a day or when Jetpack version changes. To customize it:
7321
	 *   add_filter( 'jetpack_gutenberg_cdn_cache_buster', function( $version ) { return time(); }, 10, 1 );
7322
	 *
7323
	 * @since 6.5.0
7324
	 *
7325
	 * @return void
7326
	 */
7327
	public static function load_jetpack_gutenberg() {
7328
		/**
7329
		 * Filter to turn on loading Gutenberg blocks
7330
		 *
7331
		 * @since 6.5.0
7332
		 *
7333
		 * @param bool false Whether to load Gutenberg blocks
7334
		 */
7335
		if ( ! Jetpack::is_gutenberg_available() || ! apply_filters( 'jetpack_gutenberg', false ) ) {
7336
			return;
7337
		}
7338
7339
		/**
7340
		 * Filter to turn off serving blocks via CDN
7341
		 *
7342
		 * @since 6.5.0
7343
		 *
7344
		 * @param bool true Whether to load Gutenberg blocks from CDN
7345
		 */
7346
		if ( apply_filters( 'jetpack_gutenberg_cdn', true ) ) {
7347
			$editor_script = 'https://s0.wp.com/wp-content/mu-plugins/jetpack/_inc/blocks/jetpack-editor.js';
7348
			$editor_style = 'https://s0.wp.com/wp-content/mu-plugins/jetpack/_inc/blocks/jetpack-editor.css';
7349
7350
			/**
7351
			 * Filter to modify cache busting for Gutenberg block assets loaded from CDN
7352
			 *
7353
			 * @since 6.5.0
7354
			 *
7355
			 * @param string
7356
			 */
7357
			$version = apply_filters( 'jetpack_gutenberg_cdn_cache_buster', sprintf( '%s-%s', gmdate( 'd-m-Y' ), JETPACK__VERSION ) );
7358
		} else {
7359
			$editor_script = plugins_url( '_inc/blocks/jetpack-editor.js', JETPACK__PLUGIN_FILE );
7360
			$editor_style = plugins_url( '_inc/blocks/jetpack-editor.css', JETPACK__PLUGIN_FILE );
7361
			$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . '_inc/blocks/jetpack-editor.js' ) : JETPACK__VERSION;
7362
		}
7363
7364
		wp_register_script(
7365
			'jetpack-blocks-editor',
7366
			$editor_script,
7367
			array(
7368
				'wp-blocks',
7369
				'wp-components',
7370
				'wp-compose',
7371
				'wp-data',
7372
				'wp-editor',
7373
				'wp-element',
7374
				'wp-i18n',
7375
				'wp-plugins',
7376
			),
7377
			$version
7378
		);
7379
7380
		wp_register_style(
7381
			'jetpack-blocks-editor',
7382
			$editor_style,
7383
			array(),
7384
			$version
7385
		);
7386
7387
		register_block_type( 'jetpack/blocks', array(
7388
				'editor_script' => 'jetpack-blocks-editor',
7389
				'editor_style'  => 'jetpack-blocks-editor',
7390
		) );
7391
	}
7392
7393
	/**
7394
	 * Returns a boolean for whether backups UI should be displayed or not.
7395
	 *
7396
	 * @return bool Should backups UI be displayed?
7397
	 */
7398
	public static function show_backups_ui() {
7399
		/**
7400
		 * Whether UI for backups should be displayed.
7401
		 *
7402
		 * @since 6.5.0
7403
		 *
7404
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7405
		 */
7406
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7407
	}
7408
}
7409