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