Completed
Push — add/xml-sitemap ( f1e7a4...063fac )
by Jeremy
110:17 queued 98:29
created

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