Completed
Push — branch-3.9 ( 77e8dd...45c3f6 )
by
unknown
16:01 queued 05:43
created

class.jetpack.php (20 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'tiled-gallery',
46
		'widget-conditions',
47
		'jetpack_display_posts_widget',
48
		'gravatar-profile-widget',
49
		'widget-grid-and-list',
50
		'jetpack-widgets',
51
		'goodreads-widget',
52
		'jetpack_social_media_icons_widget',
53
	);
54
55
	public $plugins_to_deactivate = array(
56
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
57
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
63
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
64
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
65
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
66
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
67
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
68
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
69
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
70
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
71
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
72
	);
73
74
	public $capability_translations = array(
75
		'administrator' => 'manage_options',
76
		'editor'        => 'edit_others_posts',
77
		'author'        => 'publish_posts',
78
		'contributor'   => 'edit_posts',
79
		'subscriber'    => 'read',
80
	);
81
82
	/**
83
	 * Map of modules that have conflicts with plugins and should not be auto-activated
84
	 * if the plugins are active.  Used by filter_default_modules
85
	 *
86
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
87
	 * change `module-slug` and add this to your plugin:
88
	 *
89
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
90
	 * function my_jetpack_get_default_modules( $modules ) {
91
	 *     return array_diff( $modules, array( 'module-slug' ) );
92
	 * }
93
	 *
94
	 * @var array
95
	 */
96
	private $conflicting_plugins = array(
97
		'comments'          => array(
98
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
99
			'Disqus'                               => 'disqus-comment-system/disqus.php',
100
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
101
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
102
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
103
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
104
		),
105
		'contact-form'      => array(
106
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
107
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
108
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
109
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
110
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
111
		),
112
		'minileven'         => array(
113
			'WPtouch'                              => 'wptouch/wptouch.php',
114
		),
115
		'latex'             => array(
116
			'LaTeX for WordPress'                  => 'latex/latex.php',
117
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
118
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
119
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
120
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
121
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
122
		),
123
		'protect'           => array(
124
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
125
			'Captcha'                              => 'captcha/captcha.php',
126
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
127
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
128
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
129
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
130
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
131
			'Security-protection'                  => 'security-protection/security-protection.php',
132
			'Login Security'                       => 'login-security/login-security.php',
133
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
134
			'Wordfence Security'                   => 'wordfence/wordfence.php',
135
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
136
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
137
		),
138
		'random-redirect'   => array(
139
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
140
		),
141
		'related-posts'     => array(
142
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
143
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
144
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
145
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
146
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
147
			'outbrain'                             => 'outbrain/outbrain.php',
148
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
149
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
150
		),
151
		'sharedaddy'        => array(
152
			'AddThis'                              => 'addthis/addthis_social_widget.php',
153
			'Add To Any'                           => 'add-to-any/add-to-any.php',
154
			'ShareThis'                            => 'share-this/sharethis.php',
155
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
156
		),
157
		'verification-tools' => array(
158
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
159
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
160
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
161
		),
162
		'widget-visibility' => array(
163
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
164
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
165
		),
166
		'sitemaps' => array(
167
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
168
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
169
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
170
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
171
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
172
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
173
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
174
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
175
			'Sitemap'                              => 'sitemap/sitemap.php',
176
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
177
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
178
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
179
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
180
		),
181
	);
182
183
	/**
184
	 * Plugins for which we turn off our Facebook OG Tags implementation.
185
	 *
186
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
187
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
188
	 *
189
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
190
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
191
	 */
192
	private $open_graph_conflicting_plugins = array(
193
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
194
		                                                         // 2 Click Social Media Buttons
195
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
196
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
197
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
198
		'facebook/facebook.php',                                 // Facebook (official plugin)
199
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
200
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
201
		                                                         // Facebook Featured Image & OG Meta Tags
202
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
203
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
204
		                                                         // Facebook Open Graph Meta Tags for WordPress
205
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
206
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
207
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
208
		                                                         // Fedmich's Facebook Open Graph Meta
209
		'header-footer/plugin.php',                              // Header and Footer
210
		'network-publisher/networkpub.php',                      // Network Publisher
211
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
212
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
213
		                                                         // NextScripts SNAP
214
		'opengraph/opengraph.php',                               // Open Graph
215
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
216
		                                                         // Open Graph Protocol Framework
217
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
218
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
219
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
220
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
221
		'sharepress/sharepress.php',                             // SharePress
222
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
223
		'social-discussions/social-discussions.php',             // Social Discussions
224
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
225
		'socialize/socialize.php',                               // Socialize
226
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
227
		                                                         // Tweet, Like, Google +1 and Share
228
		'wordbooker/wordbooker.php',                             // Wordbooker
229
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
230
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
231
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
232
		                                                         // WP Facebook Like Send & Open Graph Meta
233
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
234
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
235
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
236
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
237
	);
238
239
	/**
240
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
241
	 */
242
	private $twitter_cards_conflicting_plugins = array(
243
	//	'twitter/twitter.php',                       // The official one handles this on its own.
244
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
245
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
246
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
247
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
248
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
249
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
250
		'twitter-cards/twitter-cards.php',           // Twitter Cards
251
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
252
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
253
	);
254
255
	/**
256
	 * Message to display in admin_notice
257
	 * @var string
258
	 */
259
	public $message = '';
260
261
	/**
262
	 * Error to display in admin_notice
263
	 * @var string
264
	 */
265
	public $error = '';
266
267
	/**
268
	 * Modules that need more privacy description.
269
	 * @var string
270
	 */
271
	public $privacy_checks = '';
272
273
	/**
274
	 * Stats to record once the page loads
275
	 *
276
	 * @var array
277
	 */
278
	public $stats = array();
279
280
	/**
281
	 * Allows us to build a temporary security report
282
	 *
283
	 * @var array
284
	 */
285
	static $security_report = array();
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	static $instance = false;
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			if ( did_action( 'plugins_loaded' ) )
311
				self::plugin_textdomain();
312
			else
313
				add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
314
315
			self::$instance = new Jetpack;
316
317
			self::$instance->plugin_upgrade();
318
319
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
320
321
		}
322
323
		return self::$instance;
324
	}
325
326
	/**
327
	 * Must never be called statically
328
	 */
329
	function plugin_upgrade() {
330
		// Upgrade: 1.1 -> 1.2
331
		if ( get_option( 'jetpack_id' ) ) {
332
			// Move individual jetpack options to single array of options
333
			$options = array();
334
			foreach ( Jetpack_Options::get_option_names() as $option ) {
335
				if ( false !== $value = get_option( "jetpack_$option" ) ) {
336
					$options[$option] = $value;
337
				}
338
			}
339
340
			if ( $options ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $options 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...
341
				Jetpack_Options::update_options( $options );
342
343
				foreach ( array_keys( $options ) as $option ) {
344
					delete_option( "jetpack_$option" );
345
				}
346
			}
347
348
			// Add missing version and old_version options
349 View Code Duplication
			if ( ! $version = Jetpack_Options::get_option( 'version' ) ) {
350
				$version = $old_version = '1.1:' . time();
351
				/**
352
				 * Fires on update, before bumping version numbers up to a new version.
353
				 *
354
				 * @since 3.4.0
355
				 *
356
				 * @param string $version Jetpack version number.
357
				 * @param bool false Does an old version exist. Default is false.
358
				 */
359
				do_action( 'updating_jetpack_version', $version, false );
360
				Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
361
			}
362
		}
363
364
		// Upgrade from a single user token to a user_id-indexed array and a master_user ID
365
		if ( ! Jetpack_Options::get_option( 'user_tokens' ) ) {
366
			if ( $user_token = Jetpack_Options::get_option( 'user_token' ) ) {
367
				$token_parts = explode( '.', $user_token );
368
				if ( isset( $token_parts[2] ) ) {
369
					$master_user = $token_parts[2];
370
					$user_tokens = array( $master_user => $user_token );
371
					Jetpack_Options::update_options( compact( 'master_user', 'user_tokens' ) );
372
					Jetpack_Options::delete_option( 'user_token' );
373
				} else {
374
					// @todo: is this even possible?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
375
					trigger_error( sprintf( 'Jetpack::plugin_upgrade found no user_id in user_token "%s"', $user_token ), E_USER_WARNING );
376
				}
377
			}
378
		}
379
380
		// Clean up legacy G+ Authorship data.
381
		if ( get_option( 'gplus_authors' ) ) {
382
			delete_option( 'gplus_authors' );
383
			delete_option( 'hide_gplus' );
384
			delete_metadata( 'post', 0, 'gplus_authorship_disabled', null, true );
385
		}
386
387
		if ( ! get_option( 'jetpack_private_options' ) ) {
388
			$jetpack_options = get_option( 'jetpack_options', array() );
389
			foreach( Jetpack_Options::get_option_names( 'private' ) as $option_name ) {
390
				if ( isset( $jetpack_options[ $option_name ] ) ) {
391
					Jetpack_Options::update_option( $option_name, $jetpack_options[ $option_name ] );
392
					unset( $jetpack_options[ $option_name ] );
393
				}
394
			}
395
			update_option( 'jetpack_options', $jetpack_options );
396
		}
397
398
		if ( Jetpack::is_active() ) {
399
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
400
			if ( JETPACK__VERSION != $version ) {
401
402
				// Check which active modules actually exist and remove others from active_modules list
403
				$unfiltered_modules = Jetpack::get_active_modules();
404
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
405
				if ( array_diff( $unfiltered_modules, $modules ) ) {
406
					Jetpack_Options::update_option( 'active_modules', $modules );
407
				}
408
409
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
410
				/**
411
				 * Fires when synchronizing all registered options and constants.
412
				 *
413
				 * @since 3.3.0
414
				 */
415
				do_action( 'jetpack_sync_all_registered_options' );
416
			}
417
418
			//if Jetpack is connected check if jetpack_unique_connection exists and if not then set it
419
			$jetpack_unique_connection = get_option( 'jetpack_unique_connection' );
420
			$is_unique_connection = $jetpack_unique_connection && array_key_exists( 'version', $jetpack_unique_connection );
421
			if ( ! $is_unique_connection ) {
422
				$jetpack_unique_connection = array(
423
					'connected'     => 1,
424
					'disconnected'  => -1,
425
					'version'       => '3.6.1'
426
				);
427
				update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
428
			}
429
		}
430
431
		if ( get_option( 'jetpack_json_api_full_management' ) ) {
432
			delete_option( 'jetpack_json_api_full_management' );
433
			self::activate_manage();
434
		}
435
436
	}
437
438
	static function activate_manage( ) {
439
440
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
441
			self::activate_module( 'manage', false, false );
442
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
443
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
444
		}
445
446
	}
447
448
	/**
449
	 * Constructor.  Initializes WordPress hooks
450
	 */
451
	private function __construct() {
452
		/*
453
		 * Check for and alert any deprecated hooks
454
		 */
455
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
456
457
		/*
458
		 * Do things that should run even in the network admin
459
		 * here, before we potentially fail out.
460
		 */
461
		add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
462
463
		/**
464
		 * We need sync object even in Multisite mode
465
		 */
466
		$this->sync = new Jetpack_Sync;
467
468
		/**
469
		 * Trigger a wp_version sync when updating WP versions
470
		 **/
471
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
472
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
473
474
		add_action( 'init', array( $this, 'sync_update_data') );
475
		add_action( 'init', array( $this, 'sync_theme_data' ) );
476
477
		/*
478
		 * Load things that should only be in Network Admin.
479
		 *
480
		 * For now blow away everything else until a more full
481
		 * understanding of what is needed at the network level is
482
		 * available
483
		 */
484
		if( is_multisite() ) {
485
			Jetpack_Network::init();
486
487
			// Only sync this info if we are on a multi site
488
			// @since  3.7
489
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
490
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
491
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
492
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
493
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
494
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
495
496
			if( is_network_admin() ) {
497
				// Sync network site data if it is updated or not.
498
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
499
				return; // End here to prevent single site actions from firing
500
			}
501
		}
502
503
504
		$theme_slug = get_option( 'stylesheet' );
505
506
507
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
508
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
509
		$this->sync->options(
510
			JETPACK__PLUGIN_DIR . 'jetpack.php',
511
			'home',
512
			'siteurl',
513
			'blogname',
514
			'gmt_offset',
515
			'timezone_string',
516
			'security_report',
517
			'stylesheet',
518
			"theme_mods_{$theme_slug}",
519
			'jetpack_sync_non_public_post_stati',
520
			'jetpack_options',
521
			'site_icon', // (int) - ID of core's Site Icon attachment ID
522
			'default_post_format',
523
			'default_category',
524
			'large_size_w',
525
			'large_size_h',
526
			'thumbnail_size_w',
527
			'thumbnail_size_h',
528
			'medium_size_w',
529
			'medium_size_h',
530
			'thumbnail_crop',
531
			'image_default_link_type'
532
		);
533
534
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
535
			$this->sync->options( __FILE__, 'jetpack_' . $option );
536
		}
537
538
		/**
539
		 * Sometimes you want to sync data to .com without adding options to .org sites.
540
		 * The mock option allows you to do just that.
541
		 */
542
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
543
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
544
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
545
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
546
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
547
548
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
549
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
550
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
551
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
552
553
		/**
554
		 * Trigger an update to the main_network_site when we update the blogname of a site.
555
		 *
556
		 */
557
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
558
559
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
560
561
		// Update the settings everytime the we register a new user to the site or we delete a user.
562
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
563
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
564
565
		// Unlink user before deleting the user from .com
566
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
567
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
568
569
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
570
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
571
572
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
573
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
574
575
			$this->require_jetpack_authentication();
576
577
			if ( Jetpack::is_active() ) {
578
				// Hack to preserve $HTTP_RAW_POST_DATA
579
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
580
581
				$signed = $this->verify_xml_rpc_signature();
582
				if ( $signed && ! is_wp_error( $signed ) ) {
583
					// The actual API methods.
584
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
585
				} else {
586
					add_filter( 'xmlrpc_methods', '__return_empty_array' );
587
				}
588
			} else {
589
				// The bootstrap API methods.
590
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
591
			}
592
593
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
594
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
595
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
596
			$this->require_jetpack_authentication();
597
			$this->add_remote_request_handlers();
598
		} else {
599
			if ( Jetpack::is_active() ) {
600
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
601
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
602
			}
603
		}
604
605
		if ( Jetpack::is_active() ) {
606
			Jetpack_Heartbeat::init();
607
		}
608
609
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
610
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
611
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
612
		}
613
614
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
615
616
		add_action( 'admin_init', array( $this, 'admin_init' ) );
617
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
618
619
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
620
621
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
622
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
623
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
624
625
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
626
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
627
628
		// Jump Start AJAX callback function
629
		add_action( 'wp_ajax_jetpack_jumpstart_ajax',  array( $this, 'jetpack_jumpstart_ajax_callback' ) );
630
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
631
632
		// Identity Crisis AJAX callback function
633
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
634
635
		// JITM AJAX callback function
636
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
637
638
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
639
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
640
641
		// Universal ajax callback for all tracking events triggered via js
642
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
643
644
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
645
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
646
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
647
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
648
649
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
650
651
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
652
653
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
654
655
		/**
656
		 * These actions run checks to load additional files.
657
		 * They check for external files or plugins, so they need to run as late as possible.
658
		 */
659
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
660
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
661
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
662
663
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
664
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
665
666
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
667
668
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
669
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
670
671
		// A filter to control all just in time messages
672
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
673
674
		/**
675
		 * This is the hack to concatinate all css files into one.
676
		 * For description and reasoning see the implode_frontend_css method
677
		 *
678
		 * Super late priority so we catch all the registered styles
679
		 */
680
		if( !is_admin() ) {
681
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
682
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
683
		}
684
685
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
686
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
687
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
688
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
689
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
690
691
	}
692
693
	/*
694
	 * Make sure any site icon added to core can get
695
	 * synced back to dotcom, so we can display it there.
696
	 */
697
	function jetpack_sync_core_icon() {
698
		if ( function_exists( 'get_site_icon_url' ) ) {
699
			$url = get_site_icon_url();
700
		} else {
701
			return;
702
		}
703
704
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
705
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
706
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
707
			// This is the option that is synced with dotcom
708
			Jetpack_Options::update_option( 'site_icon_url', $url );
709
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
710
			Jetpack_Options::delete_option( 'site_icon_url' );
711
		}
712
	}
713
714
	function jetpack_admin_ajax_tracks_callback() {
715
		// Check for nonce
716
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
717
			wp_die( 'Permissions check failed.' );
718
		}
719
720
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
721
			wp_die( 'No valid event name or type.' );
722
		}
723
724
		$tracks_data = array();
725
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
726
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
727
		}
728
729
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
730
		wp_send_json_success();
731
		wp_die();
732
	}
733
734
	function jetpack_admin_ajax_callback() {
735
		// Check for nonce
736 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
737
			wp_die( 'permissions check failed' );
738
		}
739
740
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
741
			$slug = $_REQUEST['thisModuleSlug'];
742
743
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
744
				wp_die( 'That is not a Jetpack module slug' );
745
			}
746
747
			if ( Jetpack::is_module_active( $slug ) ) {
748
				Jetpack::deactivate_module( $slug );
749
			} else {
750
				Jetpack::activate_module( $slug, false, false );
751
			}
752
753
			$modules = Jetpack_Admin::init()->get_modules();
754
			echo json_encode( $modules[ $slug ] );
755
756
			exit;
757
		}
758
759
		wp_die();
760
	}
761
762
	/*
763
	 * Sometimes we need to refresh the data,
764
	 * especially if the page is visited via a 'history'
765
	 * event like back/forward
766
	 */
767
	function jetpack_admin_ajax_refresh_data() {
768
		// Check for nonce
769 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
770
			wp_die( 'permissions check failed' );
771
		}
772
773
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
774
			$modules = Jetpack_Admin::init()->get_modules();
775
			echo json_encode( $modules );
776
			exit;
777
		}
778
779
		wp_die();
780
	}
781
782
	/**
783
	 * The callback for the Jump Start ajax requests.
784
	 */
785
	function jetpack_jumpstart_ajax_callback() {
786
		// Check for nonce
787
		if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
788
			wp_die( 'permissions check failed' );
789
790
		if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
791
			// Update the jumpstart option
792
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
793
				Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
794
			}
795
796
			// Loops through the requested "Jump Start" modules, and activates them.
797
			// Custom 'no_message' state, so that no message will be shown on reload.
798
			$modules = $_REQUEST['jumpstartModSlug'];
799
			$module_slugs = array();
800
			foreach( $modules as $module => $value ) {
801
				$module_slugs[] = $value['module_slug'];
802
			}
803
804
			// Check for possible conflicting plugins
805
			$module_slugs_filtered = $this->filter_default_modules( $module_slugs );
806
807
			foreach ( $module_slugs_filtered as $module_slug ) {
808
				Jetpack::log( 'activate', $module_slug );
809
				Jetpack::activate_module( $module_slug, false, false );
810
				Jetpack::state( 'message', 'no_message' );
811
			}
812
813
			// Set the default sharing buttons and set to display on posts if none have been set.
814
			$sharing_services = get_option( 'sharing-services' );
815
			$sharing_options  = get_option( 'sharing-options' );
816
			if ( empty( $sharing_services['visible'] ) ) {
817
				// Default buttons to set
818
				$visible = array(
819
					'twitter',
820
					'facebook',
821
					'google-plus-1',
822
				);
823
				$hidden = array();
824
825
				// Set some sharing settings
826
				$sharing = new Sharing_Service();
827
				$sharing_options['global'] = array(
828
					'button_style'  => 'icon',
829
					'sharing_label' => $sharing->default_sharing_label,
830
					'open_links'    => 'same',
831
					'show'          => array( 'post' ),
832
					'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
833
				);
834
835
				update_option( 'sharing-options', $sharing_options );
836
837
				// Send a success response so that we can display an error message.
838
				$success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
839
				echo json_encode( $success );
840
				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...
841
			}
842
843
		} elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
844
			// If dismissed, flag the jumpstart option as such.
845
			// Send a success response so that we can display an error message.
846
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
847
				$success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
848
				echo json_encode( $success );
849
				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...
850
			}
851
852
		} elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
853
854
			// FOR TESTING ONLY
855
			// @todo remove
856
			$modules = (array) $_REQUEST['jumpstartModSlug'];
857
			foreach( $modules as $module => $value ) {
858
				if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
859
					Jetpack::log( 'deactivate', $value['module_slug'] );
860
					Jetpack::deactivate_module( $value['module_slug'] );
861
					Jetpack::state( 'message', 'no_message' );
862
				} else {
863
					Jetpack::log( 'activate', $value['module_slug'] );
864
					Jetpack::activate_module( $value['module_slug'], false, false );
865
					Jetpack::state( 'message', 'no_message' );
866
				}
867
			}
868
869
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
870
			echo "reload the page";
871
		}
872
873
		wp_die();
874
	}
875
876
	/**
877
	 * The callback for the JITM ajax requests.
878
	 */
879
	function jetpack_jitm_ajax_callback() {
880
		// Check for nonce
881
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
882
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
883
		}
884
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
885
			$module_slug = $_REQUEST['jitmModule'];
886
			Jetpack::log( 'activate', $module_slug );
887
			Jetpack::activate_module( $module_slug, false, false );
888
			Jetpack::state( 'message', 'no_message' );
889
890
			//A Jetpack module is being activated through a JITM, track it
891
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
892
			$this->do_stats( 'server_side' );
893
894
			wp_send_json_success();
895
		}
896
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
897
			// get the hide_jitm options array
898
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
899
			$module_slug = $_REQUEST['jitmModule'];
900
901
			if( ! $jetpack_hide_jitm ) {
902
				$jetpack_hide_jitm = array(
903
					$module_slug => 'hide'
904
				);
905
			} else {
906
				$jetpack_hide_jitm[$module_slug] = 'hide';
907
			}
908
909
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
910
911
			//jitm is being dismissed forever, track it
912
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
913
			$this->do_stats( 'server_side' );
914
915
			wp_send_json_success();
916
		}
917 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
918
			$module_slug = $_REQUEST['jitmModule'];
919
920
			// User went to WordPress.com, track this
921
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
922
			$this->do_stats( 'server_side' );
923
924
			wp_send_json_success();
925
		}
926 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
927
			$track = $_REQUEST['jitmModule'];
928
929
			// User is viewing JITM, track it.
930
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
931
			$this->do_stats( 'server_side' );
932
933
			wp_send_json_success();
934
		}
935
	}
936
937
	/**
938
	 * If there are any stats that need to be pushed, but haven't been, push them now.
939
	 */
940
	function __destruct() {
941
		if ( ! empty( $this->stats ) ) {
942
			$this->do_stats( 'server_side' );
943
		}
944
	}
945
946
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
947
		switch( $cap ) {
948
			case 'jetpack_connect' :
949
			case 'jetpack_reconnect' :
950
				if ( Jetpack::is_development_mode() ) {
951
					$caps = array( 'do_not_allow' );
952
					break;
953
				}
954
				/**
955
				 * Pass through. If it's not development mode, these should match disconnect.
956
				 * Let users disconnect if it's development mode, just in case things glitch.
957
				 */
958
			case 'jetpack_disconnect' :
959
				/**
960
				 * In multisite, can individual site admins manage their own connection?
961
				 *
962
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
963
				 */
964
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
965
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
966
						/**
967
						 * We need to update the option name -- it's terribly unclear which
968
						 * direction the override goes.
969
						 *
970
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
971
						 */
972
						$caps = array( 'do_not_allow' );
973
						break;
974
					}
975
				}
976
977
				$caps = array( 'manage_options' );
978
				break;
979
			case 'jetpack_manage_modules' :
980
			case 'jetpack_activate_modules' :
981
			case 'jetpack_deactivate_modules' :
982
				$caps = array( 'manage_options' );
983
				break;
984
			case 'jetpack_configure_modules' :
985
				$caps = array( 'manage_options' );
986
				break;
987
			case 'jetpack_network_admin_page':
988
			case 'jetpack_network_settings_page':
989
				$caps = array( 'manage_network_plugins' );
990
				break;
991
			case 'jetpack_network_sites_page':
992
				$caps = array( 'manage_sites' );
993
				break;
994
			case 'jetpack_admin_page' :
995
				if ( Jetpack::is_development_mode() ) {
996
					$caps = array( 'manage_options' );
997
					break;
998
				}
999
1000
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
1001
				if ( ! current_user_can( 'edit_posts' ) ) {
1002
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
1003
						// We need this in order to unlink the user.
1004
						$this->admin_page_load();
1005
					}
1006
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
1007
						$caps = array( 'do_not_allow' );
1008
						break;
1009
					}
1010
				}
1011
1012
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
1013
					$caps = array( 'do_not_allow' );
1014
					break;
1015
				}
1016
				/**
1017
				 * Pass through. If it's not development mode, these should match the admin page.
1018
				 * Let users disconnect if it's development mode, just in case things glitch.
1019
				 */
1020
			case 'jetpack_connect_user' :
1021
				if ( Jetpack::is_development_mode() ) {
1022
					$caps = array( 'do_not_allow' );
1023
					break;
1024
				}
1025
				$caps = array( 'read' );
1026
				break;
1027
		}
1028
		return $caps;
1029
	}
1030
1031
	function require_jetpack_authentication() {
1032
		// Don't let anyone authenticate
1033
		$_COOKIE = array();
1034
		remove_all_filters( 'authenticate' );
1035
1036
		/**
1037
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
1038
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
1039
		 * generate false-positives.
1040
		 */
1041
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
1042
1043
		if ( Jetpack::is_active() ) {
1044
			// Allow Jetpack authentication
1045
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1046
		}
1047
	}
1048
1049
	/**
1050
	 * Load language files
1051
	 */
1052
	public static function plugin_textdomain() {
1053
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1054
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1055
	}
1056
1057
	/**
1058
	 * Register assets for use in various modules and the Jetpack admin page.
1059
	 *
1060
	 * @uses wp_script_is, wp_register_script, plugins_url
1061
	 * @action wp_loaded
1062
	 * @return null
1063
	 */
1064
	public function register_assets() {
1065
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1066
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
1067
		}
1068
1069
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1070
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
1071
		}
1072
1073 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1074
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
1075
		}
1076
1077
		/**
1078
		 * As jetpack_register_genericons is by default fired off a hook,
1079
		 * the hook may have already fired by this point.
1080
		 * So, let's just trigger it manually.
1081
		 */
1082
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1083
		jetpack_register_genericons();
1084
1085 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1086
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1087
	}
1088
1089
	/**
1090
	 * Device Pixels support
1091
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1092
	 */
1093
	function devicepx() {
1094
		if ( Jetpack::is_active() ) {
1095
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
1096
		}
1097
	}
1098
1099
	/*
1100
	 * Returns the location of Jetpack's lib directory. This filter is applied
1101
	 * in require_lib().
1102
	 *
1103
	 * @filter require_lib_dir
1104
	 */
1105
	function require_lib_dir() {
1106
		return JETPACK__PLUGIN_DIR . '_inc/lib';
1107
	}
1108
1109
	/**
1110
	 * Return the network_site_url so that .com knows what network this site is a part of.
1111
	 * @param  bool $option
1112
	 * @return string
1113
	 */
1114
	public function jetpack_main_network_site_option( $option ) {
1115
		return network_site_url();
1116
	}
1117
	/**
1118
	 * Network Name.
1119
	 */
1120
	static function network_name( $option = null ) {
1121
		global $current_site;
1122
		return $current_site->site_name;
1123
	}
1124
	/**
1125
	 * Does the network allow new user and site registrations.
1126
	 * @return string
1127
	 */
1128
	static function network_allow_new_registrations( $option = null ) {
1129
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1130
	}
1131
	/**
1132
	 * Does the network allow admins to add new users.
1133
	 * @return boolian
1134
	 */
1135
	static function network_add_new_users( $option = null ) {
1136
		return (bool) get_site_option( 'add_new_users' );
1137
	}
1138
	/**
1139
	 * File upload psace left per site in MB.
1140
	 *  -1 means NO LIMIT.
1141
	 * @return number
1142
	 */
1143
	static function network_site_upload_space( $option = null ) {
1144
		// value in MB
1145
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1146
	}
1147
1148
	/**
1149
	 * Network allowed file types.
1150
	 * @return string
1151
	 */
1152
	static function network_upload_file_types( $option = null ) {
1153
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1154
	}
1155
1156
	/**
1157
	 * Maximum file upload size set by the network.
1158
	 * @return number
1159
	 */
1160
	static function network_max_upload_file_size( $option = null ) {
1161
		// value in KB
1162
		return get_site_option( 'fileupload_maxk', 300 );
1163
	}
1164
1165
	/**
1166
	 * Lets us know if a site allows admins to manage the network.
1167
	 * @return array
1168
	 */
1169
	static function network_enable_administration_menus( $option = null ) {
1170
		return get_site_option( 'menu_items' );
1171
	}
1172
1173
	/**
1174
	 * Return whether we are dealing with a multi network setup or not.
1175
	 * The reason we are type casting this is because we want to avoid the situation where
1176
	 * the result is false since when is_main_network_option return false it cases
1177
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1178
	 * database which could be set to anything as opposed to what this function returns.
1179
	 * @param  bool  $option
1180
	 *
1181
	 * @return boolean
1182
	 */
1183
	public function is_main_network_option( $option ) {
1184
		// return '1' or ''
1185
		return (string) (bool) Jetpack::is_multi_network();
1186
	}
1187
1188
	/**
1189
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1190
	 *
1191
	 * @param  string  $option
1192
	 * @return boolean
1193
	 */
1194
	public function is_multisite( $option ) {
1195
		return (string) (bool) is_multisite();
1196
	}
1197
1198
	/**
1199
	 * Implemented since there is no core is multi network function
1200
	 * Right now there is no way to tell if we which network is the dominant network on the system
1201
	 *
1202
	 * @since  3.3
1203
	 * @return boolean
1204
	 */
1205
	public static function is_multi_network() {
1206
		global  $wpdb;
1207
1208
		// if we don't have a multi site setup no need to do any more
1209
		if ( ! is_multisite() ) {
1210
			return false;
1211
		}
1212
1213
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1214
		if ( $num_sites > 1 ) {
1215
			return true;
1216
		} else {
1217
			return false;
1218
		}
1219
	}
1220
1221
	/**
1222
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1223
	 * @return null
1224
	 */
1225
	function update_jetpack_main_network_site_option() {
1226
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1227
		/**
1228
		 * Fires when the site URL is updated.
1229
		 * Determines if the site is the main site of a Mulitiste network.
1230
		 *
1231
		 * @since 3.3.0
1232
		 *
1233
		 * @param string jetpack_main_network_site.
1234
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1235
		 */
1236
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1237
		/**
1238
		 * Fires when the site URL is updated.
1239
		 * Determines if the is part of a multi network.
1240
		 *
1241
		 * @since 3.3.0
1242
		 *
1243
		 * @param string jetpack_is_main_network.
1244
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1245
		 */
1246
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1247
		/**
1248
		 * Fires when the site URL is updated.
1249
		 * Determines if the site is part of a multisite network.
1250
		 *
1251
		 * @since 3.4.0
1252
		 *
1253
		 * @param string jetpack_is_multi_site.
1254
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1255
		 */
1256
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1257
	}
1258
	/**
1259
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1260
	 *
1261
	 */
1262
	function update_jetpack_network_settings() {
1263
		// Only sync this info for the main network site.
1264
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1265
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1266
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1267
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1268
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1269
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1270
1271
	}
1272
1273
	/**
1274
	 * Get back if the current site is single user site.
1275
	 *
1276
	 * @return bool
1277
	 */
1278
	public static function is_single_user_site() {
1279
1280
		$user_query = new WP_User_Query( array(
1281
			'blog_id' => get_current_blog_id(),
1282
			'fields'  => 'ID',
1283
			'number' => 2
1284
		) );
1285
		return 1 === (int) $user_query->get_total();
1286
	}
1287
1288
	/**
1289
	 * Returns true if the site has file write access false otherwise.
1290
	 * @return string ( '1' | '0' )
1291
	 **/
1292
	public static function file_system_write_access() {
1293
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1294
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1295
		}
1296
1297
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1298
1299
		$filesystem_method = get_filesystem_method();
1300
		if ( $filesystem_method === 'direct' ) {
1301
			return 1;
1302
		}
1303
1304
		ob_start();
1305
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1306
		ob_end_clean();
1307
		if ( $filesystem_credentials_are_stored ) {
1308
			return 1;
1309
		}
1310
		return 0;
1311
	}
1312
1313
	/**
1314
	 * Finds out if a site is using a version control system.
1315
	 * @return string ( '1' | '0' )
1316
	 **/
1317
	public static function is_version_controlled() {
1318
1319
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1320
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1321
		}
1322
		$updater = new WP_Automatic_Updater();
1323
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1324
		// transients should not be empty
1325
		if ( empty( $is_version_controlled ) ) {
1326
			$is_version_controlled = '0';
1327
		}
1328
		return $is_version_controlled;
1329
	}
1330
1331
	/**
1332
	 * Determines whether the current theme supports featured images or not.
1333
	 * @return string ( '1' | '0' )
1334
	 */
1335
	public static function featured_images_enabled() {
1336
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1337
	}
1338
1339
	/*
1340
	 * Sync back wp_version
1341
	 */
1342
	public static function get_wp_version() {
1343
		global $wp_version;
1344
		return $wp_version;
1345
	}
1346
1347
	/**
1348
	 * Keeps wp_version in sync with .com when WordPress core updates
1349
	 **/
1350
	public static function update_get_wp_version( $update, $meta_data ) {
1351
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1352
			/** This action is documented in wp-includes/option.php */
1353
			/**
1354
			 * This triggers the sync for the jetpack version
1355
			 * See Jetpack_Sync options method for more info.
1356
			 */
1357
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1358
		}
1359
	}
1360
1361
	/**
1362
	 * Triggers a sync of update counts and update details
1363
	 */
1364
	function sync_update_data() {
1365
		// Anytime WordPress saves update data, we'll want to sync update data
1366
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1367
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1368
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1369
		// Anytime a connection to jetpack is made, sync the update data
1370
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1371
		// Anytime the Jetpack Version changes, sync the the update data
1372
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1373
1374
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1375
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1376
		}
1377
1378
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1379
	}
1380
1381
	/**
1382
	 * Triggers a sync of information specific to the current theme.
1383
	 */
1384
	function sync_theme_data() {
1385
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1386
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1387
	}
1388
1389
	/**
1390
	 * jetpack_updates is saved in the following schema:
1391
	 *
1392
	 * array (
1393
	 *      'plugins'                       => (int) Number of plugin updates available.
1394
	 *      'themes'                        => (int) Number of theme updates available.
1395
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1396
	 *      'translations'                  => (int) Number of translation updates available.
1397
	 *      'total'                         => (int) Total of all available updates.
1398
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1399
	 * )
1400
	 * @return array
1401
	 */
1402
	public static function get_updates() {
1403
		$update_data = wp_get_update_data();
1404
1405
		// Stores the individual update counts as well as the total count.
1406
		if ( isset( $update_data['counts'] ) ) {
1407
			$updates = $update_data['counts'];
1408
		}
1409
1410
		// If we need to update WordPress core, let's find the latest version number.
1411 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1412
			$cur = get_preferred_from_update_core();
1413
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1414
				$updates['wp_update_version'] = $cur->current;
1415
			}
1416
		}
1417
		return isset( $updates ) ? $updates : array();
1418
	}
1419
1420
	public static function get_update_details() {
1421
		$update_details = array(
1422
			'update_core' => get_site_transient( 'update_core' ),
1423
			'update_plugins' => get_site_transient( 'update_plugins' ),
1424
			'update_themes' => get_site_transient( 'update_themes' ),
1425
		);
1426
		return $update_details;
1427
	}
1428
1429
	public static function refresh_update_data() {
1430
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1431
			/**
1432
			 * Fires whenever the amount of updates needed for a site changes.
1433
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1434
			 *
1435
			 * @since 3.7.0
1436
			 *
1437
			 * @param string jetpack_updates
1438
			 * @param array Update counts calculated by Jetpack::get_updates
1439
			 */
1440
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1441
		}
1442
		/**
1443
		 * Fires whenever the amount of updates needed for a site changes.
1444
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1445
		 *
1446
		 * @since 3.7.0
1447
		 *
1448
		 * @param string jetpack_update_details
1449
		 * @param array Update details calculated by Jetpack::get_update_details
1450
		 */
1451
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1452
	}
1453
1454
	public static function refresh_theme_data() {
1455
		/**
1456
		 * Fires whenever a theme change is made.
1457
		 *
1458
		 * @since 3.8.1
1459
		 *
1460
		 * @param string featured_images_enabled
1461
		 * @param boolean Whether featured images are enabled or not
1462
		 */
1463
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1464
	}
1465
1466
	/**
1467
	 * Invalides the transient as well as triggers the update of the mock option.
1468
	 *
1469
	 * @return null
1470
	 */
1471
	function is_single_user_site_invalidate() {
1472
		/**
1473
		 * Fires when a user is added or removed from a site.
1474
		 * Determines if the site is a single user site.
1475
		 *
1476
		 * @since 3.4.0
1477
		 *
1478
		 * @param string jetpack_single_user_site.
1479
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1480
		 */
1481
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1482
	}
1483
1484
	/**
1485
	 * Is Jetpack active?
1486
	 */
1487
	public static function is_active() {
1488
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1489
	}
1490
1491
	/**
1492
	 * Is Jetpack in development (offline) mode?
1493
	 */
1494
	public static function is_development_mode() {
1495
		$development_mode = false;
1496
1497
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1498
			$development_mode = JETPACK_DEV_DEBUG;
1499
		}
1500
1501
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1502
			$development_mode = true;
1503
		}
1504
		/**
1505
		 * Filters Jetpack's development mode.
1506
		 *
1507
		 * @see http://jetpack.me/support/development-mode/
1508
		 *
1509
		 * @since 2.2.1
1510
		 *
1511
		 * @param bool $development_mode Is Jetpack's development mode active.
1512
		 */
1513
		return apply_filters( 'jetpack_development_mode', $development_mode );
1514
	}
1515
1516
	/**
1517
	* Get Jetpack development mode notice text and notice class.
1518
	*
1519
	* Mirrors the checks made in Jetpack::is_development_mode
1520
	*
1521
	*/
1522
	public static function show_development_mode_notice() {
1523
		if ( Jetpack::is_development_mode() ) {
1524
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1525
				$notice = sprintf(
1526
					/* translators: %s is a URL */
1527
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1528
					'http://jetpack.me/support/development-mode/'
1529
				);
1530
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1531
				$notice = sprintf(
1532
					/* translators: %s is a URL */
1533
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1534
					'http://jetpack.me/support/development-mode/'
1535
				);
1536
			} else {
1537
				$notice = sprintf(
1538
					/* translators: %s is a URL */
1539
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1540
					'http://jetpack.me/support/development-mode/'
1541
				);
1542
			}
1543
1544
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1545
		}
1546
1547
		// Throw up a notice if using a development version and as for feedback.
1548
		if ( Jetpack::is_development_version() ) {
1549
			/* translators: %s is a URL */
1550
			$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/' );
1551
1552
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1553
		}
1554
		// Throw up a notice if using staging mode
1555
		if ( Jetpack::is_staging_site() ) {
1556
			/* translators: %s is a URL */
1557
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.me/support/staging-sites/' );
1558
1559
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1560
		}
1561
	}
1562
1563
	/**
1564
	 * Whether Jetpack's version maps to a public release, or a development version.
1565
	 */
1566
	public static function is_development_version() {
1567
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1568
	}
1569
1570
	/**
1571
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1572
	 */
1573
	public static function is_user_connected( $user_id = false ) {
1574
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1575
		if ( ! $user_id ) {
1576
			return false;
1577
		}
1578
		return (bool) Jetpack_Data::get_access_token( $user_id );
1579
	}
1580
1581
	/**
1582
	 * Get the wpcom user data of the current|specified connected user.
1583
	 */
1584 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1585
		if ( ! $user_id ) {
1586
			$user_id = get_current_user_id();
1587
		}
1588
		Jetpack::load_xml_rpc_client();
1589
		$xml = new Jetpack_IXR_Client( array(
1590
			'user_id' => $user_id,
1591
		) );
1592
		$xml->query( 'wpcom.getUser' );
1593
		if ( ! $xml->isError() ) {
1594
			return $xml->getResponse();
1595
		}
1596
		return false;
1597
	}
1598
1599
	/**
1600
	 * Get the wpcom email of the current|specified connected user.
1601
	 */
1602 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1603
		if ( ! $user_id ) {
1604
			$user_id = get_current_user_id();
1605
		}
1606
		Jetpack::load_xml_rpc_client();
1607
		$xml = new Jetpack_IXR_Client( array(
1608
			'user_id' => $user_id,
1609
		) );
1610
		$xml->query( 'wpcom.getUserEmail' );
1611
		if ( ! $xml->isError() ) {
1612
			return $xml->getResponse();
1613
		}
1614
		return false;
1615
	}
1616
1617
	/**
1618
	 * Get the wpcom email of the master user.
1619
	 */
1620
	public static function get_master_user_email() {
1621
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1622
		if ( $master_user_id ) {
1623
			return self::get_connected_user_email( $master_user_id );
1624
		}
1625
		return '';
1626
	}
1627
1628
	function current_user_is_connection_owner() {
1629
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1630
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1631
	}
1632
1633
	/**
1634
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1635
	 */
1636
	function extra_oembed_providers() {
1637
		// Cloudup: https://dev.cloudup.com/#oembed
1638
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1639
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1640
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1641
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1642
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1643
	}
1644
1645
	/**
1646
	 * Synchronize connected user role changes
1647
	 */
1648
	function user_role_change( $user_id ) {
1649
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1650
			$current_user_id = get_current_user_id();
1651
			wp_set_current_user( $user_id );
1652
			$role = $this->translate_current_user_to_role();
1653
			$signed_role = $this->sign_role( $role );
1654
			wp_set_current_user( $current_user_id );
1655
1656
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1657
			$master_user_id = absint( $master_token->external_user_id );
1658
1659
			if ( ! $master_user_id )
1660
				return; // this shouldn't happen
1661
1662
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1663
			//@todo retry on failure
1664
1665
			//try to choose a new master if we're demoting the current one
1666
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1667
				$query = new WP_User_Query(
1668
					array(
1669
						'fields'  => array( 'id' ),
1670
						'role'    => 'administrator',
1671
						'orderby' => 'id',
1672
						'exclude' => array( $master_user_id ),
1673
					)
1674
				);
1675
				$new_master = false;
1676
				foreach ( $query->results as $result ) {
1677
					$uid = absint( $result->id );
1678
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1679
						$new_master = $uid;
1680
						break;
1681
					}
1682
				}
1683
1684
				if ( $new_master ) {
1685
					Jetpack_Options::update_option( 'master_user', $new_master );
1686
				}
1687
				// else disconnect..?
1688
			}
1689
		}
1690
	}
1691
1692
	/**
1693
	 * Loads the currently active modules.
1694
	 */
1695
	public static function load_modules() {
1696
		if ( ! self::is_active() && !self::is_development_mode() ) {
1697
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1698
				return;
1699
			}
1700
		}
1701
1702
		$version = Jetpack_Options::get_option( 'version' );
1703 View Code Duplication
		if ( ! $version ) {
1704
			$version = $old_version = JETPACK__VERSION . ':' . time();
1705
			/** This action is documented in class.jetpack.php */
1706
			do_action( 'updating_jetpack_version', $version, false );
1707
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1708
		}
1709
		list( $version ) = explode( ':', $version );
1710
1711
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1712
1713
		$modules_data = array();
1714
1715
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1716
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1717
			$updated_modules = array();
1718
			foreach ( $modules as $module ) {
1719
				$modules_data[ $module ] = Jetpack::get_module( $module );
1720
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1721
					continue;
1722
				}
1723
1724
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1725
					continue;
1726
				}
1727
1728
				$updated_modules[] = $module;
1729
			}
1730
1731
			$modules = array_diff( $modules, $updated_modules );
1732
		}
1733
1734
		$is_development_mode = Jetpack::is_development_mode();
1735
1736
		foreach ( $modules as $index => $module ) {
1737
			// If we're in dev mode, disable modules requiring a connection
1738
			if ( $is_development_mode ) {
1739
				// Prime the pump if we need to
1740
				if ( empty( $modules_data[ $module ] ) ) {
1741
					$modules_data[ $module ] = Jetpack::get_module( $module );
1742
				}
1743
				// If the module requires a connection, but we're in local mode, don't include it.
1744
				if ( $modules_data[ $module ]['requires_connection'] ) {
1745
					continue;
1746
				}
1747
			}
1748
1749
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1750
				continue;
1751
			}
1752
1753
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1754
				unset( $modules[ $index ] );
1755
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1756
				continue;
1757
			}
1758
1759
			/**
1760
			 * Fires when a specific module is loaded.
1761
			 * The dynamic part of the hook, $module, is the module slug.
1762
			 *
1763
			 * @since 1.1.0
1764
			 */
1765
			do_action( 'jetpack_module_loaded_' . $module );
1766
		}
1767
1768
		/**
1769
		 * Fires when all the modules are loaded.
1770
		 *
1771
		 * @since 1.1.0
1772
		 */
1773
		do_action( 'jetpack_modules_loaded' );
1774
1775
		// 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.
1776
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1777
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1778
	}
1779
1780
	/**
1781
	 * Check if Jetpack's REST API compat file should be included
1782
	 * @action plugins_loaded
1783
	 * @return null
1784
	 */
1785
	public function check_rest_api_compat() {
1786
		/**
1787
		 * Filters the list of REST API compat files to be included.
1788
		 *
1789
		 * @since 2.2.5
1790
		 *
1791
		 * @param array $args Array of REST API compat files to include.
1792
		 */
1793
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1794
1795
		if ( function_exists( 'bbpress' ) )
1796
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1797
1798
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1799
			require_once $_jetpack_rest_api_compat_include;
1800
	}
1801
1802
	/**
1803
	 * Gets all plugins currently active in values, regardless of whether they're
1804
	 * traditionally activated or network activated.
1805
	 *
1806
	 * @todo Store the result in core's object cache maybe?
1807
	 */
1808
	public static function get_active_plugins() {
1809
		$active_plugins = (array) get_option( 'active_plugins', array() );
1810
1811
		if ( is_multisite() ) {
1812
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1813
			// whereas active_plugins stores them in the values.
1814
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1815
			if ( $network_plugins ) {
1816
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1817
			}
1818
		}
1819
1820
		sort( $active_plugins );
1821
1822
		return array_unique( $active_plugins );
1823
	}
1824
1825
	/**
1826
	 * Gets and parses additional plugin data to send with the heartbeat data
1827
	 *
1828
	 * @since 3.8.1
1829
	 *
1830
	 * @return array Array of plugin data
1831
	 */
1832
	public static function get_parsed_plugin_data() {
1833
		if ( ! function_exists( 'get_plugins' ) ) {
1834
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1835
		}
1836
		$all_plugins    = get_plugins();
1837
		$active_plugins = Jetpack::get_active_plugins();
1838
1839
		$plugins = array();
1840
		foreach ( $all_plugins as $path => $plugin_data ) {
1841
			$plugins[ $path ] = array(
1842
					'is_active' => in_array( $path, $active_plugins ),
1843
					'file'      => $path,
1844
					'name'      => $plugin_data['Name'],
1845
					'version'   => $plugin_data['Version'],
1846
					'author'    => $plugin_data['Author'],
1847
			);
1848
		}
1849
1850
		return $plugins;
1851
	}
1852
1853
	/**
1854
	 * Gets and parses theme data to send with the heartbeat data
1855
	 *
1856
	 * @since 3.8.1
1857
	 *
1858
	 * @return array Array of theme data
1859
	 */
1860
	public static function get_parsed_theme_data() {
1861
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1862
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1863
1864
		$themes = array();
1865
		foreach ( $all_themes as $slug => $theme_data ) {
1866
			$theme_headers = array();
1867
			foreach ( $header_keys as $header_key ) {
1868
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1869
			}
1870
1871
			$themes[ $slug ] = array(
1872
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1873
					'slug' => $slug,
1874
					'theme_root' => $theme_data->get_theme_root_uri(),
1875
					'parent' => $theme_data->parent(),
1876
					'headers' => $theme_headers
1877
			);
1878
		}
1879
1880
		return $themes;
1881
	}
1882
1883
	/**
1884
	 * Checks whether a specific plugin is active.
1885
	 *
1886
	 * We don't want to store these in a static variable, in case
1887
	 * there are switch_to_blog() calls involved.
1888
	 */
1889
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1890
		return in_array( $plugin, self::get_active_plugins() );
1891
	}
1892
1893
	/**
1894
	 * Check if Jetpack's Open Graph tags should be used.
1895
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1896
	 *
1897
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1898
	 * @action plugins_loaded
1899
	 * @return null
1900
	 */
1901
	public function check_open_graph() {
1902
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1903
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1904
		}
1905
1906
		$active_plugins = self::get_active_plugins();
1907
1908
		if ( ! empty( $active_plugins ) ) {
1909
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1910
				if ( in_array( $plugin, $active_plugins ) ) {
1911
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1912
					break;
1913
				}
1914
			}
1915
		}
1916
1917
		/**
1918
		 * Allow the addition of Open Graph Meta Tags to all pages.
1919
		 *
1920
		 * @since 2.0.3
1921
		 *
1922
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1923
		 */
1924
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1925
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1926
		}
1927
	}
1928
1929
	/**
1930
	 * Check if Jetpack's Twitter tags should be used.
1931
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1932
	 *
1933
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1934
	 * @action plugins_loaded
1935
	 * @return null
1936
	 */
1937
	public function check_twitter_tags() {
1938
1939
		$active_plugins = self::get_active_plugins();
1940
1941
		if ( ! empty( $active_plugins ) ) {
1942
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1943
				if ( in_array( $plugin, $active_plugins ) ) {
1944
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1945
					break;
1946
				}
1947
			}
1948
		}
1949
1950
		/**
1951
		 * Allow Twitter Card Meta tags to be disabled.
1952
		 *
1953
		 * @since 2.6.0
1954
		 *
1955
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1956
		 */
1957
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1958
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1959
		}
1960
	}
1961
1962
1963
1964
1965
	/*
1966
	 *
1967
	 * Jetpack Security Reports
1968
	 *
1969
	 * Allowed types: login_form, backup, file_scanning, spam
1970
	 *
1971
	 * 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)
1972
	 *
1973
	 * 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)
1974
	 *
1975
	 *
1976
	 * Example code to submit a security report:
1977
	 *
1978
	 *  function akismet_submit_jetpack_security_report() {
1979
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1980
	 *  }
1981
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1982
	 *
1983
	 */
1984
1985
1986
	/**
1987
	 * Calls for security report submissions.
1988
	 *
1989
	 * @return null
1990
	 */
1991
	public static function perform_security_reporting() {
1992
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1993
1994
		if ( $no_check_needed ) {
1995
			return;
1996
		}
1997
1998
		/**
1999
		 * Fires before a security report is created.
2000
		 *
2001
		 * @since 3.4.0
2002
		 */
2003
		do_action( 'jetpack_security_report' );
2004
2005
		Jetpack_Options::update_option( 'security_report', self::$security_report );
2006
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
2007
	}
2008
2009
	/**
2010
	 * Allows plugins to submit security reports.
2011
 	 *
2012
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2013
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2014
	 * @param array   $args         See definitions above
2015
	 */
2016
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2017
2018
		if( !doing_action( 'jetpack_security_report' ) ) {
2019
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
2020
		}
2021
2022
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
2023
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
2024
		}
2025
2026
		if( !function_exists( 'get_plugin_data' ) ) {
2027
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
2028
		}
2029
2030
		//Get rid of any non-allowed args
2031
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
2032
2033
		$plugin = get_plugin_data( $plugin_file );
2034
2035
		if ( !$plugin['Name'] ) {
2036
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
2037
		}
2038
2039
		// Sanitize everything to make sure we're not syncing something wonky
2040
		$type = sanitize_key( $type );
2041
2042
		$args['plugin'] = $plugin;
2043
2044
		// Cast blocked, last and next as integers.
2045
		// Last and next should be in unix timestamp format
2046
		if ( isset( $args['blocked'] ) ) {
2047
			$args['blocked'] = (int) $args['blocked'];
2048
		}
2049
		if ( isset( $args['last'] ) ) {
2050
			$args['last'] = (int) $args['last'];
2051
		}
2052
		if ( isset( $args['next'] ) ) {
2053
			$args['next'] = (int) $args['next'];
2054
		}
2055
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
2056
			$args['status'] = 'ok';
2057
		}
2058
		if ( isset( $args['message'] ) ) {
2059
2060
			if( $args['status'] == 'ok' ) {
2061
				unset( $args['message'] );
2062
			}
2063
2064
			$allowed_html = array(
2065
			    'a' => array(
2066
			        'href' => array(),
2067
			        'title' => array()
2068
			    ),
2069
			    'em' => array(),
2070
			    'strong' => array(),
2071
			);
2072
2073
			$args['message'] = wp_kses( $args['message'], $allowed_html );
2074
		}
2075
2076
		$plugin_name = $plugin[ 'Name' ];
2077
2078
		self::$security_report[ $type ][ $plugin_name ] = $args;
2079
	}
2080
2081
	/**
2082
	 * Collects a new report if needed, then returns it.
2083
	 */
2084
	public function get_security_report() {
2085
		self::perform_security_reporting();
2086
		return Jetpack_Options::get_option( 'security_report' );
2087
	}
2088
2089
2090
/* Jetpack Options API */
2091
2092
	public static function get_option_names( $type = 'compact' ) {
2093
		return Jetpack_Options::get_option_names( $type );
2094
	}
2095
2096
	/**
2097
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2098
 	 *
2099
	 * @param string $name    Option name
2100
	 * @param mixed  $default (optional)
2101
	 */
2102
	public static function get_option( $name, $default = false ) {
2103
		return Jetpack_Options::get_option( $name, $default );
2104
	}
2105
2106
	/**
2107
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
2108
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
2109
	* $name must be a registered option name.
2110
	*/
2111
	public static function create_nonce( $name ) {
2112
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
2113
2114
		Jetpack_Options::update_option( $name, $secret );
2115
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
2116
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2117
			return new Jetpack_Error( 'missing_secrets' );
2118
2119
		return array(
2120
			'secret_1' => $secret_1,
2121
			'secret_2' => $secret_2,
2122
			'eol'      => $eol,
2123
		);
2124
	}
2125
2126
	/**
2127
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2128
 	 *
2129
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2130
	 * @param string $name  Option name
2131
	 * @param mixed  $value Option value
2132
	 */
2133
	public static function update_option( $name, $value ) {
2134
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2135
		return Jetpack_Options::update_option( $name, $value );
2136
	}
2137
2138
	/**
2139
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2140
 	 *
2141
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2142
	 * @param array $array array( option name => option value, ... )
2143
	 */
2144
	public static function update_options( $array ) {
2145
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2146
		return Jetpack_Options::update_options( $array );
2147
	}
2148
2149
	/**
2150
	 * Deletes the given option.  May be passed multiple option names as an array.
2151
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2152
	 *
2153
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2154
	 * @param string|array $names
2155
	 */
2156
	public static function delete_option( $names ) {
2157
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2158
		return Jetpack_Options::delete_option( $names );
2159
	}
2160
2161
	/**
2162
	 * Enters a user token into the user_tokens option
2163
	 *
2164
	 * @param int $user_id
2165
	 * @param string $token
2166
	 * return bool
2167
	 */
2168
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2169
		// not designed for concurrent updates
2170
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2171
		if ( ! is_array( $user_tokens ) )
2172
			$user_tokens = array();
2173
		$user_tokens[$user_id] = $token;
2174
		if ( $is_master_user ) {
2175
			$master_user = $user_id;
2176
			$options     = compact( 'user_tokens', 'master_user' );
2177
		} else {
2178
			$options = compact( 'user_tokens' );
2179
		}
2180
		return Jetpack_Options::update_options( $options );
2181
	}
2182
2183
	/**
2184
	 * Returns an array of all PHP files in the specified absolute path.
2185
	 * Equivalent to glob( "$absolute_path/*.php" ).
2186
	 *
2187
	 * @param string $absolute_path The absolute path of the directory to search.
2188
	 * @return array Array of absolute paths to the PHP files.
2189
	 */
2190
	public static function glob_php( $absolute_path ) {
2191
		if ( function_exists( 'glob' ) ) {
2192
			return glob( "$absolute_path/*.php" );
2193
		}
2194
2195
		$absolute_path = untrailingslashit( $absolute_path );
2196
		$files = array();
2197
		if ( ! $dir = @opendir( $absolute_path ) ) {
2198
			return $files;
2199
		}
2200
2201
		while ( false !== $file = readdir( $dir ) ) {
2202
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2203
				continue;
2204
			}
2205
2206
			$file = "$absolute_path/$file";
2207
2208
			if ( ! is_file( $file ) ) {
2209
				continue;
2210
			}
2211
2212
			$files[] = $file;
2213
		}
2214
2215
		closedir( $dir );
2216
2217
		return $files;
2218
	}
2219
2220
	public static function activate_new_modules( $redirect = false ) {
2221
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2222
			return;
2223
		}
2224
2225
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2226 View Code Duplication
		if ( ! $jetpack_old_version ) {
2227
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2228
			/** This action is documented in class.jetpack.php */
2229
			do_action( 'updating_jetpack_version', $version, false );
2230
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2231
		}
2232
2233
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2234
2235
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2236
			return;
2237
		}
2238
2239
		$active_modules     = Jetpack::get_active_modules();
2240
		$reactivate_modules = array();
2241
		foreach ( $active_modules as $active_module ) {
2242
			$module = Jetpack::get_module( $active_module );
2243
			if ( ! isset( $module['changed'] ) ) {
2244
				continue;
2245
			}
2246
2247
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2248
				continue;
2249
			}
2250
2251
			$reactivate_modules[] = $active_module;
2252
			Jetpack::deactivate_module( $active_module );
2253
		}
2254
2255
		$new_version = JETPACK__VERSION . ':' . time();
2256
		/** This action is documented in class.jetpack.php */
2257
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2258
		Jetpack_Options::update_options(
2259
			array(
2260
				'version'     => $new_version,
2261
				'old_version' => $jetpack_old_version,
2262
			)
2263
		);
2264
2265
		Jetpack::state( 'message', 'modules_activated' );
2266
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2267
2268
		if ( $redirect ) {
2269
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2270
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2271
				$page = $_GET['page'];
2272
			}
2273
2274
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2275
			exit;
2276
		}
2277
	}
2278
2279
	/**
2280
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2281
	 * Make sure to tuck away module "library" files in a sub-directory.
2282
	 */
2283
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2284
		static $modules = null;
2285
2286
		if ( ! isset( $modules ) ) {
2287
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2288
			// Use the cache if we're on the front-end and it's available...
2289
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2290
				$modules = $available_modules_option[ JETPACK__VERSION ];
2291
			} else {
2292
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2293
2294
				$modules = array();
2295
2296
				foreach ( $files as $file ) {
2297
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2298
						continue;
2299
					}
2300
2301
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2302
				}
2303
2304
				Jetpack_Options::update_option( 'available_modules', array(
2305
					JETPACK__VERSION => $modules,
2306
				) );
2307
			}
2308
		}
2309
2310
		/**
2311
		 * Filters the array of modules available to be activated.
2312
		 *
2313
		 * @since 2.4.0
2314
		 *
2315
		 * @param array $modules Array of available modules.
2316
		 * @param string $min_version Minimum version number required to use modules.
2317
		 * @param string $max_version Maximum version number required to use modules.
2318
		 */
2319
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2320
2321
		if ( ! $min_version && ! $max_version ) {
2322
			return array_keys( $mods );
2323
		}
2324
2325
		$r = array();
2326
		foreach ( $mods as $slug => $introduced ) {
2327
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2328
				continue;
2329
			}
2330
2331
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2332
				continue;
2333
			}
2334
2335
			$r[] = $slug;
2336
		}
2337
2338
		return $r;
2339
	}
2340
2341
	/**
2342
	 * Default modules loaded on activation.
2343
	 */
2344
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2345
		$return = array();
2346
2347
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2348
			$module_data = Jetpack::get_module( $module );
2349
2350
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2351
				case 'yes' :
2352
					$return[] = $module;
2353
					break;
2354
				case 'public' :
2355
					if ( Jetpack_Options::get_option( 'public' ) ) {
2356
						$return[] = $module;
2357
					}
2358
					break;
2359
				case 'no' :
2360
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2361
					break;
2362
			}
2363
		}
2364
		/**
2365
		 * Filters the array of default modules.
2366
		 *
2367
		 * @since 2.5.0
2368
		 *
2369
		 * @param array $return Array of default modules.
2370
		 * @param string $min_version Minimum version number required to use modules.
2371
		 * @param string $max_version Maximum version number required to use modules.
2372
		 */
2373
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2374
	}
2375
2376
	/**
2377
	 * Checks activated modules during auto-activation to determine
2378
	 * if any of those modules are being deprecated.  If so, close
2379
	 * them out, and add any replacement modules.
2380
	 *
2381
	 * Runs at priority 99 by default.
2382
	 *
2383
	 * This is run late, so that it can still activate a module if
2384
	 * the new module is a replacement for another that the user
2385
	 * currently has active, even if something at the normal priority
2386
	 * would kibosh everything.
2387
	 *
2388
	 * @since 2.6
2389
	 * @uses jetpack_get_default_modules filter
2390
	 * @param array $modules
2391
	 * @return array
2392
	 */
2393
	function handle_deprecated_modules( $modules ) {
2394
		$deprecated_modules = array(
2395
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2396
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2397
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2398
		);
2399
2400
		// Don't activate SSO if they never completed activating WPCC.
2401
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2402
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2403
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2404
				$deprecated_modules['wpcc'] = null;
2405
			}
2406
		}
2407
2408
		foreach ( $deprecated_modules as $module => $replacement ) {
2409
			if ( Jetpack::is_module_active( $module ) ) {
2410
				self::deactivate_module( $module );
2411
				if ( $replacement ) {
2412
					$modules[] = $replacement;
2413
				}
2414
			}
2415
		}
2416
2417
		return array_unique( $modules );
2418
	}
2419
2420
	/**
2421
	 * Checks activated plugins during auto-activation to determine
2422
	 * if any of those plugins are in the list with a corresponding module
2423
	 * that is not compatible with the plugin. The module will not be allowed
2424
	 * to auto-activate.
2425
	 *
2426
	 * @since 2.6
2427
	 * @uses jetpack_get_default_modules filter
2428
	 * @param array $modules
2429
	 * @return array
2430
	 */
2431
	function filter_default_modules( $modules ) {
2432
2433
		$active_plugins = self::get_active_plugins();
2434
2435
		if ( ! empty( $active_plugins ) ) {
2436
2437
			// For each module we'd like to auto-activate...
2438
			foreach ( $modules as $key => $module ) {
2439
				// If there are potential conflicts for it...
2440
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2441
					// For each potential conflict...
2442
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2443
						// If that conflicting plugin is active...
2444
						if ( in_array( $plugin, $active_plugins ) ) {
2445
							// Remove that item from being auto-activated.
2446
							unset( $modules[ $key ] );
2447
						}
2448
					}
2449
				}
2450
			}
2451
		}
2452
2453
		return $modules;
2454
	}
2455
2456
	/**
2457
	 * Extract a module's slug from its full path.
2458
	 */
2459
	public static function get_module_slug( $file ) {
2460
		return str_replace( '.php', '', basename( $file ) );
2461
	}
2462
2463
	/**
2464
	 * Generate a module's path from its slug.
2465
	 */
2466
	public static function get_module_path( $slug ) {
2467
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2468
	}
2469
2470
	/**
2471
	 * Load module data from module file. Headers differ from WordPress
2472
	 * plugin headers to avoid them being identified as standalone
2473
	 * plugins on the WordPress plugins page.
2474
	 */
2475
	public static function get_module( $module ) {
2476
		$headers = array(
2477
			'name'                      => 'Module Name',
2478
			'description'               => 'Module Description',
2479
			'jumpstart_desc'            => 'Jumpstart Description',
2480
			'sort'                      => 'Sort Order',
2481
			'recommendation_order'      => 'Recommendation Order',
2482
			'introduced'                => 'First Introduced',
2483
			'changed'                   => 'Major Changes In',
2484
			'deactivate'                => 'Deactivate',
2485
			'free'                      => 'Free',
2486
			'requires_connection'       => 'Requires Connection',
2487
			'auto_activate'             => 'Auto Activate',
2488
			'module_tags'               => 'Module Tags',
2489
			'feature'                   => 'Feature',
2490
			'additional_search_queries' => 'Additional Search Queries',
2491
		);
2492
2493
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2494
2495
		$mod = Jetpack::get_file_data( $file, $headers );
2496
		if ( empty( $mod['name'] ) ) {
2497
			return false;
2498
		}
2499
2500
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2501
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2502
		$mod['deactivate']              = empty( $mod['deactivate'] );
2503
		$mod['free']                    = empty( $mod['free'] );
2504
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2505
2506
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2507
			$mod['auto_activate'] = 'No';
2508
		} else {
2509
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2510
		}
2511
2512
		if ( $mod['module_tags'] ) {
2513
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2514
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2515
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2516
		} else {
2517
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2518
		}
2519
2520
		if ( $mod['feature'] ) {
2521
			$mod['feature'] = explode( ',', $mod['feature'] );
2522
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2523
		} else {
2524
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2525
		}
2526
2527
		/**
2528
		 * Filters the feature array on a module.
2529
		 *
2530
		 * This filter allows you to control where each module is filtered: Recommended,
2531
		 * Jumpstart, and the default "Other" listing.
2532
		 *
2533
		 * @since 3.5.0
2534
		 *
2535
		 * @param array   $mod['feature'] The areas to feature this module:
2536
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2537
		 *     'Recommended' shows on the main Jetpack admin screen.
2538
		 *     'Other' should be the default if no other value is in the array.
2539
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2540
		 * @param array   $mod All the currently assembled module data.
2541
		 */
2542
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2543
2544
		/**
2545
		 * Filter the returned data about a module.
2546
		 *
2547
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2548
		 * so please be careful.
2549
		 *
2550
		 * @since 3.6.0
2551
		 *
2552
		 * @param array   $mod    The details of the requested module.
2553
		 * @param string  $module The slug of the module, e.g. sharedaddy
2554
		 * @param string  $file   The path to the module source file.
2555
		 */
2556
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2557
	}
2558
2559
	/**
2560
	 * Like core's get_file_data implementation, but caches the result.
2561
	 */
2562
	public static function get_file_data( $file, $headers ) {
2563
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2564
		$file_name = basename( $file );
2565
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2566
		$key              = md5( $file_name . serialize( $headers ) );
2567
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2568
2569
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2570
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2571
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2572
		}
2573
2574
		$data = get_file_data( $file, $headers );
2575
2576
		// Strip out any old Jetpack versions that are cluttering the option.
2577
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2578
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2579
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2580
2581
		return $data;
2582
	}
2583
2584
	/**
2585
	 * Return translated module tag.
2586
	 *
2587
	 * @param string $tag Tag as it appears in each module heading.
2588
	 *
2589
	 * @return mixed
2590
	 */
2591
	public static function translate_module_tag( $tag ) {
2592
		return jetpack_get_module_i18n_tag( $tag );
2593
	}
2594
2595
	/**
2596
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2597
	 *
2598
	 * @since 3.9.2
2599
	 *
2600
	 * @param array $modules
2601
	 *
2602
	 * @return string|void
2603
	 */
2604
	public static function get_translated_modules( $modules ) {
2605
		foreach ( $modules as $index => $module ) {
2606
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2607
			if ( isset( $module['name'] ) ) {
2608
				$modules[ $index ]['name'] = $i18n_module['name'];
2609
			}
2610
			if ( isset( $module['description'] ) ) {
2611
				$modules[ $index ]['description'] = $i18n_module['description'];
2612
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2613
			}
2614
		}
2615
		return $modules;
2616
	}
2617
2618
	/**
2619
	 * Get a list of activated modules as an array of module slugs.
2620
	 */
2621
	public static function get_active_modules() {
2622
		$active = Jetpack_Options::get_option( 'active_modules' );
2623
		if ( ! is_array( $active ) )
2624
			$active = array();
2625
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2626
			$active[] = 'vaultpress';
2627
		} else {
2628
			$active = array_diff( $active, array( 'vaultpress' ) );
2629
		}
2630
2631
		//If protect is active on the main site of a multisite, it should be active on all sites.
2632
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2633
			$active[] = 'protect';
2634
		}
2635
2636
		return array_unique( $active );
2637
	}
2638
2639
	/**
2640
	 * Check whether or not a Jetpack module is active.
2641
	 *
2642
	 * @param string $module The slug of a Jetpack module.
2643
	 * @return bool
2644
	 *
2645
	 * @static
2646
	 */
2647
	public static function is_module_active( $module ) {
2648
		return in_array( $module, self::get_active_modules() );
2649
	}
2650
2651
	public static function is_module( $module ) {
2652
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2653
	}
2654
2655
	/**
2656
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2657
	 *
2658
	 * @param bool $catch True to start catching, False to stop.
2659
	 *
2660
	 * @static
2661
	 */
2662
	public static function catch_errors( $catch ) {
2663
		static $display_errors, $error_reporting;
2664
2665
		if ( $catch ) {
2666
			$display_errors  = @ini_set( 'display_errors', 1 );
2667
			$error_reporting = @error_reporting( E_ALL );
2668
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2669
		} else {
2670
			@ini_set( 'display_errors', $display_errors );
2671
			@error_reporting( $error_reporting );
2672
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2673
		}
2674
	}
2675
2676
	/**
2677
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2678
	 */
2679
	public static function catch_errors_on_shutdown() {
2680
		Jetpack::state( 'php_errors', ob_get_clean() );
2681
	}
2682
2683
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array() ) {
2684
		$jetpack = Jetpack::init();
2685
2686
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2687
		$modules = array_merge( $other_modules, $modules );
2688
2689
		// Look for standalone plugins and disable if active.
2690
2691
		$to_deactivate = array();
2692
		foreach ( $modules as $module ) {
2693
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2694
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2695
			}
2696
		}
2697
2698
		$deactivated = array();
2699
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2700
			list( $probable_file, $probable_title ) = $deactivate_me;
2701
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2702
				$deactivated[] = $module;
2703
			}
2704
		}
2705
2706
		if ( $deactivated ) {
2707
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2708
2709
			$url = add_query_arg(
2710
				array(
2711
					'action'   => 'activate_default_modules',
2712
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2713
				),
2714
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2715
			);
2716
			wp_safe_redirect( $url );
2717
			exit;
2718
		}
2719
2720
		/**
2721
		 * Fires before default modules are activated.
2722
		 *
2723
		 * @since 1.9.0
2724
		 *
2725
		 * @param string $min_version Minimum version number required to use modules.
2726
		 * @param string $max_version Maximum version number required to use modules.
2727
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2728
		 */
2729
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2730
2731
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2732
		Jetpack::restate();
2733
		Jetpack::catch_errors( true );
2734
2735
		$active = Jetpack::get_active_modules();
2736
2737
		foreach ( $modules as $module ) {
2738
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2739
				$active[] = $module;
2740
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2741
				continue;
2742
			}
2743
2744
			if ( in_array( $module, $active ) ) {
2745
				$module_info = Jetpack::get_module( $module );
2746
				if ( ! $module_info['deactivate'] ) {
2747
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2748 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2749
						$active_state = explode( ',', $active_state );
2750
					} else {
2751
						$active_state = array();
2752
					}
2753
					$active_state[] = $module;
2754
					Jetpack::state( $state, implode( ',', $active_state ) );
2755
				}
2756
				continue;
2757
			}
2758
2759
			$file = Jetpack::get_module_path( $module );
2760
			if ( ! file_exists( $file ) ) {
2761
				continue;
2762
			}
2763
2764
			// we'll override this later if the plugin can be included without fatal error
2765
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2766
			Jetpack::state( 'error', 'module_activation_failed' );
2767
			Jetpack::state( 'module', $module );
2768
			ob_start();
2769
			require $file;
2770
			/**
2771
			 * Fires when a specific module is activated.
2772
			 *
2773
			 * @since 1.9.0
2774
			 *
2775
			 * @param string $module Module slug.
2776
			 */
2777
			do_action( 'jetpack_activate_module', $module );
2778
			$active[] = $module;
2779
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2780 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2781
				$active_state = explode( ',', $active_state );
2782
			} else {
2783
				$active_state = array();
2784
			}
2785
			$active_state[] = $module;
2786
			Jetpack::state( $state, implode( ',', $active_state ) );
2787
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2788
			ob_end_clean();
2789
		}
2790
		Jetpack::state( 'error', false );
2791
		Jetpack::state( 'module', false );
2792
		Jetpack::catch_errors( false );
2793
		/**
2794
		 * Fires when default modules are activated.
2795
		 *
2796
		 * @since 1.9.0
2797
		 *
2798
		 * @param string $min_version Minimum version number required to use modules.
2799
		 * @param string $max_version Maximum version number required to use modules.
2800
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2801
		 */
2802
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2803
	}
2804
2805
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2806
		/**
2807
		 * Fires before a module is activated.
2808
		 *
2809
		 * @since 2.6.0
2810
		 *
2811
		 * @param string $module Module slug.
2812
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2813
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2814
		 */
2815
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2816
2817
		$jetpack = Jetpack::init();
2818
2819
		if ( ! strlen( $module ) )
2820
			return false;
2821
2822
		if ( ! Jetpack::is_module( $module ) )
2823
			return false;
2824
2825
		// If it's already active, then don't do it again
2826
		$active = Jetpack::get_active_modules();
2827
		foreach ( $active as $act ) {
2828
			if ( $act == $module )
2829
				return true;
2830
		}
2831
2832
		$module_data = Jetpack::get_module( $module );
2833
2834
		if ( ! Jetpack::is_active() ) {
2835
			if ( !Jetpack::is_development_mode() )
2836
				return false;
2837
2838
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2839
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2840
				return false;
2841
		}
2842
2843
		// Check and see if the old plugin is active
2844
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2845
			// Deactivate the old plugin
2846
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2847
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2848
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2849
				Jetpack::state( 'deactivated_plugins', $module );
2850
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2851
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() 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...
2852
			}
2853
		}
2854
2855
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2856
		Jetpack::state( 'module', $module );
2857
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2858
2859
		Jetpack::catch_errors( true );
2860
		ob_start();
2861
		require Jetpack::get_module_path( $module );
2862
		/** This action is documented in class.jetpack.php */
2863
		do_action( 'jetpack_activate_module', $module );
2864
		$active[] = $module;
2865
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2866
		Jetpack::state( 'error', false ); // the override
2867
		Jetpack::state( 'message', 'module_activated' );
2868
		Jetpack::state( 'module', $module );
2869
		ob_end_clean();
2870
		Jetpack::catch_errors( false );
2871
2872
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2873 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2874
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2875
2876
			//Jump start is being dismissed send data to MC Stats
2877
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2878
2879
			$jetpack->do_stats( 'server_side' );
2880
		}
2881
2882
		if ( $redirect ) {
2883
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2884
		}
2885
		if ( $exit ) {
2886
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() 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...
2887
		}
2888
	}
2889
2890
	function activate_module_actions( $module ) {
2891
		/**
2892
		 * Fires when a module is activated.
2893
		 * The dynamic part of the filter, $module, is the module slug.
2894
		 *
2895
		 * @since 1.9.0
2896
		 *
2897
		 * @param string $module Module slug.
2898
		 */
2899
		do_action( "jetpack_activate_module_$module", $module );
2900
2901
		$this->sync->sync_all_module_options( $module );
2902
	}
2903
2904
	public static function deactivate_module( $module ) {
2905
		/**
2906
		 * Fires when a module is deactivated.
2907
		 *
2908
		 * @since 1.9.0
2909
		 *
2910
		 * @param string $module Module slug.
2911
		 */
2912
		do_action( 'jetpack_pre_deactivate_module', $module );
2913
2914
		$jetpack = Jetpack::init();
2915
2916
		$active = Jetpack::get_active_modules();
2917
		$new    = array_filter( array_diff( $active, (array) $module ) );
2918
2919
		/**
2920
		 * Fires when a module is deactivated.
2921
		 * The dynamic part of the filter, $module, is the module slug.
2922
		 *
2923
		 * @since 1.9.0
2924
		 *
2925
		 * @param string $module Module slug.
2926
		 */
2927
		do_action( "jetpack_deactivate_module_$module", $module );
2928
2929
		// A flag for Jump Start so it's not shown again.
2930 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2931
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2932
2933
			//Jump start is being dismissed send data to MC Stats
2934
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2935
2936
			$jetpack->do_stats( 'server_side' );
2937
		}
2938
2939
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2940
	}
2941
2942
	public static function enable_module_configurable( $module ) {
2943
		$module = Jetpack::get_module_slug( $module );
2944
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2945
	}
2946
2947
	public static function module_configuration_url( $module ) {
2948
		$module = Jetpack::get_module_slug( $module );
2949
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2950
	}
2951
2952
	public static function module_configuration_load( $module, $method ) {
2953
		$module = Jetpack::get_module_slug( $module );
2954
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2955
	}
2956
2957
	public static function module_configuration_head( $module, $method ) {
2958
		$module = Jetpack::get_module_slug( $module );
2959
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2960
	}
2961
2962
	public static function module_configuration_screen( $module, $method ) {
2963
		$module = Jetpack::get_module_slug( $module );
2964
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2965
	}
2966
2967
	public static function module_configuration_activation_screen( $module, $method ) {
2968
		$module = Jetpack::get_module_slug( $module );
2969
		add_action( 'display_activate_module_setting_' . $module, $method );
2970
	}
2971
2972
/* Installation */
2973
2974
	public static function bail_on_activation( $message, $deactivate = true ) {
2975
?>
2976
<!doctype html>
2977
<html>
2978
<head>
2979
<meta charset="<?php bloginfo( 'charset' ); ?>">
2980
<style>
2981
* {
2982
	text-align: center;
2983
	margin: 0;
2984
	padding: 0;
2985
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2986
}
2987
p {
2988
	margin-top: 1em;
2989
	font-size: 18px;
2990
}
2991
</style>
2992
<body>
2993
<p><?php echo esc_html( $message ); ?></p>
2994
</body>
2995
</html>
2996
<?php
2997
		if ( $deactivate ) {
2998
			$plugins = get_option( 'active_plugins' );
2999
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3000
			$update  = false;
3001
			foreach ( $plugins as $i => $plugin ) {
3002
				if ( $plugin === $jetpack ) {
3003
					$plugins[$i] = false;
3004
					$update = true;
3005
				}
3006
			}
3007
3008
			if ( $update ) {
3009
				update_option( 'active_plugins', array_filter( $plugins ) );
3010
			}
3011
		}
3012
		exit;
3013
	}
3014
3015
	/**
3016
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3017
	 * @static
3018
	 */
3019
	public static function plugin_activation( $network_wide ) {
3020
		Jetpack_Options::update_option( 'activated', 1 );
3021
3022
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3023
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3024
		}
3025
3026
		if ( $network_wide )
3027
			Jetpack::state( 'network_nag', true );
3028
3029
		Jetpack::plugin_initialize();
3030
	}
3031
	/**
3032
	 * Runs before bumping version numbers up to a new version
3033
	 * @param  (string) $version    Version:timestamp
3034
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
3035
	 * @return null              [description]
3036
	 */
3037
	public static function do_version_bump( $version, $old_version ) {
3038
3039
		if ( ! $old_version ) { // For new sites
3040
			// Setting up jetpack manage
3041
			Jetpack::activate_manage();
3042
		}
3043
	}
3044
3045
	/**
3046
	 * Sets the internal version number and activation state.
3047
	 * @static
3048
	 */
3049
	public static function plugin_initialize() {
3050
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3051
			Jetpack_Options::update_option( 'activated', 2 );
3052
		}
3053
3054 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3055
			$version = $old_version = JETPACK__VERSION . ':' . time();
3056
			/** This action is documented in class.jetpack.php */
3057
			do_action( 'updating_jetpack_version', $version, false );
3058
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3059
		}
3060
3061
		Jetpack::load_modules();
3062
3063
		Jetpack_Options::delete_option( 'do_activate' );
3064
	}
3065
3066
	/**
3067
	 * Removes all connection options
3068
	 * @static
3069
	 */
3070
	public static function plugin_deactivation( ) {
3071
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3072
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3073
			Jetpack_Network::init()->deactivate();
3074
		} else {
3075
			Jetpack::disconnect( false );
3076
			//Jetpack_Heartbeat::init()->deactivate();
3077
		}
3078
	}
3079
3080
	/**
3081
	 * Disconnects from the Jetpack servers.
3082
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3083
	 * @static
3084
	 */
3085
	public static function disconnect( $update_activated_state = true ) {
3086
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3087
		Jetpack::clean_nonces( true );
3088
3089
		Jetpack::load_xml_rpc_client();
3090
		$xml = new Jetpack_IXR_Client();
3091
		$xml->query( 'jetpack.deregister' );
3092
3093
		Jetpack_Options::delete_option(
3094
			array(
3095
				'register',
3096
				'blog_token',
3097
				'user_token',
3098
				'user_tokens',
3099
				'master_user',
3100
				'time_diff',
3101
				'fallback_no_verify_ssl_certs',
3102
			)
3103
		);
3104
3105
		if ( $update_activated_state ) {
3106
			Jetpack_Options::update_option( 'activated', 4 );
3107
		}
3108
3109
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
3110
		// Check then record unique disconnection if site has never been disconnected previously
3111
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
3112
			$jetpack_unique_connection['disconnected'] = 1;
3113
		}
3114
		else {
3115
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3116
				//track unique disconnect
3117
				$jetpack = Jetpack::init();
3118
3119
				$jetpack->stat( 'connections', 'unique-disconnect' );
3120
				$jetpack->do_stats( 'server_side' );
3121
			}
3122
			// increment number of times disconnected
3123
			$jetpack_unique_connection['disconnected'] += 1;
3124
		}
3125
3126
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3127
3128
		// Disable the Heartbeat cron
3129
		Jetpack_Heartbeat::init()->deactivate();
3130
	}
3131
3132
	/**
3133
	 * Unlinks the current user from the linked WordPress.com user
3134
	 */
3135
	public static function unlink_user( $user_id = null ) {
3136
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3137
			return false;
3138
3139
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3140
3141
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3142
			return false;
3143
3144
		if ( ! isset( $tokens[ $user_id ] ) )
3145
			return false;
3146
3147
		Jetpack::load_xml_rpc_client();
3148
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3149
		$xml->query( 'jetpack.unlink_user', $user_id );
3150
3151
		unset( $tokens[ $user_id ] );
3152
3153
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3154
3155
		return true;
3156
	}
3157
3158
	/**
3159
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3160
	 */
3161
	public static function try_registration() {
3162
		// Let's get some testing in beta versions and such.
3163
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3164
			// Before attempting to connect, let's make sure that the domains are viable.
3165
			$domains_to_check = array_unique( array(
3166
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3167
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3168
			) );
3169
			foreach ( $domains_to_check as $domain ) {
3170
				$result = Jetpack_Data::is_usable_domain( $domain );
3171
				if ( is_wp_error( $result ) ) {
3172
					return $result;
3173
				}
3174
			}
3175
		}
3176
3177
		$result = Jetpack::register();
3178
3179
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3180
		if ( ! $result || is_wp_error( $result ) ) {
3181
			return $result;
3182
		} else {
3183
			return true;
3184
		}
3185
	}
3186
3187
	/**
3188
	 * Tracking an internal event log. Try not to put too much chaff in here.
3189
	 *
3190
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3191
	 */
3192
	public static function log( $code, $data = null ) {
3193
		// only grab the latest 200 entries
3194
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3195
3196
		// Append our event to the log
3197
		$log_entry = array(
3198
			'time'    => time(),
3199
			'user_id' => get_current_user_id(),
3200
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3201
			'code'    => $code,
3202
		);
3203
		// Don't bother storing it unless we've got some.
3204
		if ( ! is_null( $data ) ) {
3205
			$log_entry['data'] = $data;
3206
		}
3207
		$log[] = $log_entry;
3208
3209
		// Try add_option first, to make sure it's not autoloaded.
3210
		// @todo: Add an add_option method to Jetpack_Options
3211
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3212
			Jetpack_Options::update_option( 'log', $log );
3213
		}
3214
3215
		/**
3216
		 * Fires when Jetpack logs an internal event.
3217
		 *
3218
		 * @since 3.0.0
3219
		 *
3220
		 * @param array $log_entry {
3221
		 *	Array of details about the log entry.
3222
		 *
3223
		 *	@param string time Time of the event.
3224
		 *	@param int user_id ID of the user who trigerred the event.
3225
		 *	@param int blog_id Jetpack Blog ID.
3226
		 *	@param string code Unique name for the event.
3227
		 *	@param string data Data about the event.
3228
		 * }
3229
		 */
3230
		do_action( 'jetpack_log_entry', $log_entry );
3231
	}
3232
3233
	/**
3234
	 * Get the internal event log.
3235
	 *
3236
	 * @param $event (string) - only return the specific log events
3237
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3238
	 *
3239
	 * @return array of log events || WP_Error for invalid params
3240
	 */
3241
	public static function get_log( $event = false, $num = false ) {
3242
		if ( $event && ! is_string( $event ) ) {
3243
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3244
		}
3245
3246
		if ( $num && ! is_numeric( $num ) ) {
3247
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3248
		}
3249
3250
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3251
3252
		// If nothing set - act as it did before, otherwise let's start customizing the output
3253
		if ( ! $num && ! $event ) {
3254
			return $entire_log;
3255
		} else {
3256
			$entire_log = array_reverse( $entire_log );
3257
		}
3258
3259
		$custom_log_output = array();
3260
3261
		if ( $event ) {
3262
			foreach ( $entire_log as $log_event ) {
3263
				if ( $event == $log_event[ 'code' ] ) {
3264
					$custom_log_output[] = $log_event;
3265
				}
3266
			}
3267
		} else {
3268
			$custom_log_output = $entire_log;
3269
		}
3270
3271
		if ( $num ) {
3272
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3273
		}
3274
3275
		return $custom_log_output;
3276
	}
3277
3278
	/**
3279
	 * Log modification of important settings.
3280
	 */
3281
	public static function log_settings_change( $option, $old_value, $value ) {
3282
		switch( $option ) {
3283
			case 'jetpack_sync_non_public_post_stati':
3284
				self::log( $option, $value );
3285
				break;
3286
		}
3287
	}
3288
3289
	/**
3290
	 * Return stat data for WPCOM sync
3291
	 */
3292
	function get_stat_data() {
3293
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3294
		$additional_data = $this->get_additional_stat_data();
3295
3296
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3297
	}
3298
3299
	/**
3300
	 * Get additional stat data to sync to WPCOM
3301
	 */
3302
	function get_additional_stat_data( $prefix = '' ) {
3303
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3304
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3305
		$return["{$prefix}users"]          = count_users();
3306
		$return["{$prefix}site-count"]     = 0;
3307
		if ( function_exists( 'get_blog_count' ) ) {
3308
			$return["{$prefix}site-count"] = get_blog_count();
3309
		}
3310
		return $return;
3311
	}
3312
3313
	/* Admin Pages */
3314
3315
	function admin_init() {
3316
		// If the plugin is not connected, display a connect message.
3317
		if (
3318
			// the plugin was auto-activated and needs its candy
3319
			Jetpack_Options::get_option( 'do_activate' )
3320
		||
3321
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3322
			! Jetpack_Options::get_option( 'activated' )
3323
		) {
3324
			Jetpack::plugin_initialize();
3325
		}
3326
3327
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3328
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3329
				// Show connect notice on dashboard and plugins pages
3330
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3331
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3332
			}
3333
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3334
			// Upgrade: 1.1 -> 1.1.1
3335
			// Check and see if host can verify the Jetpack servers' SSL certificate
3336
			$args = array();
3337
			Jetpack_Client::_wp_remote_request(
3338
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3339
				$args,
3340
				true
3341
			);
3342
		} else {
3343
			// Show the notice on the Dashboard only for now
3344
3345
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3346
3347
			// Identity crisis notices
3348
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3349
		}
3350
3351
		// If the plugin has just been disconnected from WP.com, show the survey notice
3352
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3353
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3354
		}
3355
3356
		if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3357
			add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
3358
		}
3359
3360
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3361
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3362
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3363
3364
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3365
			// Artificially throw errors in certain whitelisted cases during plugin activation
3366
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3367
3368
			// Kick off synchronization of user role when it changes
3369
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3370
		}
3371
3372
		// Jetpack Manage Activation Screen from .com
3373
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3374
	}
3375
3376
	function admin_body_class( $admin_body_class = '' ) {
3377
		$classes = explode( ' ', trim( $admin_body_class ) );
3378
3379
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3380
3381
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3382
		return " $admin_body_class ";
3383
	}
3384
3385
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3386
		return $admin_body_class . ' jetpack-pagestyles ';
3387
	}
3388
3389
	function prepare_connect_notice() {
3390
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3391
3392
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3393
3394
		if ( Jetpack::state( 'network_nag' ) )
3395
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3396
	}
3397
	/**
3398
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3399
	 *
3400
	 * @return null
3401
	 */
3402
	function prepare_manage_jetpack_notice() {
3403
3404
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3405
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3406
	}
3407
3408
	function manage_activate_screen() {
3409
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3410
	}
3411
	/**
3412
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3413
	 * This function artificially throws errors for such cases (whitelisted).
3414
	 *
3415
	 * @param string $plugin The activated plugin.
3416
	 */
3417
	function throw_error_on_activate_plugin( $plugin ) {
3418
		$active_modules = Jetpack::get_active_modules();
3419
3420
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3421
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3422
			$throw = false;
3423
3424
			// Try and make sure it really was the stats plugin
3425
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3426
				if ( 'stats.php' == basename( $plugin ) ) {
3427
					$throw = true;
3428
				}
3429
			} else {
3430
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3431
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3432
					$throw = true;
3433
				}
3434
			}
3435
3436
			if ( $throw ) {
3437
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3438
			}
3439
		}
3440
	}
3441
3442
	function intercept_plugin_error_scrape_init() {
3443
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3444
	}
3445
3446
	function intercept_plugin_error_scrape( $action, $result ) {
3447
		if ( ! $result ) {
3448
			return;
3449
		}
3450
3451
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3452
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3453
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3454
			}
3455
		}
3456
	}
3457
3458
	function add_remote_request_handlers() {
3459
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3460
	}
3461
3462
	function remote_request_handlers() {
3463
		switch ( current_filter() ) {
3464
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3465
			$response = $this->upload_handler();
3466
			break;
3467
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
3468
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3469
			break;
3470
		}
3471
3472
		if ( ! $response ) {
3473
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3474
		}
3475
3476
		if ( is_wp_error( $response ) ) {
3477
			$status_code       = $response->get_error_data();
3478
			$error             = $response->get_error_code();
3479
			$error_description = $response->get_error_message();
3480
3481
			if ( ! is_int( $status_code ) ) {
3482
				$status_code = 400;
3483
			}
3484
3485
			status_header( $status_code );
3486
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3487
		}
3488
3489
		status_header( 200 );
3490
		if ( true === $response ) {
3491
			exit;
3492
		}
3493
3494
		die( json_encode( (object) $response ) );
3495
	}
3496
3497
	function upload_handler() {
3498
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3499
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3500
		}
3501
3502
		$user = wp_authenticate( '', '' );
3503
		if ( ! $user || is_wp_error( $user ) ) {
3504
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3505
		}
3506
3507
		wp_set_current_user( $user->ID );
3508
3509
		if ( ! current_user_can( 'upload_files' ) ) {
3510
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3511
		}
3512
3513
		if ( empty( $_FILES ) ) {
3514
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3515
		}
3516
3517
		foreach ( array_keys( $_FILES ) as $files_key ) {
3518
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3519
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3520
			}
3521
		}
3522
3523
		$media_keys = array_keys( $_FILES['media'] );
3524
3525
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3526
		if ( ! $token || is_wp_error( $token ) ) {
3527
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3528
		}
3529
3530
		$uploaded_files = array();
3531
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3532
		unset( $GLOBALS['post'] );
3533
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3534
			$file = array();
3535
			foreach ( $media_keys as $media_key ) {
3536
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3537
			}
3538
3539
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3540
3541
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3542
			if ( $hmac_provided !== $hmac_file ) {
3543
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3544
				continue;
3545
			}
3546
3547
			$_FILES['.jetpack.upload.'] = $file;
3548
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3549
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3550
				$post_id = 0;
3551
			}
3552
			$attachment_id = media_handle_upload(
3553
				'.jetpack.upload.',
3554
				$post_id,
3555
				array(),
3556
				array(
3557
					'action' => 'jetpack_upload_file',
3558
				)
3559
			);
3560
3561
			if ( ! $attachment_id ) {
3562
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3563
			} elseif ( is_wp_error( $attachment_id ) ) {
3564
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3565
			} else {
3566
				$attachment = get_post( $attachment_id );
3567
				$uploaded_files[$index] = (object) array(
3568
					'id'   => (string) $attachment_id,
3569
					'file' => $attachment->post_title,
3570
					'url'  => wp_get_attachment_url( $attachment_id ),
3571
					'type' => $attachment->post_mime_type,
3572
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3573
				);
3574
			}
3575
		}
3576
		if ( ! is_null( $global_post ) ) {
3577
			$GLOBALS['post'] = $global_post;
3578
		}
3579
3580
		return $uploaded_files;
3581
	}
3582
3583
	/**
3584
	 * Add help to the Jetpack page
3585
	 *
3586
	 * @since Jetpack (1.2.3)
3587
	 * @return false if not the Jetpack page
3588
	 */
3589
	function admin_help() {
3590
		$current_screen = get_current_screen();
3591
3592
		// Overview
3593
		$current_screen->add_help_tab(
3594
			array(
3595
				'id'		=> 'home',
3596
				'title'		=> __( 'Home', 'jetpack' ),
3597
				'content'	=>
3598
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3599
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3600
					'<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>',
3601
			)
3602
		);
3603
3604
		// Screen Content
3605
		if ( current_user_can( 'manage_options' ) ) {
3606
			$current_screen->add_help_tab(
3607
				array(
3608
					'id'		=> 'settings',
3609
					'title'		=> __( 'Settings', 'jetpack' ),
3610
					'content'	=>
3611
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3612
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3613
						'<ol>' .
3614
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3615
							'<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>' .
3616
						'</ol>' .
3617
						'<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>'
3618
				)
3619
			);
3620
		}
3621
3622
		// Help Sidebar
3623
		$current_screen->set_help_sidebar(
3624
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3625
			'<p><a href="http://jetpack.me/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3626
			'<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3627
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3628
		);
3629
	}
3630
3631
	function admin_menu_css() {
3632
		wp_enqueue_style( 'jetpack-icons' );
3633
	}
3634
3635
	function admin_menu_order() {
3636
		return true;
3637
	}
3638
3639 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3640
		$jp_menu_order = array();
3641
3642
		foreach ( $menu_order as $index => $item ) {
3643
			if ( $item != 'jetpack' ) {
3644
				$jp_menu_order[] = $item;
3645
			}
3646
3647
			if ( $index == 0 ) {
3648
				$jp_menu_order[] = 'jetpack';
3649
			}
3650
		}
3651
3652
		return $jp_menu_order;
3653
	}
3654
3655
	function admin_head() {
3656 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3657
			/** This action is documented in class.jetpack-admin-page.php */
3658
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3659
	}
3660
3661
	function admin_banner_styles() {
3662
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3663
3664
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3665
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3666
		wp_style_add_data( 'jetpack', 'suffix', $min );
3667
	}
3668
3669
	function admin_scripts() {
3670
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3671
		wp_localize_script(
3672
			'jetpack-js',
3673
			'jetpackL10n',
3674
			array(
3675
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3676
				'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?",
3677
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3678
			)
3679
		);
3680
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3681
	}
3682
3683
	function plugin_action_links( $actions ) {
3684
3685
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3686
3687
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3688
			return array_merge(
3689
				$jetpack_home,
3690
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3691
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3692
				$actions
3693
				);
3694
			}
3695
3696
		return array_merge( $jetpack_home, $actions );
3697
	}
3698
3699
	function admin_connect_notice() {
3700
		// Don't show the connect notice anywhere but the plugins.php after activating
3701
		$current = get_current_screen();
3702
		if ( 'plugins' !== $current->parent_base )
3703
			return;
3704
3705
		if ( ! current_user_can( 'jetpack_connect' ) )
3706
			return;
3707
3708
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3709
		?>
3710
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3711
			<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>
3712
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3713
				<div class="jp-banner__content is-connection">
3714
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3715
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3716
				</div>
3717
				<div class="jp-banner__action-container is-connection">
3718
						<a href="<?php echo $this->build_connect_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3719
				</div>
3720 View Code Duplication
			<?php else : ?>
3721
				<div class="jp-banner__content">
3722
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3723
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3724
				</div>
3725
				<div class="jp-banner__action-container">
3726
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3727
				</div>
3728
			<?php endif; ?>
3729
		</div>
3730
3731
		<?php
3732
	}
3733
3734
	/**
3735
	 * This is the first banner
3736
	 * It should be visible only to user that can update the option
3737
	 * Are not connected
3738
	 *
3739
	 * @return null
3740
	 */
3741
	function admin_jetpack_manage_notice() {
3742
		$screen = get_current_screen();
3743
3744
		// Don't show the connect notice on the jetpack settings page.
3745
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3746
			return;
3747
3748
		// Only show it if don't have the managment option set.
3749
		// And not dismissed it already.
3750
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3751
			return;
3752
		}
3753
3754
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3755
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3756
		/**
3757
		 * I think it would be great to have different wordsing depending on where you are
3758
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3759
		 * etc..
3760
		 */
3761
3762
		?>
3763
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3764
			<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>
3765
			<div class="jp-banner__content">
3766
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3767
				<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>
3768
			</div>
3769
			<div class="jp-banner__action-container is-opt-in">
3770
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3771
			</div>
3772
		</div>
3773
		<?php
3774
	}
3775
3776
	/**
3777
	 * Returns the url that the user clicks to remove the notice for the big banner
3778
	 * @return (string)
3779
	 */
3780
	function opt_out_jetpack_manage_url() {
3781
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3782
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3783
	}
3784
	/**
3785
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3786
	 * @return (string)
3787
	 */
3788
	function opt_in_jetpack_manage_url() {
3789
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3790
	}
3791
3792
	function opt_in_jetpack_manage_notice() {
3793
		?>
3794
		<div class="wrap">
3795
			<div id="message" class="jetpack-message is-opt-in">
3796
				<?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' ); ?>
3797
			</div>
3798
		</div>
3799
		<?php
3800
3801
	}
3802
	/**
3803
	 * Determines whether to show the notice of not true = display notice
3804
	 * @return (bool)
3805
	 */
3806
	function can_display_jetpack_manage_notice() {
3807
		// never display the notice to users that can't do anything about it anyways
3808
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3809
			return false;
3810
3811
		// don't display if we are in development more
3812
		if( Jetpack::is_development_mode() ) {
3813
			return false;
3814
		}
3815
		// don't display if the site is private
3816
		if(  ! Jetpack_Options::get_option( 'public' ) )
3817
			return false;
3818
3819
		/**
3820
		 * Should the Jetpack Remote Site Management notice be displayed.
3821
		 *
3822
		 * @since 3.3.0
3823
		 *
3824
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3825
		 */
3826
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3827
	}
3828
3829
	function network_connect_notice() {
3830
		?>
3831
		<div id="message" class="updated jetpack-message">
3832
			<div class="squeezer">
3833
				<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>
3834
			</div>
3835
		</div>
3836
		<?php
3837
	}
3838
3839
	public static function jetpack_comment_notice() {
3840
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3841
			return '';
3842
		}
3843
3844
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3845
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3846
3847
		if ( $jetpack_old_version ) {
3848
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3849
				return '';
3850
			}
3851
		}
3852
3853
		if ( $jetpack_new_version ) {
3854
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3855
				return '';
3856
			}
3857
		}
3858
3859
		return '<br /><br />' . sprintf(
3860
			__( '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' ),
3861
			wp_nonce_url(
3862
				Jetpack::admin_url(
3863
					array(
3864
						'page'   => 'jetpack',
3865
						'action' => 'activate',
3866
						'module' => 'comments',
3867
					)
3868
				),
3869
				'jetpack_activate-comments'
3870
			),
3871
			__( 'click here', 'jetpack' )
3872
		);
3873
	}
3874
3875
	/**
3876
	 * Show the survey link when the user has just disconnected Jetpack.
3877
	 */
3878
	function disconnect_survey_notice() {
3879
		?>
3880
		<div class="wrap">
3881
			<div id="message" class="jetpack-message stay-visible">
3882
				<div class="squeezer">
3883
					<h2>
3884
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3885
						<br />
3886
						<?php echo sprintf(
3887
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3888
							'https://jetpack.me/survey-disconnected/',
3889
							'_blank'
3890
						); ?>
3891
					</h2>
3892
				</div>
3893
			</div>
3894
		</div>
3895
		<?php
3896
	}
3897
3898
	/*
3899
	 * Registration flow:
3900
	 * 1 - ::admin_page_load() action=register
3901
	 * 2 - ::try_registration()
3902
	 * 3 - ::register()
3903
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3904
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3905
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3906
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3907
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3908
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3909
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3910
	 *       jetpack_id, jetpack_secret, jetpack_public
3911
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3912
	 * 4 - redirect to https://jetpack.wordpress.com/jetpack.authorize/1/
3913
	 * 5 - user logs in with WP.com account
3914
	 * 6 - redirect to this site's wp-admin/index.php?page=jetpack&action=authorize with
3915
	 *     code <-- OAuth2 style authorization code
3916
	 * 7 - ::admin_page_load() action=authorize
3917
	 * 8 - Jetpack_Client_Server::authorize()
3918
	 * 9 - Jetpack_Client_Server::get_token()
3919
	 * 10- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3920
	 *     client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3921
	 * 11- which responds with
3922
	 *     access_token, token_type, scope
3923
	 * 12- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3924
	 * 13- Jetpack::activate_default_modules()
3925
	 *     Deactivates deprecated plugins
3926
	 *     Activates all default modules
3927
	 *     Catches errors: redirects to wp-admin/index.php?page=jetpack state:error=something
3928
	 * 14- redirect to this site's wp-admin/index.php?page=jetpack with state:message=authorized
3929
	 *     Done!
3930
	 */
3931
3932
	/**
3933
	 * Handles the page load events for the Jetpack admin page
3934
	 */
3935
	function admin_page_load() {
3936
		$error = false;
3937
3938
		// Make sure we have the right body class to hook stylings for subpages off of.
3939
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3940
3941
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3942
			// Should only be used in intermediate redirects to preserve state across redirects
3943
			Jetpack::restate();
3944
		}
3945
3946
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3947
			// User clicked in the iframe to link their accounts
3948
			if ( ! Jetpack::is_user_connected() ) {
3949
				$connect_url = $this->build_connect_url( true );
3950
				if ( isset( $_GET['notes_iframe'] ) )
3951
					$connect_url .= '&notes_iframe';
3952
				wp_redirect( $connect_url );
3953
				exit;
3954
			} else {
3955
				Jetpack::state( 'message', 'already_authorized' );
3956
				wp_safe_redirect( Jetpack::admin_url() );
3957
				exit;
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...
3958
			}
3959
		}
3960
3961
3962
		if ( isset( $_GET['action'] ) ) {
3963
			switch ( $_GET['action'] ) {
3964
			case 'authorize' :
3965
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3966
					Jetpack::state( 'message', 'already_authorized' );
3967
					wp_safe_redirect( Jetpack::admin_url() );
3968
					exit;
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...
3969
				}
3970
				Jetpack::log( 'authorize' );
3971
				$client_server = new Jetpack_Client_Server;
3972
				$client_server->authorize();
3973
				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...
3974
			case 'register' :
3975
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3976
					$error = 'cheatin';
3977
					break;
3978
				}
3979
				check_admin_referer( 'jetpack-register' );
3980
				Jetpack::log( 'register' );
3981
				Jetpack::maybe_set_version_option();
3982
				$registered = Jetpack::try_registration();
3983
				if ( is_wp_error( $registered ) ) {
3984
					$error = $registered->get_error_code();
3985
					Jetpack::state( 'error_description', $registered->get_error_message() );
3986
					break;
3987
				}
3988
3989
				wp_redirect( $this->build_connect_url( true ) );
3990
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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