Completed
Push — update/exit-after-redirect ( 430c2f )
by
unknown
29:03 queued 19:00
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

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

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

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

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