Completed
Push — add/sync-rest-options ( 3a27a6...110de2 )
by
unknown
08:34
created

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