Completed
Push — fix/connection-tracking ( 11f338 )
by
unknown
10:24
created

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

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

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

Loading history...
3991
			case 'activate' :
3992
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3993
					$error = 'cheatin';
3994
					break;
3995
				}
3996
3997
				$module = stripslashes( $_GET['module'] );
3998
				check_admin_referer( "jetpack_activate-$module" );
3999
				Jetpack::log( 'activate', $module );
4000
				Jetpack::activate_module( $module );
4001
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4002
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4003
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4004
			case 'activate_default_modules' :
4005
				check_admin_referer( 'activate_default_modules' );
4006
				Jetpack::log( 'activate_default_modules' );
4007
				Jetpack::restate();
4008
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4009
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4010
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4011
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4012
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4013
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4014
			case 'disconnect' :
4015
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4016
					$error = 'cheatin';
4017
					break;
4018
				}
4019
4020
				check_admin_referer( 'jetpack-disconnect' );
4021
				Jetpack::log( 'disconnect' );
4022
				Jetpack::disconnect();
4023
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4024
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4025
			case 'reconnect' :
4026
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4027
					$error = 'cheatin';
4028
					break;
4029
				}
4030
4031
				check_admin_referer( 'jetpack-reconnect' );
4032
				Jetpack::log( 'reconnect' );
4033
				$this->disconnect();
4034
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4035
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4036 View Code Duplication
			case 'deactivate' :
4037
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4038
					$error = 'cheatin';
4039
					break;
4040
				}
4041
4042
				$modules = stripslashes( $_GET['module'] );
4043
				check_admin_referer( "jetpack_deactivate-$modules" );
4044
				foreach ( explode( ',', $modules ) as $module ) {
4045
					Jetpack::log( 'deactivate', $module );
4046
					Jetpack::deactivate_module( $module );
4047
					Jetpack::state( 'message', 'module_deactivated' );
4048
				}
4049
				Jetpack::state( 'module', $modules );
4050
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4051
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4052
			case 'unlink' :
4053
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4054
				check_admin_referer( 'jetpack-unlink' );
4055
				Jetpack::log( 'unlink' );
4056
				$this->unlink_user();
4057
				Jetpack::state( 'message', 'unlinked' );
4058
				if ( 'sub-unlink' == $redirect ) {
4059
					wp_safe_redirect( admin_url() );
4060
				} else {
4061
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4062
				}
4063
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
4064
			default:
4065
				/**
4066
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4067
				 *
4068
				 * @since 2.6.0
4069
				 *
4070
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4071
				 */
4072
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4073
			}
4074
		}
4075
4076
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4077
			self::activate_new_modules( true );
4078
		}
4079
4080
		switch ( $error ) {
4081
		case 'cheatin' :
4082
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
4083
			break;
4084
		case 'access_denied' :
4085
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'http://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
4086
			break;
4087
		case 'wrong_state' :
4088
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
4089
			break;
4090
		case 'invalid_client' :
4091
			// @todo re-register instead of deactivate/reactivate
4092
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
4093
			break;
4094
		case 'invalid_grant' :
4095
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
4096
			break;
4097
		case 'site_inaccessible' :
4098
		case 'site_requires_authorization' :
4099
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
4100
			break;
4101
		case 'module_activation_failed' :
4102
			$module = Jetpack::state( 'module' );
4103
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4104
				$this->error = sprintf( __( '%s could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' ), $mod['name'] );
4105
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
4106
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
4107
				}
4108
			} else {
4109
				$this->error = __( 'Module could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' );
4110
			}
4111
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
4112
				$this->error .= "<br />\n";
4113
				$this->error .= $php_errors;
4114
			}
4115
			break;
4116
		case 'master_user_required' :
4117
			$module = Jetpack::state( 'module' );
4118
			$module_name = '';
4119
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4120
				$module_name = $mod['name'];
4121
			}
4122
4123
			$master_user = Jetpack_Options::get_option( 'master_user' );
4124
			$master_userdata = get_userdata( $master_user ) ;
4125
			if ( $master_userdata ) {
4126
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
4127
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
4128
				} else {
4129
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
4130
				}
4131
				$this->error .= '  ' . sprintf( __( 'This module can only be altered by %s, the user who initiated the Jetpack connection on this site.' , 'jetpack' ), esc_html( $master_userdata->display_name ) );
4132
4133
			} else {
4134
				$this->error = sprintf( __( 'Only the user who initiated the Jetpack connection on this site can toggle %s, but that user no longer exists. This should not happen.', 'jetpack' ), $module_name );
4135
			}
4136
			break;
4137
		case 'not_public' :
4138
			$this->error = __( '<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. This usually means your site is not publicly accessible (localhost).', 'jetpack' );
4139
			break;
4140
		case 'wpcom_408' :
4141
		case 'wpcom_5??' :
4142
		case 'wpcom_bad_response' :
4143
		case 'wpcom_outage' :
4144
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
4145
			break;
4146
		case 'register_http_request_failed' :
4147
		case 'token_http_request_failed' :
4148
			$this->error = sprintf( __( 'Jetpack could not contact WordPress.com: %s.  This usually means something is incorrectly configured on your web host.', 'jetpack' ), "<code>$error</code>" );
4149
			break;
4150
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
4151
			if ( empty( $error ) ) {
4152
				break;
4153
			}
4154
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
4155
			// no break: fall through
4156
		case 'no_role' :
4157
		case 'no_cap' :
4158
		case 'no_code' :
4159
		case 'no_state' :
4160
		case 'invalid_state' :
4161
		case 'invalid_request' :
4162
		case 'invalid_scope' :
4163
		case 'unsupported_response_type' :
4164
		case 'invalid_token' :
4165
		case 'no_token' :
4166
		case 'missing_secrets' :
4167
		case 'home_missing' :
4168
		case 'siteurl_missing' :
4169
		case 'gmt_offset_missing' :
4170
		case 'site_name_missing' :
4171
		case 'secret_1_missing' :
4172
		case 'secret_2_missing' :
4173
		case 'site_lang_missing' :
4174
		case 'home_malformed' :
4175
		case 'siteurl_malformed' :
4176
		case 'gmt_offset_malformed' :
4177
		case 'timezone_string_malformed' :
4178
		case 'site_name_malformed' :
4179
		case 'secret_1_malformed' :
4180
		case 'secret_2_malformed' :
4181
		case 'site_lang_malformed' :
4182
		case 'secrets_mismatch' :
4183
		case 'verify_secret_1_missing' :
4184
		case 'verify_secret_1_malformed' :
4185
		case 'verify_secrets_missing' :
4186
		case 'verify_secrets_mismatch' :
4187
			$error = esc_html( $error );
4188
			$this->error = sprintf( __( '<strong>Your Jetpack has a glitch.</strong>  We&#8217;re sorry for the inconvenience. Please try again later, if the issue continues please contact support with this message: %s', 'jetpack' ), "<code>$error</code>" );
4189
			if ( ! Jetpack::is_active() ) {
4190
				$this->error .= '<br />';
4191
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4192
			}
4193
			break;
4194
		}
4195
4196
		$message_code = Jetpack::state( 'message' );
4197
4198
		$active_state = Jetpack::state( 'activated_modules' );
4199
		if ( ! empty( $active_state ) ) {
4200
			$available    = Jetpack::get_available_modules();
4201
			$active_state = explode( ',', $active_state );
4202
			$active_state = array_intersect( $active_state, $available );
4203
			if ( count( $active_state ) ) {
4204
				foreach ( $active_state as $mod ) {
4205
					$this->stat( 'module-activated', $mod );
4206
				}
4207
			} else {
4208
				$active_state = false;
4209
			}
4210
		}
4211
		if( Jetpack::state( 'optin-manage' ) ) {
4212
			$activated_manage = $message_code;
4213
			$message_code = 'jetpack-manage';
4214
4215
		}
4216
		switch ( $message_code ) {
4217
		case 'modules_activated' :
4218
			$this->message = sprintf(
4219
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4220
				JETPACK__VERSION
4221
			);
4222
4223
			if ( $active_state ) {
4224
				$titles = array();
4225 View Code Duplication
				foreach ( $active_state as $mod ) {
4226
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4227
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4228
					}
4229
				}
4230
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4231
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4232
				}
4233
			}
4234
4235
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4236
				$titles = array();
4237 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4238
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4239
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4240
					}
4241
				}
4242
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4243
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4244
				}
4245
			}
4246
4247
			$this->message .= Jetpack::jetpack_comment_notice();
4248
			break;
4249
		case 'jetpack-manage':
4250
			$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>';
4251
			if ( $activated_manage ) {
4252
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4253
			}
4254
			break;
4255
		case 'module_activated' :
4256
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4257
				$this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking the Deactivate link next to each module.', 'jetpack' ), $module['name'] );
4258
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4259
			}
4260
			break;
4261
4262
		case 'module_deactivated' :
4263
			$modules = Jetpack::state( 'module' );
4264
			if ( ! $modules ) {
4265
				break;
4266
			}
4267
4268
			$module_names = array();
4269
			foreach ( explode( ',', $modules ) as $module_slug ) {
4270
				$module = Jetpack::get_module( $module_slug );
4271
				if ( $module ) {
4272
					$module_names[] = $module['name'];
4273
				}
4274
4275
				$this->stat( 'module-deactivated', $module_slug );
4276
			}
4277
4278
			if ( ! $module_names ) {
4279
				break;
4280
			}
4281
4282
			$this->message = wp_sprintf(
4283
				_nx(
4284
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4285
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4286
					count( $module_names ),
4287
					'%l = list of Jetpack module/feature names',
4288
					'jetpack'
4289
				),
4290
				$module_names
4291
			);
4292
			break;
4293
4294
		case 'module_configured' :
4295
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4296
			break;
4297
4298
		case 'already_authorized' :
4299
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4300
			break;
4301
4302
		case 'authorized' :
4303
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4304
			$this->message .= Jetpack::jetpack_comment_notice();
4305
			break;
4306
4307
		case 'linked' :
4308
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4309
			$this->message .= Jetpack::jetpack_comment_notice();
4310
			break;
4311
4312
		case 'unlinked' :
4313
			$user = wp_get_current_user();
4314
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4315
			break;
4316
4317
		case 'switch_master' :
4318
			global $current_user;
4319
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4320
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4321
			if ( $is_master_user ) {
4322
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4323
			} else {
4324
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4325
			}
4326
			break;
4327
		}
4328
4329
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4330
4331
		if ( ! empty( $deactivated_plugins ) ) {
4332
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4333
			$deactivated_titles  = array();
4334
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4335
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4336
					continue;
4337
				}
4338
4339
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4340
			}
4341
4342
			if ( $deactivated_titles ) {
4343
				if ( $this->message ) {
4344
					$this->message .= "<br /><br />\n";
4345
				}
4346
4347
				$this->message .= wp_sprintf(
4348
					_n(
4349
						'Jetpack contains the most recent version of the old %l plugin.',
4350
						'Jetpack contains the most recent versions of the old %l plugins.',
4351
						count( $deactivated_titles ),
4352
						'jetpack'
4353
					),
4354
					$deactivated_titles
4355
				);
4356
4357
				$this->message .= "<br />\n";
4358
4359
				$this->message .= _n(
4360
					'The old version has been deactivated and can be removed from your site.',
4361
					'The old versions have been deactivated and can be removed from your site.',
4362
					count( $deactivated_titles ),
4363
					'jetpack'
4364
				);
4365
			}
4366
		}
4367
4368
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4369
4370
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4371
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4372
		}
4373
4374 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4375
			/**
4376
			 * Fires when a module configuration page is loaded.
4377
			 * The dynamic part of the hook is the configure parameter from the URL.
4378
			 *
4379
			 * @since 1.1.0
4380
			 */
4381
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4382
		}
4383
4384
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4385
	}
4386
4387
	function admin_notices() {
4388
4389
		if ( $this->error ) {
4390
?>
4391
<div id="message" class="jetpack-message jetpack-err">
4392
	<div class="squeezer">
4393
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4394
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4395
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4396
<?php	endif; ?>
4397
	</div>
4398
</div>
4399
<?php
4400
		}
4401
4402
		if ( $this->message ) {
4403
?>
4404
<div id="message" class="jetpack-message">
4405
	<div class="squeezer">
4406
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4407
	</div>
4408
</div>
4409
<?php
4410
		}
4411
4412
		if ( $this->privacy_checks ) :
4413
			$module_names = $module_slugs = array();
4414
4415
			$privacy_checks = explode( ',', $this->privacy_checks );
4416
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4417
			foreach ( $privacy_checks as $module_slug ) {
4418
				$module = Jetpack::get_module( $module_slug );
4419
				if ( ! $module ) {
4420
					continue;
4421
				}
4422
4423
				$module_slugs[] = $module_slug;
4424
				$module_names[] = "<strong>{$module['name']}</strong>";
4425
			}
4426
4427
			$module_slugs = join( ',', $module_slugs );
4428
?>
4429
<div id="message" class="jetpack-message jetpack-err">
4430
	<div class="squeezer">
4431
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4432
		<p><?php
4433
			echo wp_kses(
4434
				wptexturize(
4435
					wp_sprintf(
4436
						_nx(
4437
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4438
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4439
							count( $privacy_checks ),
4440
							'%l = list of Jetpack module/feature names',
4441
							'jetpack'
4442
						),
4443
						$module_names
4444
					)
4445
				),
4446
				array( 'strong' => true )
4447
			);
4448
4449
			echo "\n<br />\n";
4450
4451
			echo wp_kses(
4452
				sprintf(
4453
					_nx(
4454
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4455
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4456
						count( $privacy_checks ),
4457
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4458
						'jetpack'
4459
					),
4460
					wp_nonce_url(
4461
						Jetpack::admin_url(
4462
							array(
4463
								'page'   => 'jetpack',
4464
								'action' => 'deactivate',
4465
								'module' => urlencode( $module_slugs ),
4466
							)
4467
						),
4468
						"jetpack_deactivate-$module_slugs"
4469
					),
4470
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4471
				),
4472
				array( 'a' => array( 'href' => true, 'title' => true ) )
4473
			);
4474
		?></p>
4475
	</div>
4476
</div>
4477
<?php endif;
4478
	// only display the notice if the other stuff is not there
4479
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4480
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4481
			$this->opt_in_jetpack_manage_notice();
4482
		}
4483
	}
4484
4485
	/**
4486
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4487
	 */
4488
	function stat( $group, $detail ) {
4489
		if ( ! isset( $this->stats[ $group ] ) )
4490
			$this->stats[ $group ] = array();
4491
		$this->stats[ $group ][] = $detail;
4492
	}
4493
4494
	/**
4495
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4496
	 */
4497
	function do_stats( $method = '' ) {
4498
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4499
			foreach ( $this->stats as $group => $stats ) {
4500
				if ( is_array( $stats ) && count( $stats ) ) {
4501
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4502
					if ( 'server_side' === $method ) {
4503
						self::do_server_side_stat( $args );
4504
					} else {
4505
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4506
					}
4507
				}
4508
				unset( $this->stats[ $group ] );
4509
			}
4510
		}
4511
	}
4512
4513
	/**
4514
	 * Runs stats code for a one-off, server-side.
4515
	 *
4516
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4517
	 *
4518
	 * @return bool If it worked.
4519
	 */
4520
	static function do_server_side_stat( $args ) {
4521
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4522
		if ( is_wp_error( $response ) )
4523
			return false;
4524
4525
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4526
			return false;
4527
4528
		return true;
4529
	}
4530
4531
	/**
4532
	 * Builds the stats url.
4533
	 *
4534
	 * @param $args array|string The arguments to append to the URL.
4535
	 *
4536
	 * @return string The URL to be pinged.
4537
	 */
4538
	static function build_stats_url( $args ) {
4539
		$defaults = array(
4540
			'v'    => 'wpcom2',
4541
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4542
		);
4543
		$args     = wp_parse_args( $args, $defaults );
4544
		/**
4545
		 * Filter the URL used as the Stats tracking pixel.
4546
		 *
4547
		 * @since 2.3.2
4548
		 *
4549
		 * @param string $url Base URL used as the Stats tracking pixel.
4550
		 */
4551
		$base_url = apply_filters(
4552
			'jetpack_stats_base_url',
4553
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4554
		);
4555
		$url      = add_query_arg( $args, $base_url );
4556
		return $url;
4557
	}
4558
4559
	function translate_current_user_to_role() {
4560
		foreach ( $this->capability_translations as $role => $cap ) {
4561
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4562
				return $role;
4563
			}
4564
		}
4565
4566
		return false;
4567
	}
4568
4569
	function translate_role_to_cap( $role ) {
4570
		if ( ! isset( $this->capability_translations[$role] ) ) {
4571
			return false;
4572
		}
4573
4574
		return $this->capability_translations[$role];
4575
	}
4576
4577
	function sign_role( $role ) {
4578
		if ( ! $user_id = (int) get_current_user_id() ) {
4579
			return false;
4580
		}
4581
4582
		$token = Jetpack_Data::get_access_token();
4583
		if ( ! $token || is_wp_error( $token ) ) {
4584
			return false;
4585
		}
4586
4587
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4588
	}
4589
4590
4591
	/**
4592
	 * Builds a URL to the Jetpack connection auth page
4593
	 *
4594
	 * @since 3.9.5
4595
	 *
4596
	 * @param bool $raw If true, URL will not be escaped.
4597
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4598
	 *                              If string, will be a custom redirect.
4599
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4600
	 *
4601
	 * @return string Connect URL
4602
	 */
4603
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4604
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4605
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4606
			if( is_network_admin() ) {
4607
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4608
			    'admin.php?page=jetpack-settings' ), $url );
4609
			}
4610
		} else {
4611
			$role = $this->translate_current_user_to_role();
4612
			$signed_role = $this->sign_role( $role );
4613
4614
			$user = wp_get_current_user();
4615
4616
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( menu_page_url( 'jetpack', false ) );
4617
4618
			if( isset( $_REQUEST['is_multisite'] ) ) {
4619
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4620
			}
4621
4622
			$secrets = Jetpack::init()->generate_secrets();
4623
			Jetpack_Options::update_option( 'authorize', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] . ':' . $secrets[3] );
4624
4625
			@list( $secret ) = explode( ':', Jetpack_Options::get_option( 'authorize' ) );
4626
4627
			$args = urlencode_deep(
4628
				array(
4629
					'response_type' => 'code',
4630
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4631
					'redirect_uri'  => add_query_arg(
4632
						array(
4633
							'action'   => 'authorize',
4634
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4635
							'redirect' => urlencode( $redirect ),
4636
						),
4637
						menu_page_url( 'jetpack', false )
4638
					),
4639
					'state'         => $user->ID,
4640
					'scope'         => $signed_role,
4641
					'user_email'    => $user->user_email,
4642
					'user_login'    => $user->user_login,
4643
					'is_active'     => Jetpack::is_active(),
4644
					'jp_version'    => JETPACK__VERSION,
4645
					'auth_type'     => 'calypso',
4646
					'secret'		=> $secret,
4647
				)
4648
			);
4649
4650
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4651
		}
4652
4653
		if ( $from ) {
4654
			$url = add_query_arg( 'from', $from, $url );
4655
		}
4656
		return $raw ? $url : esc_url( $url );
4657
	}
4658
4659
	function build_reconnect_url( $raw = false ) {
4660
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4661
		return $raw ? $url : esc_url( $url );
4662
	}
4663
4664
	public static function admin_url( $args = null ) {
4665
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4666
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4667
		return $url;
4668
	}
4669
4670
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4671
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4672
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4673
	}
4674
4675
	function dismiss_jetpack_notice() {
4676
4677
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4678
			return;
4679
		}
4680
4681
		switch( $_GET['jetpack-notice'] ) {
4682
			case 'dismiss':
4683
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4684
4685
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4686
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4687
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4688
				}
4689
				break;
4690 View Code Duplication
			case 'jetpack-manage-opt-out':
4691
4692
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4693
					// Don't show the banner again
4694
4695
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4696
					// redirect back to the page that had the notice
4697
					if ( wp_get_referer() ) {
4698
						wp_safe_redirect( wp_get_referer() );
4699
					} else {
4700
						// Take me to Jetpack
4701
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4702
					}
4703
				}
4704
				break;
4705 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4706
4707
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4708
					// Don't show the banner again
4709
4710
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4711
					// redirect back to the page that had the notice
4712
					if ( wp_get_referer() ) {
4713
						wp_safe_redirect( wp_get_referer() );
4714
					} else {
4715
						// Take me to Jetpack
4716
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4717
					}
4718
				}
4719
				break;
4720
			case 'jetpack-manage-opt-in':
4721
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4722
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4723
4724
					$redirection_url = Jetpack::admin_url();
4725
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4726
4727
					// Don't redirect form the Jetpack Setting Page
4728
					$referer_parsed = parse_url ( wp_get_referer() );
4729
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4730
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4731
						// Take the user to Jetpack home except when on the setting page
4732
						$redirection_url = wp_get_referer();
4733
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4734
					}
4735
					// Also update the JSON API FULL MANAGEMENT Option
4736
					Jetpack::activate_module( 'manage', false, false );
4737
4738
					// Special Message when option in.
4739
					Jetpack::state( 'optin-manage', 'true' );
4740
					// Activate the Module if not activated already
4741
4742
					// Redirect properly
4743
					wp_safe_redirect( $redirection_url );
4744
4745
				}
4746
				break;
4747
		}
4748
	}
4749
4750
	function debugger_page() {
4751
		nocache_headers();
4752
		if ( ! current_user_can( 'manage_options' ) ) {
4753
			die( '-1' );
4754
		}
4755
		Jetpack_Debugger::jetpack_debug_display_handler();
4756
		exit;
4757
	}
4758
4759
	public static function admin_screen_configure_module( $module_id ) {
4760
4761
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4762
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4763
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4764
				/**
4765
				 * Fires to diplay a custom module activation screen.
4766
				 *
4767
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4768
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4769
				 *
4770
				 * @module manage
4771
				 *
4772
				 * @since 3.8.0
4773
				 *
4774
				 * @param int $module_id Module ID.
4775
				 */
4776
				do_action( 'display_activate_module_setting_' . $module_id );
4777
			} else {
4778
				self::display_activate_module_link( $module_id );
4779
			}
4780
4781
			return false;
4782
		} ?>
4783
4784
		<div id="jp-settings-screen" style="position: relative">
4785
			<h3>
4786
			<?php
4787
				$module = Jetpack::get_module( $module_id );
4788
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4789
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4790
			?>
4791
			</h3>
4792
			<?php
4793
				/**
4794
				 * Fires within the displayed message when a feature configuation is updated.
4795
				 *
4796
				 * @since 3.4.0
4797
				 *
4798
				 * @param int $module_id Module ID.
4799
				 */
4800
				do_action( 'jetpack_notices_update_settings', $module_id );
4801
				/**
4802
				 * Fires when a feature configuation screen is loaded.
4803
				 * The dynamic part of the hook, $module_id, is the module ID.
4804
				 *
4805
				 * @since 1.1.0
4806
				 */
4807
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4808
			?>
4809
		</div><?php
4810
	}
4811
4812
	/**
4813
	 * Display link to activate the module to see the settings screen.
4814
	 * @param  string $module_id
4815
	 * @return null
4816
	 */
4817
	public static function display_activate_module_link( $module_id ) {
4818
4819
		$info =  Jetpack::get_module( $module_id );
4820
		$extra = '';
4821
		$activate_url = wp_nonce_url(
4822
				Jetpack::admin_url(
4823
					array(
4824
						'page'   => 'jetpack',
4825
						'action' => 'activate',
4826
						'module' => $module_id,
4827
					)
4828
				),
4829
				"jetpack_activate-$module_id"
4830
			);
4831
4832
		?>
4833
4834
		<div class="wrap configure-module">
4835
			<div id="jp-settings-screen">
4836
				<?php
4837
				if ( $module_id == 'json-api' ) {
4838
4839
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4840
4841
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4842
4843
					$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' ), 'http://jetpack.com/support/site-management' );
4844
4845
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4846
				} ?>
4847
4848
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4849
				<div class="narrow">
4850
					<p><?php echo  $info['description']; ?></p>
4851
					<?php if( $extra ) { ?>
4852
					<p><?php echo esc_html( $extra ); ?></p>
4853
					<?php } ?>
4854
					<p>
4855
						<?php
4856
						if( wp_get_referer() ) {
4857
							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() );
4858
						} else {
4859
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4860
						} ?>
4861
					</p>
4862
				</div>
4863
4864
			</div>
4865
		</div>
4866
4867
		<?php
4868
	}
4869
4870
	public static function sort_modules( $a, $b ) {
4871
		if ( $a['sort'] == $b['sort'] )
4872
			return 0;
4873
4874
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4875
	}
4876
4877 View Code Duplication
	function sync_reindex_trigger() {
4878
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4879
			echo json_encode( $this->sync->reindex_trigger() );
4880
		} else {
4881
			echo '{"status":"ERROR"}';
4882
		}
4883
		exit;
4884
	}
4885
4886 View Code Duplication
	function sync_reindex_status(){
4887
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4888
			echo json_encode( $this->sync->reindex_status() );
4889
		} else {
4890
			echo '{"status":"ERROR"}';
4891
		}
4892
		exit;
4893
	}
4894
4895
/* Client API */
4896
4897
	/**
4898
	 * Returns the requested Jetpack API URL
4899
	 *
4900
	 * @return string
4901
	 */
4902
	public static function api_url( $relative_url ) {
4903
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4904
	}
4905
4906
	/**
4907
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4908
	 */
4909
	public static function fix_url_for_bad_hosts( $url ) {
4910
		if ( 0 !== strpos( $url, 'https://' ) ) {
4911
			return $url;
4912
		}
4913
4914
		switch ( JETPACK_CLIENT__HTTPS ) {
4915
			case 'ALWAYS' :
4916
				return $url;
4917
			case 'NEVER' :
4918
				return set_url_scheme( $url, 'http' );
4919
			// default : case 'AUTO' :
4920
		}
4921
4922
		// Yay! Your host is good!
4923
		if ( self::permit_ssl() && wp_http_supports( array( 'ssl' => true ) ) ) {
4924
			return $url;
4925
		}
4926
4927
		// Boo! Your host is bad and makes Jetpack cry!
4928
		return set_url_scheme( $url, 'http' );
4929
	}
4930
4931
	/**
4932
	 * Checks to see if the URL is using SSL to connect with Jetpack
4933
	 *
4934
	 * @since 2.3.3
4935
	 * @return boolean
4936
	 */
4937
	public static function permit_ssl( $force_recheck = false ) {
4938
		// Do some fancy tests to see if ssl is being supported
4939
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4940
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4941
				$ssl = 0;
4942
			} else {
4943
				switch ( JETPACK_CLIENT__HTTPS ) {
4944
					case 'NEVER':
4945
						$ssl = 0;
4946
						break;
4947
					case 'ALWAYS':
4948
					case 'AUTO':
4949
					default:
4950
						$ssl = 1;
4951
						break;
4952
				}
4953
4954
				// If it's not 'NEVER', test to see
4955
				if ( $ssl ) {
4956
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4957
					if ( is_wp_error( $response ) || ( 'OK' !== wp_remote_retrieve_body( $response ) ) ) {
4958
						$ssl = 0;
4959
					}
4960
				}
4961
			}
4962
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4963
		}
4964
4965
		return (bool) $ssl;
4966
	}
4967
4968
	/*
4969
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'ALWAYS' but SSL isn't working.
4970
	 */
4971
	public function alert_required_ssl_fail() {
4972
		if ( ! current_user_can( 'manage_options' ) )
4973
			return;
4974
		?>
4975
4976
		<div id="message" class="error jetpack-message jp-identity-crisis">
4977
			<div class="jp-banner__content">
4978
				<h2><?php _e( 'Something is being cranky!', 'jetpack' ); ?></h2>
4979
				<p><?php _e( 'Your site is configured to only permit SSL connections to Jetpack, but SSL connections don\'t seem to be functional!', 'jetpack' ); ?></p>
4980
			</div>
4981
		</div>
4982
4983
		<?php
4984
	}
4985
4986
	/**
4987
	 * Returns the Jetpack XML-RPC API
4988
	 *
4989
	 * @return string
4990
	 */
4991
	public static function xmlrpc_api_url() {
4992
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4993
		return untrailingslashit( $base ) . '/xmlrpc.php';
4994
	}
4995
4996
	/**
4997
	 * Creates two secret tokens and the end of life timestamp for them.
4998
	 *
4999
	 * Note these tokens are unique per call, NOT static per site for connecting.
5000
	 *
5001
	 * @since 2.6
5002
	 * @return array
5003
	 */
5004
	public function generate_secrets() {
5005
	    $secrets = array(
5006
			wp_generate_password( 32, false ), // secret_1
5007
			wp_generate_password( 32, false ), // secret_2
5008
			( time() + 600 ), // eol ( End of Life )
5009
			get_current_user_id(), // ties the secrets to the current user
5010
	    );
5011
5012
	    return $secrets;
5013
	}
5014
5015
	/**
5016
	 * Builds the timeout limit for queries talking with the wpcom servers.
5017
	 *
5018
	 * Based on local php max_execution_time in php.ini
5019
	 *
5020
	 * @since 2.6
5021
	 * @return int
5022
	 **/
5023
	public function get_remote_query_timeout_limit() {
5024
	    $timeout = (int) ini_get( 'max_execution_time' );
5025
	    if ( ! $timeout ) // Ensure exec time set in php.ini
5026
		$timeout = 30;
5027
	    return intval( $timeout / 2 );
5028
	}
5029
5030
5031
	/**
5032
	 * Takes the response from the Jetpack register new site endpoint and
5033
	 * verifies it worked properly.
5034
	 *
5035
	 * @since 2.6
5036
	 * @return true or Jetpack_Error
5037
	 **/
5038
	public function validate_remote_register_response( $response ) {
5039
	    	if ( is_wp_error( $response ) ) {
5040
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5041
		}
5042
5043
		$code   = wp_remote_retrieve_response_code( $response );
5044
		$entity = wp_remote_retrieve_body( $response );
5045
		if ( $entity )
5046
			$json = json_decode( $entity );
5047
		else
5048
			$json = false;
5049
5050
		$code_type = intval( $code / 100 );
5051
		if ( 5 == $code_type ) {
5052
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5053
		} elseif ( 408 == $code ) {
5054
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5055
		} elseif ( ! empty( $json->error ) ) {
5056
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
5057
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
5058
		} elseif ( 200 != $code ) {
5059
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5060
		}
5061
5062
		// Jetpack ID error block
5063
		if ( empty( $json->jetpack_id ) ) {
5064
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5065
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
5066
			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 );
5067
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
5068
			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 );
5069
		}
5070
5071
	    return true;
5072
	}
5073
	/**
5074
	 * @return bool|WP_Error
5075
	 */
5076
	public static function register() {
5077
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5078
		$secrets = Jetpack::init()->generate_secrets();
5079
5080
		Jetpack_Options::update_option( 'register', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] . ':' . $secrets[3] );
5081
5082
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack_Options::get_option( 'register' ) );
5083
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
5084
			return new Jetpack_Error( 'missing_secrets' );
5085
		}
5086
5087
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
5088
5089
		$gmt_offset = get_option( 'gmt_offset' );
5090
		if ( ! $gmt_offset ) {
5091
			$gmt_offset = 0;
5092
		}
5093
5094
		$stats_options = get_option( 'stats_options' );
5095
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5096
5097
		$args = array(
5098
			'method'  => 'POST',
5099
			'body'    => array(
5100
				'siteurl'         => site_url(),
5101
				'home'            => home_url(),
5102
				'gmt_offset'      => $gmt_offset,
5103
				'timezone_string' => (string) get_option( 'timezone_string' ),
5104
				'site_name'       => (string) get_option( 'blogname' ),
5105
				'secret_1'        => $secret_1,
5106
				'secret_2'        => $secret_2,
5107
				'site_lang'       => get_locale(),
5108
				'timeout'         => $timeout,
5109
				'stats_id'        => $stats_id,
5110
				'state'           => get_current_user_id(),
5111
			),
5112
			'headers' => array(
5113
				'Accept' => 'application/json',
5114
			),
5115
			'timeout' => $timeout,
5116
		);
5117
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5118
5119
5120
		// Make sure the response is valid and does not contain any Jetpack errors
5121
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
5122
		if( is_wp_error( $valid_response ) || !$valid_response ) {
5123
		    return $valid_response;
5124
		}
5125
5126
		// Grab the response values to work with
5127
		$code   = wp_remote_retrieve_response_code( $response );
5128
		$entity = wp_remote_retrieve_body( $response );
5129
5130
		if ( $entity )
5131
			$json = json_decode( $entity );
5132
		else
5133
			$json = false;
5134
5135 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
5136
			return new Jetpack_Error( 'jetpack_secret', '', $code );
5137
5138
		if ( isset( $json->jetpack_public ) ) {
5139
			$jetpack_public = (int) $json->jetpack_public;
5140
		} else {
5141
			$jetpack_public = false;
5142
		}
5143
5144
		Jetpack_Options::update_options(
5145
			array(
5146
				'id'         => (int)    $json->jetpack_id,
5147
				'blog_token' => (string) $json->jetpack_secret,
5148
				'public'     => $jetpack_public,
5149
			)
5150
		);
5151
5152
		/**
5153
		 * Fires when a site is registered on WordPress.com.
5154
		 *
5155
		 * @since 3.7.0
5156
		 *
5157
		 * @param int $json->jetpack_id Jetpack Blog ID.
5158
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5159
		 * @param int|bool $jetpack_public Is the site public.
5160
		 */
5161
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
5162
5163
		// Initialize Jump Start for the first and only time.
5164
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5165
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5166
5167
			$jetpack = Jetpack::init();
5168
5169
			$jetpack->stat( 'jumpstart', 'unique-views' );
5170
			$jetpack->do_stats( 'server_side' );
5171
		};
5172
5173
		return true;
5174
	}
5175
5176
	/**
5177
	 * If the db version is showing something other that what we've got now, bump it to current.
5178
	 *
5179
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5180
	 */
5181
	public static function maybe_set_version_option() {
5182
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5183
		if ( JETPACK__VERSION != $version ) {
5184
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5185
			return true;
5186
		}
5187
		return false;
5188
	}
5189
5190
/* Client Server API */
5191
5192
	/**
5193
	 * Loads the Jetpack XML-RPC client
5194
	 */
5195
	public static function load_xml_rpc_client() {
5196
		require_once ABSPATH . WPINC . '/class-IXR.php';
5197
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5198
	}
5199
5200
	function verify_xml_rpc_signature() {
5201
		if ( $this->xmlrpc_verification ) {
5202
			return $this->xmlrpc_verification;
5203
		}
5204
5205
		// It's not for us
5206
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5207
			return false;
5208
		}
5209
5210
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5211
		if (
5212
			empty( $token_key )
5213
		||
5214
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5215
		) {
5216
			return false;
5217
		}
5218
5219
		if ( '0' === $user_id ) {
5220
			$token_type = 'blog';
5221
			$user_id = 0;
5222
		} else {
5223
			$token_type = 'user';
5224
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5225
				return false;
5226
			}
5227
			$user_id = (int) $user_id;
5228
5229
			$user = new WP_User( $user_id );
5230
			if ( ! $user || ! $user->exists() ) {
5231
				return false;
5232
			}
5233
		}
5234
5235
		$token = Jetpack_Data::get_access_token( $user_id );
5236
		if ( ! $token ) {
5237
			return false;
5238
		}
5239
5240
		$token_check = "$token_key.";
5241
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5242
			return false;
5243
		}
5244
5245
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5246
5247
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5248
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5249
			$post_data   = $_POST;
5250
			$file_hashes = array();
5251
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5252
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5253
					continue;
5254
				}
5255
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5256
				$file_hashes[$post_data_key] = $post_data_value;
5257
			}
5258
5259
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5260
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5261
				$post_data[$post_data_key] = $post_data_value;
5262
			}
5263
5264
			ksort( $post_data );
5265
5266
			$body = http_build_query( stripslashes_deep( $post_data ) );
5267
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5268
			$body = file_get_contents( 'php://input' );
5269
		} else {
5270
			$body = null;
5271
		}
5272
		$signature = $jetpack_signature->sign_current_request(
5273
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5274
		);
5275
5276
		if ( ! $signature ) {
5277
			return false;
5278
		} else if ( is_wp_error( $signature ) ) {
5279
			return $signature;
5280
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5281
			return false;
5282
		}
5283
5284
		$timestamp = (int) $_GET['timestamp'];
5285
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5286
5287
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5288
			return false;
5289
		}
5290
5291
		$this->xmlrpc_verification = array(
5292
			'type'    => $token_type,
5293
			'user_id' => $token->external_user_id,
5294
		);
5295
5296
		return $this->xmlrpc_verification;
5297
	}
5298
5299
	/**
5300
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5301
	 */
5302
	function authenticate_jetpack( $user, $username, $password ) {
5303
		if ( is_a( $user, 'WP_User' ) ) {
5304
			return $user;
5305
		}
5306
5307
		$token_details = $this->verify_xml_rpc_signature();
5308
5309
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5310
			return $user;
5311
		}
5312
5313
		if ( 'user' !== $token_details['type'] ) {
5314
			return $user;
5315
		}
5316
5317
		if ( ! $token_details['user_id'] ) {
5318
			return $user;
5319
		}
5320
5321
		nocache_headers();
5322
5323
		return new WP_User( $token_details['user_id'] );
5324
	}
5325
5326
	function add_nonce( $timestamp, $nonce ) {
5327
		global $wpdb;
5328
		static $nonces_used_this_request = array();
5329
5330
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5331
			return $nonces_used_this_request["$timestamp:$nonce"];
5332
		}
5333
5334
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5335
		$timestamp = (int) $timestamp;
5336
		$nonce     = esc_sql( $nonce );
5337
5338
		// Raw query so we can avoid races: add_option will also update
5339
		$show_errors = $wpdb->show_errors( false );
5340
5341
		$old_nonce = $wpdb->get_row(
5342
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5343
		);
5344
5345
		if ( is_null( $old_nonce ) ) {
5346
			$return = $wpdb->query(
5347
				$wpdb->prepare(
5348
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5349
					"jetpack_nonce_{$timestamp}_{$nonce}",
5350
					time(),
5351
					'no'
5352
				)
5353
			);
5354
		} else {
5355
			$return = false;
5356
		}
5357
5358
		$wpdb->show_errors( $show_errors );
5359
5360
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5361
5362
		return $return;
5363
	}
5364
5365
	/**
5366
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5367
	 * Capture it here so we can verify the signature later.
5368
	 */
5369
	function xmlrpc_methods( $methods ) {
5370
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5371
		return $methods;
5372
	}
5373
5374
	function public_xmlrpc_methods( $methods ) {
5375
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5376
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5377
		}
5378
		return $methods;
5379
	}
5380
5381
	function jetpack_getOptions( $args ) {
5382
		global $wp_xmlrpc_server;
5383
5384
		$wp_xmlrpc_server->escape( $args );
5385
5386
		$username	= $args[1];
5387
		$password	= $args[2];
5388
5389
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5390
			return $wp_xmlrpc_server->error;
5391
		}
5392
5393
		$options = array();
5394
		$user_data = $this->get_connected_user_data();
5395
		if ( is_array( $user_data ) ) {
5396
			$options['jetpack_user_id'] = array(
5397
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5398
				'readonly'      => true,
5399
				'value'         => $user_data['ID'],
5400
			);
5401
			$options['jetpack_user_login'] = array(
5402
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5403
				'readonly'      => true,
5404
				'value'         => $user_data['login'],
5405
			);
5406
			$options['jetpack_user_email'] = array(
5407
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5408
				'readonly'      => true,
5409
				'value'         => $user_data['email'],
5410
			);
5411
			$options['jetpack_user_site_count'] = array(
5412
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5413
				'readonly'      => true,
5414
				'value'         => $user_data['site_count'],
5415
			);
5416
		}
5417
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5418
		$args = stripslashes_deep( $args );
5419
		return $wp_xmlrpc_server->wp_getOptions( $args );
5420
	}
5421
5422
	function xmlrpc_options( $options ) {
5423
		$jetpack_client_id = false;
5424
		if ( self::is_active() ) {
5425
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5426
		}
5427
		$options['jetpack_version'] = array(
5428
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5429
				'readonly'      => true,
5430
				'value'         => JETPACK__VERSION,
5431
		);
5432
5433
		$options['jetpack_client_id'] = array(
5434
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5435
				'readonly'      => true,
5436
				'value'         => $jetpack_client_id,
5437
		);
5438
		return $options;
5439
	}
5440
5441
	public static function clean_nonces( $all = false ) {
5442
		global $wpdb;
5443
5444
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5445
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
5446
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5447
		} else {
5448
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
5449
		}
5450
5451
		if ( true !== $all ) {
5452
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5453
			$sql_args[] = time() - 3600;
5454
		}
5455
5456
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5457
5458
		$sql = $wpdb->prepare( $sql, $sql_args );
5459
5460
		for ( $i = 0; $i < 1000; $i++ ) {
5461
			if ( ! $wpdb->query( $sql ) ) {
5462
				break;
5463
			}
5464
		}
5465
	}
5466
5467
	/**
5468
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5469
	 * SET: state( $key, $value );
5470
	 * GET: $value = state( $key );
5471
	 *
5472
	 * @param string $key
5473
	 * @param string $value
5474
	 * @param bool $restate private
5475
	 */
5476
	public static function state( $key = null, $value = null, $restate = false ) {
5477
		static $state = array();
5478
		static $path, $domain;
5479
		if ( ! isset( $path ) ) {
5480
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5481
			$admin_url = Jetpack::admin_url();
5482
			$bits      = parse_url( $admin_url );
5483
5484
			if ( is_array( $bits ) ) {
5485
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5486
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5487
			} else {
5488
				$path = $domain = null;
5489
			}
5490
		}
5491
5492
		// Extract state from cookies and delete cookies
5493
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5494
			$yum = $_COOKIE[ 'jetpackState' ];
5495
			unset( $_COOKIE[ 'jetpackState' ] );
5496
			foreach ( $yum as $k => $v ) {
5497
				if ( strlen( $v ) )
5498
					$state[ $k ] = $v;
5499
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5500
			}
5501
		}
5502
5503
		if ( $restate ) {
5504
			foreach ( $state as $k => $v ) {
5505
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5506
			}
5507
			return;
5508
		}
5509
5510
		// Get a state variable
5511
		if ( isset( $key ) && ! isset( $value ) ) {
5512
			if ( array_key_exists( $key, $state ) )
5513
				return $state[ $key ];
5514
			return null;
5515
		}
5516
5517
		// Set a state variable
5518
		if ( isset ( $key ) && isset( $value ) ) {
5519
			if( is_array( $value ) && isset( $value[0] ) ) {
5520
				$value = $value[0];
5521
			}
5522
			$state[ $key ] = $value;
5523
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5524
		}
5525
	}
5526
5527
	public static function restate() {
5528
		Jetpack::state( null, null, true );
5529
	}
5530
5531
	public static function check_privacy( $file ) {
5532
		static $is_site_publicly_accessible = null;
5533
5534
		if ( is_null( $is_site_publicly_accessible ) ) {
5535
			$is_site_publicly_accessible = false;
5536
5537
			Jetpack::load_xml_rpc_client();
5538
			$rpc = new Jetpack_IXR_Client();
5539
5540
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5541
			if ( $success ) {
5542
				$response = $rpc->getResponse();
5543
				if ( $response ) {
5544
					$is_site_publicly_accessible = true;
5545
				}
5546
			}
5547
5548
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5549
		}
5550
5551
		if ( $is_site_publicly_accessible ) {
5552
			return;
5553
		}
5554
5555
		$module_slug = self::get_module_slug( $file );
5556
5557
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5558
		if ( ! $privacy_checks ) {
5559
			$privacy_checks = $module_slug;
5560
		} else {
5561
			$privacy_checks .= ",$module_slug";
5562
		}
5563
5564
		Jetpack::state( 'privacy_checks', $privacy_checks );
5565
	}
5566
5567
	/**
5568
	 * Helper method for multicall XMLRPC.
5569
	 */
5570
	public static function xmlrpc_async_call() {
5571
		global $blog_id;
5572
		static $clients = array();
5573
5574
		$client_blog_id = is_multisite() ? $blog_id : 0;
5575
5576
		if ( ! isset( $clients[$client_blog_id] ) ) {
5577
			Jetpack::load_xml_rpc_client();
5578
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5579
			if ( function_exists( 'ignore_user_abort' ) ) {
5580
				ignore_user_abort( true );
5581
			}
5582
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5583
		}
5584
5585
		$args = func_get_args();
5586
5587
		if ( ! empty( $args[0] ) ) {
5588
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5589
		} elseif ( is_multisite() ) {
5590
			foreach ( $clients as $client_blog_id => $client ) {
5591
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5592
					continue;
5593
				}
5594
5595
				$switch_success = switch_to_blog( $client_blog_id, true );
5596
				if ( ! $switch_success ) {
5597
					continue;
5598
				}
5599
5600
				flush();
5601
				$client->query();
5602
5603
				restore_current_blog();
5604
			}
5605
		} else {
5606
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5607
				flush();
5608
				$clients[0]->query();
5609
			}
5610
		}
5611
	}
5612
5613
	public static function staticize_subdomain( $url ) {
5614
5615
		// Extract hostname from URL
5616
		$host = parse_url( $url, PHP_URL_HOST );
5617
5618
		// Explode hostname on '.'
5619
		$exploded_host = explode( '.', $host );
5620
5621
		// Retrieve the name and TLD
5622
		if ( count( $exploded_host ) > 1 ) {
5623
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5624
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5625
			// Rebuild domain excluding subdomains
5626
			$domain = $name . '.' . $tld;
5627
		} else {
5628
			$domain = $host;
5629
		}
5630
		// Array of Automattic domains
5631
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5632
5633
		// Return $url if not an Automattic domain
5634
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5635
			return $url;
5636
		}
5637
5638
		if ( is_ssl() ) {
5639
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5640
		}
5641
5642
		srand( crc32( basename( $url ) ) );
5643
		$static_counter = rand( 0, 2 );
5644
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5645
5646
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5647
	}
5648
5649
/* JSON API Authorization */
5650
5651
	/**
5652
	 * Handles the login action for Authorizing the JSON API
5653
	 */
5654
	function login_form_json_api_authorization() {
5655
		$this->verify_json_api_authorization_request();
5656
5657
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5658
5659
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5660
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5661
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5662
	}
5663
5664
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5665
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5666
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5667
			return $url;
5668
		}
5669
5670
		$parsed_url = parse_url( $url );
5671
		$url = strtok( $url, '?' );
5672
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5673
		if ( ! empty( $parsed_url['query'] ) )
5674
			$url .= "&{$parsed_url['query']}";
5675
5676
		return $url;
5677
	}
5678
5679
	// Make sure the POSTed request is handled by the same action
5680
	function preserve_action_in_login_form_for_json_api_authorization() {
5681
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5682
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5683
	}
5684
5685
	// If someone logs in to approve API access, store the Access Code in usermeta
5686
	function store_json_api_authorization_token( $user_login, $user ) {
5687
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5688
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5689
		$token = wp_generate_password( 32, false );
5690
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5691
	}
5692
5693
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5694
	function allow_wpcom_public_api_domain( $domains ) {
5695
		$domains[] = 'public-api.wordpress.com';
5696
		return $domains;
5697
	}
5698
5699
	// Add the Access Code details to the public-api.wordpress.com redirect
5700
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5701
		return add_query_arg(
5702
			urlencode_deep(
5703
				array(
5704
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5705
					'jetpack-user-id' => (int) $user->ID,
5706
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5707
				)
5708
			),
5709
			$redirect_to
5710
		);
5711
	}
5712
5713
	// Verifies the request by checking the signature
5714
	function verify_json_api_authorization_request() {
5715
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5716
5717
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5718
		if ( ! $token || empty( $token->secret ) ) {
5719
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5720
		}
5721
5722
		$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' );
5723
5724
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5725
5726
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5727
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5728
		} else {
5729
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5730
		}
5731
5732
		if ( ! $signature ) {
5733
			wp_die( $die_error );
5734
		} else if ( is_wp_error( $signature ) ) {
5735
			wp_die( $die_error );
5736
		} else if ( $signature !== $_GET['signature'] ) {
5737
			if ( is_ssl() ) {
5738
				// 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
5739
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5740
				if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5741
					wp_die( $die_error );
5742
				}
5743
			} else {
5744
				wp_die( $die_error );
5745
			}
5746
		}
5747
5748
		$timestamp = (int) $_GET['timestamp'];
5749
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5750
5751
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5752
			// De-nonce the nonce, at least for 5 minutes.
5753
			// 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)
5754
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5755
			if ( $old_nonce_time < time() - 300 ) {
5756
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5757
			}
5758
		}
5759
5760
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5761
		$data_filters = array(
5762
			'state'        => 'opaque',
5763
			'client_id'    => 'int',
5764
			'client_title' => 'string',
5765
			'client_image' => 'url',
5766
		);
5767
5768
		foreach ( $data_filters as $key => $sanitation ) {
5769
			if ( ! isset( $data->$key ) ) {
5770
				wp_die( $die_error );
5771
			}
5772
5773
			switch ( $sanitation ) {
5774
			case 'int' :
5775
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5776
				break;
5777
			case 'opaque' :
5778
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5779
				break;
5780
			case 'string' :
5781
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5782
				break;
5783
			case 'url' :
5784
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5785
				break;
5786
			}
5787
		}
5788
5789
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5790
			wp_die( $die_error );
5791
		}
5792
	}
5793
5794
	function login_message_json_api_authorization( $message ) {
5795
		return '<p class="message">' . sprintf(
5796
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5797
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5798
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5799
	}
5800
5801
	/**
5802
	 * Get $content_width, but with a <s>twist</s> filter.
5803
	 */
5804
	public static function get_content_width() {
5805
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5806
		/**
5807
		 * Filter the Content Width value.
5808
		 *
5809
		 * @since 2.2.3
5810
		 *
5811
		 * @param string $content_width Content Width value.
5812
		 */
5813
		return apply_filters( 'jetpack_content_width', $content_width );
5814
	}
5815
5816
	/**
5817
	 * Centralize the function here until it gets added to core.
5818
	 *
5819
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5820
	 * @param int $size Size of the avatar image
5821
	 * @param string $default URL to a default image to use if no avatar is available
5822
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5823
	 *
5824
	 * @return array First element is the URL, second is the class.
5825
	 */
5826
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5827
		// Don't bother adding the __return_true filter if it's already there.
5828
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5829
5830
		if ( $force_display && ! $has_filter )
5831
			add_filter( 'pre_option_show_avatars', '__return_true' );
5832
5833
		$avatar = get_avatar( $id_or_email, $size, $default );
5834
5835
		if ( $force_display && ! $has_filter )
5836
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5837
5838
		// If no data, fail out.
5839
		if ( is_wp_error( $avatar ) || ! $avatar )
5840
			return array( null, null );
5841
5842
		// Pull out the URL.  If it's not there, fail out.
5843
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5844
			return array( null, null );
5845
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5846
5847
		// Pull out the class, but it's not a big deal if it's missing.
5848
		$class = '';
5849
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5850
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5851
5852
		return array( $url, $class );
5853
	}
5854
5855
	/**
5856
	 * Pings the WordPress.com Mirror Site for the specified options.
5857
	 *
5858
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5859
	 *
5860
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5861
	 */
5862
	public function get_cloud_site_options( $option_names ) {
5863
		$option_names = array_filter( (array) $option_names, 'is_string' );
5864
5865
		Jetpack::load_xml_rpc_client();
5866
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5867
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5868
		if ( $xml->isError() ) {
5869
			return array(
5870
				'error_code' => $xml->getErrorCode(),
5871
				'error_msg'  => $xml->getErrorMessage(),
5872
			);
5873
		}
5874
		$cloud_site_options = $xml->getResponse();
5875
5876
		return $cloud_site_options;
5877
	}
5878
5879
	/**
5880
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5881
	 *
5882
	 * @return array An array of options to check.
5883
	 */
5884
	public static function identity_crisis_options_to_check() {
5885
		return array(
5886
			'siteurl',
5887
			'home',
5888
		);
5889
	}
5890
5891
	/**
5892
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5893
	 *
5894
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5895
	 *
5896
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5897
	 */
5898
	public static function check_identity_crisis( $force_recheck = false ) {
5899
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5900
			return false;
5901
5902
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5903
			$options_to_check = self::identity_crisis_options_to_check();
5904
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5905
			$errors        = array();
5906
5907
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5908
5909
				// If it's not the same as the local value...
5910
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5911
5912
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5913
					if ( 'error_code' == $cloud_key ) {
5914
						$errors[ $cloud_key ] = $cloud_value;
5915
						break;
5916
					}
5917
5918
					$parsed_cloud_value = parse_url( $cloud_value );
5919
					// If the current options is an IP address
5920
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5921
						// Give the new value a Jetpack to fly in to the clouds
5922
						Jetpack::resolve_identity_crisis( $cloud_key );
5923
						continue;
5924
					}
5925
5926
					// And it's not been added to the whitelist...
5927
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5928
						/*
5929
						 * This should be a temporary hack until a cleaner solution is found.
5930
						 *
5931
						 * The siteurl and home can be set to use http in General > Settings
5932
						 * however some constants can be defined that can force https in wp-admin
5933
						 * when this happens wpcom can confuse wporg with a fake identity
5934
						 * crisis with a mismatch of http vs https when it should be allowed.
5935
						 * we need to check that here.
5936
						 *
5937
						 * @see https://github.com/Automattic/jetpack/issues/1006
5938
						 */
5939
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5940
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5941
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5942
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5943
							continue;
5944
						}
5945
5946
5947
						// Then kick an error!
5948
						$errors[ $cloud_key ] = $cloud_value;
5949
					}
5950
				}
5951
			}
5952
		}
5953
5954
		/**
5955
		 * Filters the errors returned when checking for an Identity Crisis.
5956
		 *
5957
		 * @since 2.3.2
5958
		 *
5959
		 * @param array $errors Array of Identity Crisis errors.
5960
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5961
		 */
5962
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5963
	}
5964
5965
	/*
5966
	 * Resolve ID crisis
5967
	 *
5968
	 * If the URL has changed, but the rest of the options are the same (i.e. blog/user tokens)
5969
	 * The user has the option to update the shadow site with the new URL before a new
5970
	 * token is created.
5971
	 *
5972
	 * @param $key : Which option to sync.  null defautlts to home and siteurl
5973
	 */
5974
	public static function resolve_identity_crisis( $key = null ) {
5975
		if ( $key ) {
5976
			$identity_options = array( $key );
5977
		} else {
5978
			$identity_options = self::identity_crisis_options_to_check();
5979
		}
5980
5981
		if ( is_array( $identity_options ) ) {
5982
			foreach( $identity_options as $identity_option ) {
5983
				Jetpack_Sync::sync_options( __FILE__, $identity_option );
5984
5985
				/**
5986
				 * Fires when a shadow site option is updated.
5987
				 * These options are updated via the Identity Crisis UI.
5988
				 * $identity_option is the option that gets updated.
5989
				 *
5990
				 * @since 3.7.0
5991
				 */
5992
				do_action( "update_option_{$identity_option}" );
5993
			}
5994
		}
5995
	}
5996
5997
	/*
5998
	 * Whitelist URL
5999
	 *
6000
	 * Ignore the URL differences between the blog and the shadow site.
6001
	 */
6002
	public static function whitelist_current_url() {
6003
		$options_to_check = Jetpack::identity_crisis_options_to_check();
6004
		$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
6005
6006
		foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6007
			Jetpack::whitelist_identity_crisis_value( $cloud_key, $cloud_value );
6008
		}
6009
	}
6010
6011
	/*
6012
	 * Ajax callbacks for ID crisis resolutions
6013
	 *
6014
	 * Things that could happen here:
6015
	 *  - site_migrated : Update the URL on the shadow blog to match new domain
6016
	 *  - whitelist     : Ignore the URL difference
6017
	 *  - default       : Error message
6018
	 */
6019
	public static function resolve_identity_crisis_ajax_callback() {
6020
		check_ajax_referer( 'resolve-identity-crisis', 'ajax-nonce' );
6021
6022
		switch ( $_POST[ 'crisis_resolution_action' ] ) {
6023
			case 'site_migrated':
6024
				Jetpack::resolve_identity_crisis();
6025
				echo 'resolved';
6026
				break;
6027
6028
			case 'whitelist':
6029
				Jetpack::whitelist_current_url();
6030
				echo 'whitelisted';
6031
				break;
6032
6033
			case 'reset_connection':
6034
				// Delete the options first so it doesn't get confused which site to disconnect dotcom-side
6035
				Jetpack_Options::delete_option(
6036
					array(
6037
						'register',
6038
						'blog_token',
6039
						'user_token',
6040
						'user_tokens',
6041
						'master_user',
6042
						'time_diff',
6043
						'fallback_no_verify_ssl_certs',
6044
						'id',
6045
					)
6046
				);
6047
				delete_transient( 'jetpack_has_identity_crisis' );
6048
6049
				echo 'reset-connection-success';
6050
				break;
6051
6052
			default:
6053
				echo 'missing action';
6054
				break;
6055
		}
6056
6057
		wp_die();
6058
	}
6059
6060
	/**
6061
	 * Adds a value to the whitelist for the specified key.
6062
	 *
6063
	 * @param string $key The option name that we're whitelisting the value for.
6064
	 * @param string $value The value that we're intending to add to the whitelist.
6065
	 *
6066
	 * @return bool Whether the value was added to the whitelist, or false if it was already there.
6067
	 */
6068
	public static function whitelist_identity_crisis_value( $key, $value ) {
6069
		if ( Jetpack::is_identity_crisis_value_whitelisted( $key, $value ) ) {
6070
			return false;
6071
		}
6072
6073
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6074
		if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
6075
			$whitelist[ $key ] = array();
6076
		}
6077
		array_push( $whitelist[ $key ], $value );
6078
6079
		Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
6080
		return true;
6081
	}
6082
6083
	/**
6084
	 * Checks whether a value is already whitelisted.
6085
	 *
6086
	 * @param string $key The option name that we're checking the value for.
6087
	 * @param string $value The value that we're curious to see if it's on the whitelist.
6088
	 *
6089
	 * @return bool Whether the value is whitelisted.
6090
	 */
6091
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
6092
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6093
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
6094
			return true;
6095
		}
6096
		return false;
6097
	}
6098
6099
	/**
6100
	 * Checks whether the home and siteurl specifically are whitelisted
6101
	 * Written so that we don't have re-check $key and $value params every time
6102
	 * we want to check if this site is whitelisted, for example in footer.php
6103
	 *
6104
	 * @return bool True = already whitelsisted False = not whitelisted
6105
	 */
6106
	public static function is_staging_site() {
6107
		$is_staging = false;
6108
6109
		$current_whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist' );
6110
		if ( $current_whitelist ) {
6111
			$options_to_check  = Jetpack::identity_crisis_options_to_check();
6112
			$cloud_options     = Jetpack::init()->get_cloud_site_options( $options_to_check );
6113
6114
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6115
				if ( self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
6116
					$is_staging = true;
6117
					break;
6118
				}
6119
			}
6120
		}
6121
		$known_staging = array(
6122
			'urls' => array(
6123
				'#\.staging\.wpengine\.com$#i',
6124
				),
6125
			'constants' => array(
6126
				'IS_WPE_SNAPSHOT',
6127
				'JETPACK_STAGING_MODE',
6128
				)
6129
			);
6130
		/**
6131
		 * Filters the flags of known staging sites.
6132
		 *
6133
		 * @since 3.9.0
6134
		 *
6135
		 * @param array $known_staging {
6136
		 *     An array of arrays that each are used to check if the current site is staging.
6137
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6138
		 *     @type array $cosntants PHP constants of known staging/developement environments.
6139
		 *  }
6140
		 */
6141
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6142
6143
		if ( isset( $known_staging['urls'] ) ) {
6144
			foreach ( $known_staging['urls'] as $url ){
6145
				if ( preg_match( $url, site_url() ) ) {
6146
					$is_staging = true;
6147
					break;
6148
				}
6149
			}
6150
		}
6151
6152
		if ( isset( $known_staging['constants'] ) ) {
6153
			foreach ( $known_staging['constants'] as $constant ) {
6154
				if ( defined( $constant ) && constant( $constant ) ) {
6155
					$is_staging = true;
6156
				}
6157
			}
6158
		}
6159
6160
		/**
6161
		 * Filters is_staging_site check.
6162
		 *
6163
		 * @since 3.9.0
6164
		 *
6165
		 * @param bool $is_staging If the current site is a staging site.
6166
		 */
6167
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6168
	}
6169
6170
	public function identity_crisis_js( $nonce ) {
6171
?>
6172
<script>
6173
(function( $ ) {
6174
	var SECOND_IN_MS = 1000;
6175
6176
	function contactSupport( e ) {
6177
		e.preventDefault();
6178
		$( '.jp-id-crisis-question' ).hide();
6179
		$( '#jp-id-crisis-contact-support' ).show();
6180
	}
6181
6182
	function autodismissSuccessBanner() {
6183
		$( '.jp-identity-crisis' ).fadeOut(600); //.addClass( 'dismiss' );
6184
	}
6185
6186
	var data = { action: 'jetpack_resolve_identity_crisis', 'ajax-nonce': '<?php echo $nonce; ?>' };
6187
6188
	$( document ).ready(function() {
6189
6190
		// Site moved: Update the URL on the shadow blog
6191
		$( '.site-moved' ).click(function( e ) {
6192
			e.preventDefault();
6193
			data.crisis_resolution_action = 'site_migrated';
6194
			$( '#jp-id-crisis-question-1 .spinner' ).show();
6195
			$.post( ajaxurl, data, function() {
6196
				$( '.jp-id-crisis-question' ).hide();
6197
				$( '.banner-title' ).hide();
6198
				$( '#jp-id-crisis-success' ).show();
6199
				setTimeout( autodismissSuccessBanner, 6 * SECOND_IN_MS );
6200
			});
6201
6202
		});
6203
6204
		// URL hasn't changed, next question please.
6205
		$( '.site-not-moved' ).click(function( e ) {
6206
			e.preventDefault();
6207
			$( '.jp-id-crisis-question' ).hide();
6208
			$( '#jp-id-crisis-question-2' ).show();
6209
		});
6210
6211
		// Reset connection: two separate sites.
6212
		$( '.reset-connection' ).click(function( e ) {
6213
			data.crisis_resolution_action = 'reset_connection';
6214
			$.post( ajaxurl, data, function( response ) {
6215
				if ( 'reset-connection-success' === response ) {
6216
					window.location.replace( '<?php echo Jetpack::admin_url(); ?>' );
6217
				}
6218
			});
6219
		});
6220
6221
		// It's a dev environment.  Ignore.
6222
		$( '.is-dev-env' ).click(function( e ) {
6223
			data.crisis_resolution_action = 'whitelist';
6224
			$( '#jp-id-crisis-question-2 .spinner' ).show();
6225
			$.post( ajaxurl, data, function() {
6226
				$( '.jp-id-crisis-question' ).hide();
6227
				$( '.banner-title' ).hide();
6228
				$( '#jp-id-crisis-success' ).show();
6229
				setTimeout( autodismissSuccessBanner, 4 * SECOND_IN_MS );
6230
			});
6231
		});
6232
6233
		$( '.not-reconnecting' ).click(contactSupport);
6234
		$( '.not-staging-or-dev' ).click(contactSupport);
6235
	});
6236
})( jQuery );
6237
</script>
6238
<?php
6239
	}
6240
6241
	/**
6242
	 * Displays an admin_notice, alerting the user to an identity crisis.
6243
	 */
6244
	public function alert_identity_crisis() {
6245
		// @todo temporary killing of feature in 3.8.1 as it revealed a number of scenarios not foreseen.
6246
		if ( ! Jetpack::is_development_version() ) {
6247
			return;
6248
		}
6249
6250
		// @todo temporary copout for dealing with domain mapping
6251
		// @see https://github.com/Automattic/jetpack/issues/2702
6252
		if ( is_multisite() && defined( 'SUNRISE' ) && ! Jetpack::is_development_version() ) {
6253
			return;
6254
		}
6255
6256
		if ( ! current_user_can( 'jetpack_disconnect' ) ) {
6257
			return;
6258
		}
6259
6260
		if ( ! $errors = self::check_identity_crisis() ) {
6261
			return;
6262
		}
6263
6264
		// Only show on dashboard and jetpack pages
6265
		$screen = get_current_screen();
6266
		if ( 'dashboard' !== $screen->base && ! did_action( 'jetpack_notices' ) ) {
6267
			return;
6268
		}
6269
6270
		// Include the js!
6271
		$ajax_nonce = wp_create_nonce( 'resolve-identity-crisis' );
6272
		$this->identity_crisis_js( $ajax_nonce );
6273
6274
		// Include the CSS!
6275
		if ( ! wp_script_is( 'jetpack', 'done' ) ) {
6276
			$this->admin_banner_styles();
6277
		}
6278
6279
		if ( ! array_key_exists( 'error_code', $errors ) ) {
6280
			$key = 'siteurl';
6281
			if ( ! $errors[ $key ] ) {
6282
				$key = 'home';
6283
			}
6284
		} else {
6285
			$key = 'error_code';
6286
			// 401 is the only error we care about.  Any other errors should not trigger the alert.
6287
			if ( 401 !== $errors[ $key ] ) {
6288
				return;
6289
			}
6290
		}
6291
6292
		?>
6293
6294
		<style>
6295
			.jp-identity-crisis .jp-btn-group {
6296
					margin: 15px 0;
6297
				}
6298
			.jp-identity-crisis strong {
6299
					color: #518d2a;
6300
				}
6301
			.jp-identity-crisis.dismiss {
6302
				display: none;
6303
			}
6304
			.jp-identity-crisis .button {
6305
				margin-right: 4px;
6306
			}
6307
		</style>
6308
6309
		<div id="message" class="error jetpack-message jp-identity-crisis stay-visible">
6310
			<div class="service-mark"></div>
6311
			<div class="jp-id-banner__content">
6312
				<!-- <h3 class="banner-title"><?php _e( 'Something\'s not quite right with your Jetpack connection! Let\'s fix that.', 'jetpack' ); ?></h3> -->
6313
6314
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-1">
6315
					<?php
6316
					// 401 means that this site has been disconnected from wpcom, but the remote site still thinks it's connected.
6317
					if ( 'error_code' == $key && '401' == $errors[ $key ] ) : ?>
6318
						<div class="banner-content">
6319
							<p><?php
6320
								/* translators: %s is a URL */
6321
								printf( __( 'Our records show that this site does not have a valid connection to WordPress.com. Please reset your connection to fix this. <a href="%s" target="_blank">What caused this?</a>', 'jetpack' ), 'https://jetpack.com/support/no-valid-wordpress-com-connection/' );
6322
							?></p>
6323
						</div>
6324
						<div class="jp-btn-group">
6325
							<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a>
6326
							<span class="idc-separator">|</span>
6327
							<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>"><?php _e( 'Deactivate Jetpack', 'jetpack' ); ?></a>
6328
						</div>
6329
					<?php else : ?>
6330
							<div class="banner-content">
6331
							<p><?php printf( __( 'It looks like you may have changed your domain. Is <strong>%1$s</strong> still your site\'s domain, or have you updated it to <strong> %2$s </strong>?', 'jetpack' ), $errors[ $key ], (string) get_option( $key ) ); ?></p>
6332
							</div>
6333
						<div class="jp-btn-group">
6334
							<a href="#" class="regular site-moved"><?php printf( __( '%s is now my domain.', 'jetpack' ), $errors[ $key ] ); ?></a> <span class="idc-separator">|</span> <a href="#" class="site-not-moved" ><?php printf( __( '%s is still my domain.', 'jetpack' ), (string) get_option( $key ) ); ?></a>
6335
							<span class="spinner"></span>
6336
						</div>
6337
					<?php endif ; ?>
6338
				</div>
6339
6340
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-2" style="display: none;">
6341
					<div class="banner-content">
6342
						<p><?php printf(
6343
							/* translators: %1$s, %2$s and %3$s are URLs */
6344
							__(
6345
								'Are <strong> %2$s </strong> and <strong> %1$s </strong> two completely separate websites? If so we should create a new connection, which will reset your followers and linked services. <a href="%3$s"><em>What does this mean?</em></a>',
6346
								'jetpack'
6347
							),
6348
							$errors[ $key ],
6349
							(string) get_option( $key ),
6350
							'https://jetpack.com/support/what-does-resetting-the-connection-mean/'
6351
						); ?></p>
6352
					</div>
6353
					<div class="jp-btn-group">
6354
						<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6355
						<a href="#" class="is-dev-env"><?php _e( 'This is a development environment', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6356
						<a href="https://jetpack.com/contact-support/" class="contact-support"><?php _e( 'Submit a support ticket', 'jetpack' ); ?></a>
6357
						<span class="spinner"></span>
6358
					</div>
6359
				</div>
6360
6361
				<div class="jp-id-crisis-success" id="jp-id-crisis-success" style="display: none;">
6362
					<h3 class="success-notice"><?php printf( __( 'Thanks for taking the time to sort things out. We&#039;ve updated our records accordingly!', 'jetpack' ) ); ?></h3>
6363
				</div>
6364
			</div>
6365
		</div>
6366
6367
		<?php
6368
	}
6369
6370
	/**
6371
	 * Maybe Use a .min.css stylesheet, maybe not.
6372
	 *
6373
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6374
	 */
6375
	public static function maybe_min_asset( $url, $path, $plugin ) {
6376
		// Short out on things trying to find actual paths.
6377
		if ( ! $path || empty( $plugin ) ) {
6378
			return $url;
6379
		}
6380
6381
		// Strip out the abspath.
6382
		$base = dirname( plugin_basename( $plugin ) );
6383
6384
		// Short out on non-Jetpack assets.
6385
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6386
			return $url;
6387
		}
6388
6389
		// File name parsing.
6390
		$file              = "{$base}/{$path}";
6391
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6392
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6393
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6394
		$extension         = array_shift( $file_name_parts_r );
6395
6396
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6397
			// Already pointing at the minified version.
6398
			if ( 'min' === $file_name_parts_r[0] ) {
6399
				return $url;
6400
			}
6401
6402
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6403
			if ( file_exists( $min_full_path ) ) {
6404
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6405
			}
6406
		}
6407
6408
		return $url;
6409
	}
6410
6411
	/**
6412
	 * Maybe inlines a stylesheet.
6413
	 *
6414
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6415
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6416
	 *
6417
	 * Attached to `style_loader_tag` filter.
6418
	 *
6419
	 * @param string $tag The tag that would link to the external asset.
6420
	 * @param string $handle The registered handle of the script in question.
6421
	 *
6422
	 * @return string
6423
	 */
6424
	public static function maybe_inline_style( $tag, $handle ) {
6425
		global $wp_styles;
6426
		$item = $wp_styles->registered[ $handle ];
6427
6428
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6429
			return $tag;
6430
		}
6431
6432
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6433
			$href = $matches[1];
6434
			// Strip off query string
6435
			if ( $pos = strpos( $href, '?' ) ) {
6436
				$href = substr( $href, 0, $pos );
6437
			}
6438
			// Strip off fragment
6439
			if ( $pos = strpos( $href, '#' ) ) {
6440
				$href = substr( $href, 0, $pos );
6441
			}
6442
		} else {
6443
			return $tag;
6444
		}
6445
6446
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6447
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6448
			return $tag;
6449
		}
6450
6451
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6452
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6453
			// And this isn't the pass that actually deals with the RTL version...
6454
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6455
				// Short out, as the RTL version will deal with it in a moment.
6456
				return $tag;
6457
			}
6458
		}
6459
6460
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6461
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6462
		if ( $css ) {
6463
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6464
			if ( empty( $item->extra['after'] ) ) {
6465
				wp_add_inline_style( $handle, $css );
6466
			} else {
6467
				array_unshift( $item->extra['after'], $css );
6468
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6469
			}
6470
		}
6471
6472
		return $tag;
6473
	}
6474
6475
	/**
6476
	 * Loads a view file from the views
6477
	 *
6478
	 * Data passed in with the $data parameter will be available in the
6479
	 * template file as $data['value']
6480
	 *
6481
	 * @param string $template - Template file to load
6482
	 * @param array $data - Any data to pass along to the template
6483
	 * @return boolean - If template file was found
6484
	 **/
6485
	public function load_view( $template, $data = array() ) {
6486
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6487
6488
		if( file_exists( $views_dir . $template ) ) {
6489
			require_once( $views_dir . $template );
6490
			return true;
6491
		}
6492
6493
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6494
		return false;
6495
	}
6496
6497
	/**
6498
	 * Sends a ping to the Jetpack servers to toggle on/off remote portions
6499
	 * required by some modules.
6500
	 *
6501
	 * @param string $module_slug
6502
	 */
6503
	public function toggle_module_on_wpcom( $module_slug ) {
6504
		Jetpack::init()->sync->register( 'noop' );
6505
6506
		if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
6507
			self::check_privacy( $module_slug );
6508
		}
6509
6510
	}
6511
6512
	/**
6513
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6514
	 */
6515
	public function deprecated_hooks() {
6516
		global $wp_filter;
6517
6518
		/*
6519
		 * Format:
6520
		 * deprecated_filter_name => replacement_name
6521
		 *
6522
		 * If there is no replacement us null for replacement_name
6523
		 */
6524
		$deprecated_list = array(
6525
			'jetpack_bail_on_shortcode'                => 'jetpack_shortcodes_to_include',
6526
			'wpl_sharing_2014_1'                       => null,
6527
			'jetpack-tools-to-include'                 => 'jetpack_tools_to_include',
6528
			'jetpack_identity_crisis_options_to_check' => null,
6529
		);
6530
6531
		// This is a silly loop depth. Better way?
6532
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6533
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
6534
				foreach( $wp_filter[$hook] AS $func => $values ) {
6535
					foreach( $values AS $hooked ) {
6536
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
6537
					}
6538
				}
6539
			}
6540
		}
6541
	}
6542
6543
	/**
6544
	 * Converts any url in a stylesheet, to the correct absolute url.
6545
	 *
6546
	 * Considerations:
6547
	 *  - Normal, relative URLs     `feh.png`
6548
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6549
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6550
	 *  - Absolute URLs             `http://domain.com/feh.png`
6551
	 *  - Domain root relative URLs `/feh.png`
6552
	 *
6553
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6554
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6555
	 *
6556
	 * @return mixed|string
6557
	 */
6558
	public static function absolutize_css_urls( $css, $css_file_url ) {
6559
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6560
		$css_dir = dirname( $css_file_url );
6561
		$p       = parse_url( $css_dir );
6562
		$domain  = sprintf(
6563
					'%1$s//%2$s%3$s%4$s',
6564
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6565
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6566
					$p['host'],
6567
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6568
				);
6569
6570
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6571
			$find = $replace = array();
6572
			foreach ( $matches as $match ) {
6573
				$url = trim( $match['path'], "'\" \t" );
6574
6575
				// If this is a data url, we don't want to mess with it.
6576
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6577
					continue;
6578
				}
6579
6580
				// If this is an absolute or protocol-agnostic url,
6581
				// we don't want to mess with it.
6582
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6583
					continue;
6584
				}
6585
6586
				switch ( substr( $url, 0, 1 ) ) {
6587
					case '/':
6588
						$absolute = $domain . $url;
6589
						break;
6590
					default:
6591
						$absolute = $css_dir . '/' . $url;
6592
				}
6593
6594
				$find[]    = $match[0];
6595
				$replace[] = sprintf( 'url("%s")', $absolute );
6596
			}
6597
			$css = str_replace( $find, $replace, $css );
6598
		}
6599
6600
		return $css;
6601
	}
6602
6603
	/**
6604
	 * This method checks to see if SSL is required by the site in
6605
	 * order to visit it in some way other than only setting the
6606
	 * https value in the home or siteurl values.
6607
	 *
6608
	 * @since 3.2
6609
	 * @return boolean
6610
	 **/
6611
	private function is_ssl_required_to_visit_site() {
6612
		global $wp_version;
6613
		$ssl = is_ssl();
6614
6615
		if ( force_ssl_admin() ) {
6616
			$ssl = true;
6617
		}
6618
		return $ssl;
6619
	}
6620
6621
	/**
6622
	 * This methods removes all of the registered css files on the frontend
6623
	 * from Jetpack in favor of using a single file. In effect "imploding"
6624
	 * all the files into one file.
6625
	 *
6626
	 * Pros:
6627
	 * - Uses only ONE css asset connection instead of 15
6628
	 * - Saves a minimum of 56k
6629
	 * - Reduces server load
6630
	 * - Reduces time to first painted byte
6631
	 *
6632
	 * Cons:
6633
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6634
	 *		should not cause any issues with themes.
6635
	 * - Plugins/themes dequeuing styles no longer do anything. See
6636
	 *		jetpack_implode_frontend_css filter for a workaround
6637
	 *
6638
	 * For some situations developers may wish to disable css imploding and
6639
	 * instead operate in legacy mode where each file loads seperately and
6640
	 * can be edited individually or dequeued. This can be accomplished with
6641
	 * the following line:
6642
	 *
6643
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6644
	 *
6645
	 * @since 3.2
6646
	 **/
6647
	public function implode_frontend_css( $travis_test = false ) {
6648
		$do_implode = true;
6649
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6650
			$do_implode = false;
6651
		}
6652
6653
		/**
6654
		 * Allow CSS to be concatenated into a single jetpack.css file.
6655
		 *
6656
		 * @since 3.2.0
6657
		 *
6658
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6659
		 */
6660
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6661
6662
		// Do not use the imploded file when default behaviour was altered through the filter
6663
		if ( ! $do_implode ) {
6664
			return;
6665
		}
6666
6667
		// We do not want to use the imploded file in dev mode, or if not connected
6668
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6669
			if ( ! $travis_test ) {
6670
				return;
6671
			}
6672
		}
6673
6674
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6675
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6676
			return;
6677
		}
6678
6679
		/*
6680
		 * Now we assume Jetpack is connected and able to serve the single
6681
		 * file.
6682
		 *
6683
		 * In the future there will be a check here to serve the file locally
6684
		 * or potentially from the Jetpack CDN
6685
		 *
6686
		 * For now:
6687
		 * - Enqueue a single imploded css file
6688
		 * - Zero out the style_loader_tag for the bundled ones
6689
		 * - Be happy, drink scotch
6690
		 */
6691
6692
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6693
6694
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6695
6696
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6697
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6698
	}
6699
6700
	function concat_remove_style_loader_tag( $tag, $handle ) {
6701
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6702
			$tag = '';
6703
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6704
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6705
			}
6706
		}
6707
6708
		return $tag;
6709
	}
6710
6711
	/*
6712
	 * Check the heartbeat data
6713
	 *
6714
	 * Organizes the heartbeat data by severity.  For example, if the site
6715
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6716
	 *
6717
	 * Data will be added to "caution" array, if it either:
6718
	 *  - Out of date Jetpack version
6719
	 *  - Out of date WP version
6720
	 *  - Out of date PHP version
6721
	 *
6722
	 * $return array $filtered_data
6723
	 */
6724
	public static function jetpack_check_heartbeat_data() {
6725
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6726
6727
		$good    = array();
6728
		$caution = array();
6729
		$bad     = array();
6730
6731
		foreach ( $raw_data as $stat => $value ) {
6732
6733
			// Check jetpack version
6734
			if ( 'version' == $stat ) {
6735
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6736
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6737
					continue;
6738
				}
6739
			}
6740
6741
			// Check WP version
6742
			if ( 'wp-version' == $stat ) {
6743
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6744
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6745
					continue;
6746
				}
6747
			}
6748
6749
			// Check PHP version
6750
			if ( 'php-version' == $stat ) {
6751
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6752
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6753
					continue;
6754
				}
6755
			}
6756
6757
			// Check ID crisis
6758
			if ( 'identitycrisis' == $stat ) {
6759
				if ( 'yes' == $value ) {
6760
					$bad[ $stat ] = $value;
6761
					continue;
6762
				}
6763
			}
6764
6765
			// The rest are good :)
6766
			$good[ $stat ] = $value;
6767
		}
6768
6769
		$filtered_data = array(
6770
			'good'    => $good,
6771
			'caution' => $caution,
6772
			'bad'     => $bad
6773
		);
6774
6775
		return $filtered_data;
6776
	}
6777
6778
6779
	/*
6780
	 * This method is used to organize all options that can be reset
6781
	 * without disconnecting Jetpack.
6782
	 *
6783
	 * It is used in class.jetpack-cli.php to reset options
6784
	 *
6785
	 * @return array of options to delete.
6786
	 */
6787
	public static function get_jetpack_options_for_reset() {
6788
		$jetpack_options            = Jetpack_Options::get_option_names();
6789
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6790
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6791
6792
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6793
6794
		// A manual build of the wp options
6795
		$wp_options = array(
6796
			'sharing-options',
6797
			'disabled_likes',
6798
			'disabled_reblogs',
6799
			'jetpack_comments_likes_enabled',
6800
			'wp_mobile_excerpt',
6801
			'wp_mobile_featured_images',
6802
			'wp_mobile_app_promos',
6803
			'stats_options',
6804
			'stats_dashboard_widget',
6805
			'safecss_preview_rev',
6806
			'safecss_rev',
6807
			'safecss_revision_migrated',
6808
			'nova_menu_order',
6809
			'jetpack_portfolio',
6810
			'jetpack_portfolio_posts_per_page',
6811
			'jetpack_testimonial',
6812
			'jetpack_testimonial_posts_per_page',
6813
			'wp_mobile_custom_css',
6814
			'sharedaddy_disable_resources',
6815
			'sharing-options',
6816
			'sharing-services',
6817
			'site_icon_temp_data',
6818
			'featured-content',
6819
			'site_logo',
6820
		);
6821
6822
		// Flag some Jetpack options as unsafe
6823
		$unsafe_options = array(
6824
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6825
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6826
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6827
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6828
6829
			// non_compact
6830
			'activated',
6831
6832
			// private
6833
			'register',
6834
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6835
			'user_token',                  // (string) The User Token of this site. (deprecated)
6836
			'user_tokens'
6837
		);
6838
6839
		// Remove the unsafe Jetpack options
6840
		foreach ( $unsafe_options as $unsafe_option ) {
6841
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6842
				unset( $all_jp_options[ $key ] );
6843
			}
6844
		}
6845
6846
		$options = array(
6847
			'jp_options' => $all_jp_options,
6848
			'wp_options' => $wp_options
6849
		);
6850
6851
		return $options;
6852
	}
6853
6854
	/*
6855
	 * Check if an option of a Jetpack module has been updated.
6856
	 *
6857
	 * If any module option has been updated before Jump Start has been dismissed,
6858
	 * update the 'jumpstart' option so we can hide Jump Start.
6859
	 */
6860
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6861
		// Bail if Jump Start has already been dismissed
6862
		if ( 'new_connection' !== Jetpack::get_option( 'jumpstart' ) ) {
6863
			return false;
6864
		}
6865
6866
		$jetpack = Jetpack::init();
6867
6868
6869
		// Manual build of module options
6870
		$option_names = self::get_jetpack_options_for_reset();
6871
6872
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6873
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6874
6875
			//Jump start is being dismissed send data to MC Stats
6876
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6877
6878
			$jetpack->do_stats( 'server_side' );
6879
		}
6880
6881
	}
6882
6883
	/*
6884
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6885
	 * so we can bring them directly to their site in calypso.
6886
	 *
6887
	 * @param string | url
6888
	 * @return string | url without the guff
6889
	 */
6890
	public static function build_raw_urls( $url ) {
6891
		$strip_http = '/.*?:\/\//i';
6892
		$url = preg_replace( $strip_http, '', $url  );
6893
		$url = str_replace( '/', '::', $url );
6894
		return $url;
6895
	}
6896
6897
	/**
6898
	 * Stores and prints out domains to prefetch for page speed optimization.
6899
	 *
6900
	 * @param mixed $new_urls
6901
	 */
6902
	public static function dns_prefetch( $new_urls = null ) {
6903
		static $prefetch_urls = array();
6904
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6905
			echo "\r\n";
6906
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6907
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6908
			}
6909
		} elseif ( ! empty( $new_urls ) ) {
6910
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6911
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6912
			}
6913
			foreach ( (array) $new_urls as $this_new_url ) {
6914
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6915
			}
6916
			$prefetch_urls = array_unique( $prefetch_urls );
6917
		}
6918
	}
6919
6920
	public function wp_dashboard_setup() {
6921
		if ( self::is_active() ) {
6922
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6923
			$widget_title = __( 'Site Stats', 'jetpack' );
6924
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6925
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6926
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6927
		}
6928
6929
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6930
			wp_add_dashboard_widget(
6931
				'jetpack_summary_widget',
6932
				$widget_title,
6933
				array( __CLASS__, 'dashboard_widget' )
6934
			);
6935
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6936
6937
			// If we're inactive and not in development mode, sort our box to the top.
6938
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6939
				global $wp_meta_boxes;
6940
6941
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6942
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6943
6944
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6945
			}
6946
		}
6947
	}
6948
6949
	/**
6950
	 * @param mixed $result Value for the user's option
6951
	 * @return mixed
6952
	 */
6953
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6954
		if ( ! is_array( $sorted ) ) {
6955
			return $sorted;
6956
		}
6957
6958
		foreach ( $sorted as $box_context => $ids ) {
6959
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6960
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6961
				continue;
6962
			}
6963
6964
			$ids_array = explode( ',', $ids );
6965
			$key = array_search( 'dashboard_stats', $ids_array );
6966
6967
			if ( false !== $key ) {
6968
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6969
				$ids_array[ $key ] = 'jetpack_summary_widget';
6970
				$sorted[ $box_context ] = implode( ',', $ids_array );
6971
				// We've found it, stop searching, and just return.
6972
				break;
6973
			}
6974
		}
6975
6976
		return $sorted;
6977
	}
6978
6979
	public static function dashboard_widget() {
6980
		/**
6981
		 * Fires when the dashboard is loaded.
6982
		 *
6983
		 * @since 3.4.0
6984
		 */
6985
		do_action( 'jetpack_dashboard_widget' );
6986
	}
6987
6988
	public static function dashboard_widget_footer() {
6989
		?>
6990
		<footer>
6991
6992
		<div class="protect">
6993
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6994
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6995
				<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>
6996
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6997
				<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' ); ?>">
6998
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6999
				</a>
7000
			<?php else : ?>
7001
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
7002
			<?php endif; ?>
7003
		</div>
7004
7005
		<div class="akismet">
7006
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7007
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
7008
				<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>
7009 View Code Duplication
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7010
				<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">
7011
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
7012
				</a>
7013
			<?php else : ?>
7014
				<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>
7015
			<?php endif; ?>
7016
		</div>
7017
7018
7019 View Code Duplication
		<?php if ( ! current_user_can( 'edit_posts' ) && self::is_user_connected() ) : ?>
7020
			<div style="width: 100%; text-align: center; padding-top: 20px; clear: both;"><a class="button" title="<?php esc_attr_e( 'Unlink your account from WordPress.com', 'jetpack' ); ?>" href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'unlink', 'redirect' => 'sub-unlink' ), admin_url( 'index.php' ) ), 'jetpack-unlink' ) ); ?>"><?php esc_html_e( 'Unlink your account from WordPress.com', 'jetpack' ); ?></a></div>
7021
		<?php endif; ?>
7022
7023
		</footer>
7024
		<?php
7025
	}
7026
7027
	public function dashboard_widget_connect_to_wpcom() {
7028
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
7029
			return;
7030
		}
7031
		?>
7032
		<div class="wpcom-connect">
7033
			<div class="jp-emblem">
7034
			<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">
7035
				<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"/>
7036
			</svg>
7037
			</div>
7038
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
7039
			<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>
7040
7041
			<div class="actions">
7042
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
7043
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
7044
				</a>
7045
			</div>
7046
		</div>
7047
		<?php
7048
	}
7049
7050
	/*
7051
	 * A graceful transition to using Core's site icon.
7052
	 *
7053
	 * All of the hard work has already been done with the image
7054
	 * in all_done_page(). All that needs to be done now is update
7055
	 * the option and display proper messaging.
7056
	 *
7057
	 * @todo remove when WP 4.3 is minimum
7058
	 *
7059
	 * @since 3.6.1
7060
	 *
7061
	 * @return bool false = Core's icon not available || true = Core's icon is available
7062
	 */
7063
	public static function jetpack_site_icon_available_in_core() {
7064
		global $wp_version;
7065
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
7066
7067
		if ( ! $core_icon_available ) {
7068
			return false;
7069
		}
7070
7071
		// No need for Jetpack's site icon anymore if core's is already set
7072
		if ( has_site_icon() ) {
7073
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
7074
				Jetpack::log( 'deactivate', 'site-icon' );
7075
				Jetpack::deactivate_module( 'site-icon' );
7076
			}
7077
			return true;
7078
		}
7079
7080
		// Transfer Jetpack's site icon to use core.
7081
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
7082
		if ( $site_icon_id ) {
7083
			// Update core's site icon
7084
			update_option( 'site_icon', $site_icon_id );
7085
7086
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
7087
			delete_option( 'site_icon_id' );
7088
		}
7089
7090
		// No need for Jetpack's site icon anymore
7091
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
7092
			Jetpack::log( 'deactivate', 'site-icon' );
7093
			Jetpack::deactivate_module( 'site-icon' );
7094
		}
7095
7096
		return true;
7097
	}
7098
7099
}
7100