Completed
Push — add/user_sync ( 1bae49...8f8a9b )
by
unknown
140:37 queued 131:17
created

class.jetpack.php (3 issues)

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();
0 ignored issues
show
The visibility should be declared for property $min_assets.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

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

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5933
	 * @param string $handle The registered handle of the script in question.
5934
	 * @param string $href The url of the asset in question.
0 ignored issues
show
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5935
	 */
5936
	public static function set_suffix_on_min( $src, $handle ) {
5937
		if ( false === strpos( $src, '.min.css' ) ) {
5938
			return $src;
5939
		}
5940
5941
		if ( ! empty( self::$min_assets ) ) {
5942
			foreach ( self::$min_assets as $file => $path ) {
5943
				if ( false !== strpos( $src, $file ) ) {
5944
					wp_style_add_data( $handle, 'suffix', '.min' );
5945
					return $src;
5946
				}
5947
			}
5948
		}
5949
5950
		return $src;
5951
	}
5952
5953
	/**
5954
	 * Maybe inlines a stylesheet.
5955
	 *
5956
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5957
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5958
	 *
5959
	 * Attached to `style_loader_tag` filter.
5960
	 *
5961
	 * @param string $tag The tag that would link to the external asset.
5962
	 * @param string $handle The registered handle of the script in question.
5963
	 *
5964
	 * @return string
5965
	 */
5966
	public static function maybe_inline_style( $tag, $handle ) {
5967
		global $wp_styles;
5968
		$item = $wp_styles->registered[ $handle ];
5969
5970
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5971
			return $tag;
5972
		}
5973
5974
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5975
			$href = $matches[1];
5976
			// Strip off query string
5977
			if ( $pos = strpos( $href, '?' ) ) {
5978
				$href = substr( $href, 0, $pos );
5979
			}
5980
			// Strip off fragment
5981
			if ( $pos = strpos( $href, '#' ) ) {
5982
				$href = substr( $href, 0, $pos );
5983
			}
5984
		} else {
5985
			return $tag;
5986
		}
5987
5988
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5989
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5990
			return $tag;
5991
		}
5992
5993
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5994
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5995
			// And this isn't the pass that actually deals with the RTL version...
5996
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5997
				// Short out, as the RTL version will deal with it in a moment.
5998
				return $tag;
5999
			}
6000
		}
6001
6002
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6003
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6004
		if ( $css ) {
6005
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6006
			if ( empty( $item->extra['after'] ) ) {
6007
				wp_add_inline_style( $handle, $css );
6008
			} else {
6009
				array_unshift( $item->extra['after'], $css );
6010
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6011
			}
6012
		}
6013
6014
		return $tag;
6015
	}
6016
6017
	/**
6018
	 * Loads a view file from the views
6019
	 *
6020
	 * Data passed in with the $data parameter will be available in the
6021
	 * template file as $data['value']
6022
	 *
6023
	 * @param string $template - Template file to load
6024
	 * @param array $data - Any data to pass along to the template
6025
	 * @return boolean - If template file was found
6026
	 **/
6027
	public function load_view( $template, $data = array() ) {
6028
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6029
6030
		if( file_exists( $views_dir . $template ) ) {
6031
			require_once( $views_dir . $template );
6032
			return true;
6033
		}
6034
6035
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6036
		return false;
6037
	}
6038
6039
	/**
6040
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6041
	 */
6042
	public function deprecated_hooks() {
6043
		global $wp_filter;
6044
6045
		/*
6046
		 * Format:
6047
		 * deprecated_filter_name => replacement_name
6048
		 *
6049
		 * If there is no replacement, use null for replacement_name
6050
		 */
6051
		$deprecated_list = array(
6052
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6053
			'wpl_sharing_2014_1'                                     => null,
6054
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6055
			'jetpack_identity_crisis_options_to_check'               => null,
6056
			'update_option_jetpack_single_user_site'                 => null,
6057
			'audio_player_default_colors'                            => null,
6058
			'add_option_jetpack_featured_images_enabled'             => null,
6059
			'add_option_jetpack_update_details'                      => null,
6060
			'add_option_jetpack_updates'                             => null,
6061
			'add_option_jetpack_network_name'                        => null,
6062
			'add_option_jetpack_network_allow_new_registrations'     => null,
6063
			'add_option_jetpack_network_add_new_users'               => null,
6064
			'add_option_jetpack_network_site_upload_space'           => null,
6065
			'add_option_jetpack_network_upload_file_types'           => null,
6066
			'add_option_jetpack_network_enable_administration_menus' => null,
6067
			'add_option_jetpack_is_multi_site'                       => null,
6068
			'add_option_jetpack_is_main_network'                     => null,
6069
			'add_option_jetpack_main_network_site'                   => null,
6070
			'jetpack_sync_all_registered_options'                    => null,
6071
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6072
			'jetpack_is_post_mailable'                               => null,
6073
			'jetpack_seo_site_host'                                  => null,
6074
		);
6075
6076
		// This is a silly loop depth. Better way?
6077
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6078
			if ( has_action( $hook ) ) {
6079
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6080
					foreach( $values AS $hooked ) {
6081
						if ( is_callable( $hooked['function'] ) ) {
6082
							$function_name = 'an anonymous function';
6083
						} else {
6084
							$function_name = $hooked['function'];
6085
						}
6086
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6087
					}
6088
				}
6089
			}
6090
		}
6091
	}
6092
6093
	/**
6094
	 * Converts any url in a stylesheet, to the correct absolute url.
6095
	 *
6096
	 * Considerations:
6097
	 *  - Normal, relative URLs     `feh.png`
6098
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6099
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6100
	 *  - Absolute URLs             `http://domain.com/feh.png`
6101
	 *  - Domain root relative URLs `/feh.png`
6102
	 *
6103
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6104
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6105
	 *
6106
	 * @return mixed|string
6107
	 */
6108
	public static function absolutize_css_urls( $css, $css_file_url ) {
6109
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6110
		$css_dir = dirname( $css_file_url );
6111
		$p       = parse_url( $css_dir );
6112
		$domain  = sprintf(
6113
					'%1$s//%2$s%3$s%4$s',
6114
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6115
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6116
					$p['host'],
6117
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6118
				);
6119
6120
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6121
			$find = $replace = array();
6122
			foreach ( $matches as $match ) {
6123
				$url = trim( $match['path'], "'\" \t" );
6124
6125
				// If this is a data url, we don't want to mess with it.
6126
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6127
					continue;
6128
				}
6129
6130
				// If this is an absolute or protocol-agnostic url,
6131
				// we don't want to mess with it.
6132
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6133
					continue;
6134
				}
6135
6136
				switch ( substr( $url, 0, 1 ) ) {
6137
					case '/':
6138
						$absolute = $domain . $url;
6139
						break;
6140
					default:
6141
						$absolute = $css_dir . '/' . $url;
6142
				}
6143
6144
				$find[]    = $match[0];
6145
				$replace[] = sprintf( 'url("%s")', $absolute );
6146
			}
6147
			$css = str_replace( $find, $replace, $css );
6148
		}
6149
6150
		return $css;
6151
	}
6152
6153
	/**
6154
	 * This methods removes all of the registered css files on the front end
6155
	 * from Jetpack in favor of using a single file. In effect "imploding"
6156
	 * all the files into one file.
6157
	 *
6158
	 * Pros:
6159
	 * - Uses only ONE css asset connection instead of 15
6160
	 * - Saves a minimum of 56k
6161
	 * - Reduces server load
6162
	 * - Reduces time to first painted byte
6163
	 *
6164
	 * Cons:
6165
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6166
	 *		should not cause any issues with themes.
6167
	 * - Plugins/themes dequeuing styles no longer do anything. See
6168
	 *		jetpack_implode_frontend_css filter for a workaround
6169
	 *
6170
	 * For some situations developers may wish to disable css imploding and
6171
	 * instead operate in legacy mode where each file loads seperately and
6172
	 * can be edited individually or dequeued. This can be accomplished with
6173
	 * the following line:
6174
	 *
6175
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6176
	 *
6177
	 * @since 3.2
6178
	 **/
6179
	public function implode_frontend_css( $travis_test = false ) {
6180
		$do_implode = true;
6181
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6182
			$do_implode = false;
6183
		}
6184
6185
		/**
6186
		 * Allow CSS to be concatenated into a single jetpack.css file.
6187
		 *
6188
		 * @since 3.2.0
6189
		 *
6190
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6191
		 */
6192
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6193
6194
		// Do not use the imploded file when default behaviour was altered through the filter
6195
		if ( ! $do_implode ) {
6196
			return;
6197
		}
6198
6199
		// We do not want to use the imploded file in dev mode, or if not connected
6200
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6201
			if ( ! $travis_test ) {
6202
				return;
6203
			}
6204
		}
6205
6206
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6207
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6208
			return;
6209
		}
6210
6211
		/*
6212
		 * Now we assume Jetpack is connected and able to serve the single
6213
		 * file.
6214
		 *
6215
		 * In the future there will be a check here to serve the file locally
6216
		 * or potentially from the Jetpack CDN
6217
		 *
6218
		 * For now:
6219
		 * - Enqueue a single imploded css file
6220
		 * - Zero out the style_loader_tag for the bundled ones
6221
		 * - Be happy, drink scotch
6222
		 */
6223
6224
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6225
6226
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6227
6228
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6229
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6230
	}
6231
6232
	function concat_remove_style_loader_tag( $tag, $handle ) {
6233
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6234
			$tag = '';
6235
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6236
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6237
			}
6238
		}
6239
6240
		return $tag;
6241
	}
6242
6243
	/*
6244
	 * Check the heartbeat data
6245
	 *
6246
	 * Organizes the heartbeat data by severity.  For example, if the site
6247
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6248
	 *
6249
	 * Data will be added to "caution" array, if it either:
6250
	 *  - Out of date Jetpack version
6251
	 *  - Out of date WP version
6252
	 *  - Out of date PHP version
6253
	 *
6254
	 * $return array $filtered_data
6255
	 */
6256
	public static function jetpack_check_heartbeat_data() {
6257
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6258
6259
		$good    = array();
6260
		$caution = array();
6261
		$bad     = array();
6262
6263
		foreach ( $raw_data as $stat => $value ) {
6264
6265
			// Check jetpack version
6266
			if ( 'version' == $stat ) {
6267
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6268
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6269
					continue;
6270
				}
6271
			}
6272
6273
			// Check WP version
6274
			if ( 'wp-version' == $stat ) {
6275
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6276
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6277
					continue;
6278
				}
6279
			}
6280
6281
			// Check PHP version
6282
			if ( 'php-version' == $stat ) {
6283
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6284
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6285
					continue;
6286
				}
6287
			}
6288
6289
			// Check ID crisis
6290
			if ( 'identitycrisis' == $stat ) {
6291
				if ( 'yes' == $value ) {
6292
					$bad[ $stat ] = $value;
6293
					continue;
6294
				}
6295
			}
6296
6297
			// The rest are good :)
6298
			$good[ $stat ] = $value;
6299
		}
6300
6301
		$filtered_data = array(
6302
			'good'    => $good,
6303
			'caution' => $caution,
6304
			'bad'     => $bad
6305
		);
6306
6307
		return $filtered_data;
6308
	}
6309
6310
6311
	/*
6312
	 * This method is used to organize all options that can be reset
6313
	 * without disconnecting Jetpack.
6314
	 *
6315
	 * It is used in class.jetpack-cli.php to reset options
6316
	 *
6317
	 * @return array of options to delete.
6318
	 */
6319
	public static function get_jetpack_options_for_reset() {
6320
		$jetpack_options            = Jetpack_Options::get_option_names();
6321
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6322
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6323
6324
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6325
6326
		// A manual build of the wp options
6327
		$wp_options = array(
6328
			'sharing-options',
6329
			'disabled_likes',
6330
			'disabled_reblogs',
6331
			'jetpack_comments_likes_enabled',
6332
			'wp_mobile_excerpt',
6333
			'wp_mobile_featured_images',
6334
			'wp_mobile_app_promos',
6335
			'stats_options',
6336
			'stats_dashboard_widget',
6337
			'safecss_preview_rev',
6338
			'safecss_rev',
6339
			'safecss_revision_migrated',
6340
			'nova_menu_order',
6341
			'jetpack_portfolio',
6342
			'jetpack_portfolio_posts_per_page',
6343
			'jetpack_testimonial',
6344
			'jetpack_testimonial_posts_per_page',
6345
			'wp_mobile_custom_css',
6346
			'sharedaddy_disable_resources',
6347
			'sharing-options',
6348
			'sharing-services',
6349
			'site_icon_temp_data',
6350
			'featured-content',
6351
			'site_logo',
6352
			'jetpack_dismissed_notices',
6353
		);
6354
6355
		// Flag some Jetpack options as unsafe
6356
		$unsafe_options = array(
6357
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6358
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6359
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6360
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6361
6362
			// non_compact
6363
			'activated',
6364
6365
			// private
6366
			'register',
6367
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6368
			'user_token',                  // (string) The User Token of this site. (deprecated)
6369
			'user_tokens'
6370
		);
6371
6372
		// Remove the unsafe Jetpack options
6373
		foreach ( $unsafe_options as $unsafe_option ) {
6374
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6375
				unset( $all_jp_options[ $key ] );
6376
			}
6377
		}
6378
6379
		$options = array(
6380
			'jp_options' => $all_jp_options,
6381
			'wp_options' => $wp_options
6382
		);
6383
6384
		return $options;
6385
	}
6386
6387
	/**
6388
	 * Check if an option of a Jetpack module has been updated.
6389
	 *
6390
	 * If any module option has been updated before Jump Start has been dismissed,
6391
	 * update the 'jumpstart' option so we can hide Jump Start.
6392
	 *
6393
	 * @param string $option_name
6394
	 *
6395
	 * @return bool
6396
	 */
6397
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6398
		// Bail if Jump Start has already been dismissed
6399
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6400
			return false;
6401
		}
6402
6403
		$jetpack = Jetpack::init();
6404
6405
		// Manual build of module options
6406
		$option_names = self::get_jetpack_options_for_reset();
6407
6408
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6409
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6410
6411
			//Jump start is being dismissed send data to MC Stats
6412
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6413
6414
			$jetpack->do_stats( 'server_side' );
6415
		}
6416
6417
	}
6418
6419
	/*
6420
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6421
	 * so we can bring them directly to their site in calypso.
6422
	 *
6423
	 * @param string | url
6424
	 * @return string | url without the guff
6425
	 */
6426
	public static function build_raw_urls( $url ) {
6427
		$strip_http = '/.*?:\/\//i';
6428
		$url = preg_replace( $strip_http, '', $url  );
6429
		$url = str_replace( '/', '::', $url );
6430
		return $url;
6431
	}
6432
6433
	/**
6434
	 * Stores and prints out domains to prefetch for page speed optimization.
6435
	 *
6436
	 * @param mixed $new_urls
6437
	 */
6438
	public static function dns_prefetch( $new_urls = null ) {
6439
		static $prefetch_urls = array();
6440
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6441
			echo "\r\n";
6442
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6443
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6444
			}
6445
		} elseif ( ! empty( $new_urls ) ) {
6446
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6447
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6448
			}
6449
			foreach ( (array) $new_urls as $this_new_url ) {
6450
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6451
			}
6452
			$prefetch_urls = array_unique( $prefetch_urls );
6453
		}
6454
	}
6455
6456
	public function wp_dashboard_setup() {
6457
		if ( self::is_active() ) {
6458
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6459
			$widget_title = __( 'Site Stats', 'jetpack' );
6460
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6461
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6462
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6463
		}
6464
6465
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6466
			wp_add_dashboard_widget(
6467
				'jetpack_summary_widget',
6468
				$widget_title,
6469
				array( __CLASS__, 'dashboard_widget' )
6470
			);
6471
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6472
6473
			// If we're inactive and not in development mode, sort our box to the top.
6474
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6475
				global $wp_meta_boxes;
6476
6477
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6478
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6479
6480
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6481
			}
6482
		}
6483
	}
6484
6485
	/**
6486
	 * @param mixed $result Value for the user's option
6487
	 * @return mixed
6488
	 */
6489
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6490
		if ( ! is_array( $sorted ) ) {
6491
			return $sorted;
6492
		}
6493
6494
		foreach ( $sorted as $box_context => $ids ) {
6495
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6496
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6497
				continue;
6498
			}
6499
6500
			$ids_array = explode( ',', $ids );
6501
			$key = array_search( 'dashboard_stats', $ids_array );
6502
6503
			if ( false !== $key ) {
6504
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6505
				$ids_array[ $key ] = 'jetpack_summary_widget';
6506
				$sorted[ $box_context ] = implode( ',', $ids_array );
6507
				// We've found it, stop searching, and just return.
6508
				break;
6509
			}
6510
		}
6511
6512
		return $sorted;
6513
	}
6514
6515
	public static function dashboard_widget() {
6516
		/**
6517
		 * Fires when the dashboard is loaded.
6518
		 *
6519
		 * @since 3.4.0
6520
		 */
6521
		do_action( 'jetpack_dashboard_widget' );
6522
	}
6523
6524
	public static function dashboard_widget_footer() {
6525
		?>
6526
		<footer>
6527
6528
		<div class="protect">
6529
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6530
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6531
				<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>
6532
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6533
				<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' ); ?>">
6534
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6535
				</a>
6536
			<?php else : ?>
6537
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6538
			<?php endif; ?>
6539
		</div>
6540
6541
		<div class="akismet">
6542
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6543
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6544
				<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>
6545
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6546
				<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">
6547
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6548
				</a>
6549
			<?php else : ?>
6550
				<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>
6551
			<?php endif; ?>
6552
		</div>
6553
6554
		</footer>
6555
		<?php
6556
	}
6557
6558
	public function dashboard_widget_connect_to_wpcom() {
6559
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6560
			return;
6561
		}
6562
		?>
6563
		<div class="wpcom-connect">
6564
			<div class="jp-emblem">
6565
			<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">
6566
				<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"/>
6567
			</svg>
6568
			</div>
6569
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6570
			<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>
6571
6572
			<div class="actions">
6573
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6574
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6575
				</a>
6576
			</div>
6577
		</div>
6578
		<?php
6579
	}
6580
6581
	/**
6582
	 * Return string containing the Jetpack logo.
6583
	 *
6584
	 * @since 3.9.0
6585
	 *
6586
	 * @return string
6587
	 */
6588
	public static function get_jp_emblem() {
6589
		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>';
6590
	}
6591
6592
	/*
6593
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6594
	 */
6595
	function jetpack_icon_user_connected( $columns ) {
6596
		$columns['user_jetpack'] = '';
6597
		return $columns;
6598
	}
6599
6600
	/*
6601
	 * Show Jetpack icon if the user is linked.
6602
	 */
6603
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6604
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6605
			$emblem_html = sprintf(
6606
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6607
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6608
				Jetpack::get_jp_emblem()
6609
			);
6610
			return $emblem_html;
6611
		}
6612
6613
		return $val;
6614
	}
6615
6616
	/*
6617
	 * Style the Jetpack user column
6618
	 */
6619
	function jetpack_user_col_style() {
6620
		global $current_screen;
6621
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6622
			<style>
6623
				.fixed .column-user_jetpack {
6624
					width: 21px;
6625
				}
6626
				.jp-emblem-user-admin svg {
6627
					width: 20px;
6628
					height: 20px;
6629
				}
6630
				.jp-emblem-user-admin path {
6631
					fill: #8cc258;
6632
				}
6633
			</style>
6634
		<?php }
6635
	}
6636
6637
	/**
6638
	 * Checks if Akismet is active and working.
6639
	 *
6640
	 * @since  5.1.0
6641
	 * @return bool True = Akismet available. False = Aksimet not available.
6642
	 */
6643
	public static function is_akismet_active() {
6644
		if ( method_exists( 'Akismet' , 'http_post' ) || function_exists( 'akismet_http_post' ) ) {
6645
			return true;
6646
		}
6647
		return false;
6648
	}
6649
6650
	/**
6651
	 * Checks if one or more function names is in debug_backtrace
6652
	 *
6653
	 * @param $names Mixed string name of function or array of string names of functions
6654
	 *
6655
	 * @return bool
6656
	 */
6657
	public static function is_function_in_backtrace( $names ) {
6658
		$backtrace = debug_backtrace( false );
6659
		if ( ! is_array( $names ) ) {
6660
			$names = array( $names );
6661
		}
6662
		$names_as_keys = array_flip( $names );
6663
6664
		//Do check in constant O(1) time for PHP5.5+
6665
		if ( function_exists( 'array_column' ) ) {
6666
			$backtrace_functions = array_column( $backtrace, 'function' );
6667
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6668
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6669
			return ! empty ( $intersection );
6670
		}
6671
6672
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6673
		foreach ( $backtrace as $call ) {
6674
			if ( isset( $names[ $call['function'] ] ) ) {
6675
				return true;
6676
			}
6677
		}
6678
		return false;
6679
	}
6680
}
6681