Completed
Push — remove/deprecated-upgrade-code ( 30dd2a...39f6ed )
by
unknown
09:55
created

class.jetpack.php (8 issues)

Upgrade to new PHP Analysis Engine

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

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