Completed
Push — add/msm-skip-sitemap ( e66df8 )
by
unknown
10:17
created

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