Completed
Push — branch-4.1 ( 3fb9ba...cc3fd4 )
by Jeremy
272:42 queued 263:17
created

class.jetpack.php (13 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

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

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

Loading history...
2329
					break;
2330
			}
2331
		}
2332
		/**
2333
		 * Filters the array of default modules.
2334
		 *
2335
		 * @since 2.5.0
2336
		 *
2337
		 * @param array $return Array of default modules.
2338
		 * @param string $min_version Minimum version number required to use modules.
2339
		 * @param string $max_version Maximum version number required to use modules.
2340
		 */
2341
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2342
	}
2343
2344
	/**
2345
	 * Checks activated modules during auto-activation to determine
2346
	 * if any of those modules are being deprecated.  If so, close
2347
	 * them out, and add any replacement modules.
2348
	 *
2349
	 * Runs at priority 99 by default.
2350
	 *
2351
	 * This is run late, so that it can still activate a module if
2352
	 * the new module is a replacement for another that the user
2353
	 * currently has active, even if something at the normal priority
2354
	 * would kibosh everything.
2355
	 *
2356
	 * @since 2.6
2357
	 * @uses jetpack_get_default_modules filter
2358
	 * @param array $modules
2359
	 * @return array
2360
	 */
2361
	function handle_deprecated_modules( $modules ) {
2362
		$deprecated_modules = array(
2363
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2364
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2365
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2366
		);
2367
2368
		// Don't activate SSO if they never completed activating WPCC.
2369
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2370
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2371
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2372
				$deprecated_modules['wpcc'] = null;
2373
			}
2374
		}
2375
2376
		foreach ( $deprecated_modules as $module => $replacement ) {
2377
			if ( Jetpack::is_module_active( $module ) ) {
2378
				self::deactivate_module( $module );
2379
				if ( $replacement ) {
2380
					$modules[] = $replacement;
2381
				}
2382
			}
2383
		}
2384
2385
		return array_unique( $modules );
2386
	}
2387
2388
	/**
2389
	 * Checks activated plugins during auto-activation to determine
2390
	 * if any of those plugins are in the list with a corresponding module
2391
	 * that is not compatible with the plugin. The module will not be allowed
2392
	 * to auto-activate.
2393
	 *
2394
	 * @since 2.6
2395
	 * @uses jetpack_get_default_modules filter
2396
	 * @param array $modules
2397
	 * @return array
2398
	 */
2399
	function filter_default_modules( $modules ) {
2400
2401
		$active_plugins = self::get_active_plugins();
2402
2403
		if ( ! empty( $active_plugins ) ) {
2404
2405
			// For each module we'd like to auto-activate...
2406
			foreach ( $modules as $key => $module ) {
2407
				// If there are potential conflicts for it...
2408
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2409
					// For each potential conflict...
2410
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2411
						// If that conflicting plugin is active...
2412
						if ( in_array( $plugin, $active_plugins ) ) {
2413
							// Remove that item from being auto-activated.
2414
							unset( $modules[ $key ] );
2415
						}
2416
					}
2417
				}
2418
			}
2419
		}
2420
2421
		return $modules;
2422
	}
2423
2424
	/**
2425
	 * Extract a module's slug from its full path.
2426
	 */
2427
	public static function get_module_slug( $file ) {
2428
		return str_replace( '.php', '', basename( $file ) );
2429
	}
2430
2431
	/**
2432
	 * Generate a module's path from its slug.
2433
	 */
2434
	public static function get_module_path( $slug ) {
2435
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2436
	}
2437
2438
	/**
2439
	 * Load module data from module file. Headers differ from WordPress
2440
	 * plugin headers to avoid them being identified as standalone
2441
	 * plugins on the WordPress plugins page.
2442
	 */
2443
	public static function get_module( $module ) {
2444
		$headers = array(
2445
			'name'                      => 'Module Name',
2446
			'description'               => 'Module Description',
2447
			'jumpstart_desc'            => 'Jumpstart Description',
2448
			'sort'                      => 'Sort Order',
2449
			'recommendation_order'      => 'Recommendation Order',
2450
			'introduced'                => 'First Introduced',
2451
			'changed'                   => 'Major Changes In',
2452
			'deactivate'                => 'Deactivate',
2453
			'free'                      => 'Free',
2454
			'requires_connection'       => 'Requires Connection',
2455
			'auto_activate'             => 'Auto Activate',
2456
			'module_tags'               => 'Module Tags',
2457
			'feature'                   => 'Feature',
2458
			'additional_search_queries' => 'Additional Search Queries',
2459
		);
2460
2461
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2462
2463
		$mod = Jetpack::get_file_data( $file, $headers );
2464
		if ( empty( $mod['name'] ) ) {
2465
			return false;
2466
		}
2467
2468
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2469
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2470
		$mod['deactivate']              = empty( $mod['deactivate'] );
2471
		$mod['free']                    = empty( $mod['free'] );
2472
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2473
2474
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2475
			$mod['auto_activate'] = 'No';
2476
		} else {
2477
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2478
		}
2479
2480
		if ( $mod['module_tags'] ) {
2481
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2482
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2483
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2484
		} else {
2485
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2486
		}
2487
2488
		if ( $mod['feature'] ) {
2489
			$mod['feature'] = explode( ',', $mod['feature'] );
2490
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2491
		} else {
2492
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2493
		}
2494
2495
		/**
2496
		 * Filters the feature array on a module.
2497
		 *
2498
		 * This filter allows you to control where each module is filtered: Recommended,
2499
		 * Jumpstart, and the default "Other" listing.
2500
		 *
2501
		 * @since 3.5.0
2502
		 *
2503
		 * @param array   $mod['feature'] The areas to feature this module:
2504
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2505
		 *     'Recommended' shows on the main Jetpack admin screen.
2506
		 *     'Other' should be the default if no other value is in the array.
2507
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2508
		 * @param array   $mod All the currently assembled module data.
2509
		 */
2510
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2511
2512
		/**
2513
		 * Filter the returned data about a module.
2514
		 *
2515
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2516
		 * so please be careful.
2517
		 *
2518
		 * @since 3.6.0
2519
		 *
2520
		 * @param array   $mod    The details of the requested module.
2521
		 * @param string  $module The slug of the module, e.g. sharedaddy
2522
		 * @param string  $file   The path to the module source file.
2523
		 */
2524
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2525
	}
2526
2527
	/**
2528
	 * Like core's get_file_data implementation, but caches the result.
2529
	 */
2530
	public static function get_file_data( $file, $headers ) {
2531
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2532
		$file_name = basename( $file );
2533
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2534
		$key              = md5( $file_name . serialize( $headers ) );
2535
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2536
2537
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2538
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2539
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2540
		}
2541
2542
		$data = get_file_data( $file, $headers );
2543
2544
		// Strip out any old Jetpack versions that are cluttering the option.
2545
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2546
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2547
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2548
2549
		return $data;
2550
	}
2551
2552
	/**
2553
	 * Return translated module tag.
2554
	 *
2555
	 * @param string $tag Tag as it appears in each module heading.
2556
	 *
2557
	 * @return mixed
2558
	 */
2559
	public static function translate_module_tag( $tag ) {
2560
		return jetpack_get_module_i18n_tag( $tag );
2561
	}
2562
2563
	/**
2564
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2565
	 *
2566
	 * @since 3.9.2
2567
	 *
2568
	 * @param array $modules
2569
	 *
2570
	 * @return string|void
2571
	 */
2572
	public static function get_translated_modules( $modules ) {
2573
		foreach ( $modules as $index => $module ) {
2574
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2575
			if ( isset( $module['name'] ) ) {
2576
				$modules[ $index ]['name'] = $i18n_module['name'];
2577
			}
2578
			if ( isset( $module['description'] ) ) {
2579
				$modules[ $index ]['description'] = $i18n_module['description'];
2580
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2581
			}
2582
		}
2583
		return $modules;
2584
	}
2585
2586
	/**
2587
	 * Get a list of activated modules as an array of module slugs.
2588
	 */
2589
	public static function get_active_modules() {
2590
		$active = Jetpack_Options::get_option( 'active_modules' );
2591
		if ( ! is_array( $active ) )
2592
			$active = array();
2593
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2594
			$active[] = 'vaultpress';
2595
		} else {
2596
			$active = array_diff( $active, array( 'vaultpress' ) );
2597
		}
2598
2599
		//If protect is active on the main site of a multisite, it should be active on all sites.
2600
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2601
			$active[] = 'protect';
2602
		}
2603
2604
		return array_unique( $active );
2605
	}
2606
2607
	/**
2608
	 * Check whether or not a Jetpack module is active.
2609
	 *
2610
	 * @param string $module The slug of a Jetpack module.
2611
	 * @return bool
2612
	 *
2613
	 * @static
2614
	 */
2615
	public static function is_module_active( $module ) {
2616
		return in_array( $module, self::get_active_modules() );
2617
	}
2618
2619
	public static function is_module( $module ) {
2620
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2621
	}
2622
2623
	/**
2624
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2625
	 *
2626
	 * @param bool $catch True to start catching, False to stop.
2627
	 *
2628
	 * @static
2629
	 */
2630
	public static function catch_errors( $catch ) {
2631
		static $display_errors, $error_reporting;
2632
2633
		if ( $catch ) {
2634
			$display_errors  = @ini_set( 'display_errors', 1 );
2635
			$error_reporting = @error_reporting( E_ALL );
2636
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2637
		} else {
2638
			@ini_set( 'display_errors', $display_errors );
2639
			@error_reporting( $error_reporting );
2640
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2641
		}
2642
	}
2643
2644
	/**
2645
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2646
	 */
2647
	public static function catch_errors_on_shutdown() {
2648
		Jetpack::state( 'php_errors', ob_get_clean() );
2649
	}
2650
2651
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2652
		$jetpack = Jetpack::init();
2653
2654
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2655
		$modules = array_merge( $other_modules, $modules );
2656
2657
		// Look for standalone plugins and disable if active.
2658
2659
		$to_deactivate = array();
2660
		foreach ( $modules as $module ) {
2661
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2662
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2663
			}
2664
		}
2665
2666
		$deactivated = array();
2667
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2668
			list( $probable_file, $probable_title ) = $deactivate_me;
2669
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2670
				$deactivated[] = $module;
2671
			}
2672
		}
2673
2674
		if ( $deactivated && $redirect ) {
2675
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2676
2677
			$url = add_query_arg(
2678
				array(
2679
					'action'   => 'activate_default_modules',
2680
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2681
				),
2682
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2683
			);
2684
			wp_safe_redirect( $url );
2685
			exit;
2686
		}
2687
2688
		/**
2689
		 * Fires before default modules are activated.
2690
		 *
2691
		 * @since 1.9.0
2692
		 *
2693
		 * @param string $min_version Minimum version number required to use modules.
2694
		 * @param string $max_version Maximum version number required to use modules.
2695
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2696
		 */
2697
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2698
2699
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2700
		Jetpack::restate();
2701
		Jetpack::catch_errors( true );
2702
2703
		$active = Jetpack::get_active_modules();
2704
2705
		foreach ( $modules as $module ) {
2706
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2707
				$active[] = $module;
2708
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2709
				continue;
2710
			}
2711
2712
			if ( in_array( $module, $active ) ) {
2713
				$module_info = Jetpack::get_module( $module );
2714
				if ( ! $module_info['deactivate'] ) {
2715
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2716 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2717
						$active_state = explode( ',', $active_state );
2718
					} else {
2719
						$active_state = array();
2720
					}
2721
					$active_state[] = $module;
2722
					Jetpack::state( $state, implode( ',', $active_state ) );
2723
				}
2724
				continue;
2725
			}
2726
2727
			$file = Jetpack::get_module_path( $module );
2728
			if ( ! file_exists( $file ) ) {
2729
				continue;
2730
			}
2731
2732
			// we'll override this later if the plugin can be included without fatal error
2733
			if ( $redirect ) {
2734
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2735
			}
2736
			Jetpack::state( 'error', 'module_activation_failed' );
2737
			Jetpack::state( 'module', $module );
2738
			ob_start();
2739
			require $file;
2740
			/**
2741
			 * Fires when a specific module is activated.
2742
			 *
2743
			 * @since 1.9.0
2744
			 *
2745
			 * @param string $module Module slug.
2746
			 */
2747
			do_action( 'jetpack_activate_module', $module );
2748
			$active[] = $module;
2749
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2750 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2751
				$active_state = explode( ',', $active_state );
2752
			} else {
2753
				$active_state = array();
2754
			}
2755
			$active_state[] = $module;
2756
			Jetpack::state( $state, implode( ',', $active_state ) );
2757
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2758
			ob_end_clean();
2759
		}
2760
		Jetpack::state( 'error', false );
2761
		Jetpack::state( 'module', false );
2762
		Jetpack::catch_errors( false );
2763
		/**
2764
		 * Fires when default modules are activated.
2765
		 *
2766
		 * @since 1.9.0
2767
		 *
2768
		 * @param string $min_version Minimum version number required to use modules.
2769
		 * @param string $max_version Maximum version number required to use modules.
2770
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2771
		 */
2772
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2773
	}
2774
2775
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2776
		/**
2777
		 * Fires before a module is activated.
2778
		 *
2779
		 * @since 2.6.0
2780
		 *
2781
		 * @param string $module Module slug.
2782
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2783
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2784
		 */
2785
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2786
2787
		$jetpack = Jetpack::init();
2788
2789
		if ( ! strlen( $module ) )
2790
			return false;
2791
2792
		if ( ! Jetpack::is_module( $module ) )
2793
			return false;
2794
2795
		// If it's already active, then don't do it again
2796
		$active = Jetpack::get_active_modules();
2797
		foreach ( $active as $act ) {
2798
			if ( $act == $module )
2799
				return true;
2800
		}
2801
2802
		$module_data = Jetpack::get_module( $module );
2803
2804
		if ( ! Jetpack::is_active() ) {
2805
			if ( !Jetpack::is_development_mode() )
2806
				return false;
2807
2808
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2809
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2810
				return false;
2811
		}
2812
2813
		// Check and see if the old plugin is active
2814
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2815
			// Deactivate the old plugin
2816
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2817
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2818
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2819
				Jetpack::state( 'deactivated_plugins', $module );
2820
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2821
				exit;
2822
			}
2823
		}
2824
2825
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2826
		Jetpack::state( 'module', $module );
2827
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2828
2829
		Jetpack::catch_errors( true );
2830
		ob_start();
2831
		require Jetpack::get_module_path( $module );
2832
		/** This action is documented in class.jetpack.php */
2833
		do_action( 'jetpack_activate_module', $module );
2834
		$active[] = $module;
2835
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2836
		Jetpack::state( 'error', false ); // the override
2837
		Jetpack::state( 'message', 'module_activated' );
2838
		Jetpack::state( 'module', $module );
2839
		ob_end_clean();
2840
		Jetpack::catch_errors( false );
2841
2842
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2843 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2844
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2845
2846
			//Jump start is being dismissed send data to MC Stats
2847
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2848
2849
			$jetpack->do_stats( 'server_side' );
2850
		}
2851
2852
		if ( $redirect ) {
2853
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2854
		}
2855
		if ( $exit ) {
2856
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2857
		}
2858
		return true;
2859
	}
2860
2861
	function activate_module_actions( $module ) {
2862
		/**
2863
		 * Fires when a module is activated.
2864
		 * The dynamic part of the filter, $module, is the module slug.
2865
		 *
2866
		 * @since 1.9.0
2867
		 *
2868
		 * @param string $module Module slug.
2869
		 */
2870
		do_action( "jetpack_activate_module_$module", $module );
2871
2872
		$this->sync->sync_all_module_options( $module );
2873
	}
2874
2875
	public static function deactivate_module( $module ) {
2876
		/**
2877
		 * Fires when a module is deactivated.
2878
		 *
2879
		 * @since 1.9.0
2880
		 *
2881
		 * @param string $module Module slug.
2882
		 */
2883
		do_action( 'jetpack_pre_deactivate_module', $module );
2884
2885
		$jetpack = Jetpack::init();
2886
2887
		$active = Jetpack::get_active_modules();
2888
		$new    = array_filter( array_diff( $active, (array) $module ) );
2889
2890
		/**
2891
		 * Fires when a module is deactivated.
2892
		 * The dynamic part of the filter, $module, is the module slug.
2893
		 *
2894
		 * @since 1.9.0
2895
		 *
2896
		 * @param string $module Module slug.
2897
		 */
2898
		do_action( "jetpack_deactivate_module_$module", $module );
2899
2900
		// A flag for Jump Start so it's not shown again.
2901 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2902
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2903
2904
			//Jump start is being dismissed send data to MC Stats
2905
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2906
2907
			$jetpack->do_stats( 'server_side' );
2908
		}
2909
2910
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2911
	}
2912
2913
	public static function enable_module_configurable( $module ) {
2914
		$module = Jetpack::get_module_slug( $module );
2915
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2916
	}
2917
2918
	public static function module_configuration_url( $module ) {
2919
		$module = Jetpack::get_module_slug( $module );
2920
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2921
	}
2922
2923
	public static function module_configuration_load( $module, $method ) {
2924
		$module = Jetpack::get_module_slug( $module );
2925
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2926
	}
2927
2928
	public static function module_configuration_head( $module, $method ) {
2929
		$module = Jetpack::get_module_slug( $module );
2930
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2931
	}
2932
2933
	public static function module_configuration_screen( $module, $method ) {
2934
		$module = Jetpack::get_module_slug( $module );
2935
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2936
	}
2937
2938
	public static function module_configuration_activation_screen( $module, $method ) {
2939
		$module = Jetpack::get_module_slug( $module );
2940
		add_action( 'display_activate_module_setting_' . $module, $method );
2941
	}
2942
2943
/* Installation */
2944
2945
	public static function bail_on_activation( $message, $deactivate = true ) {
2946
?>
2947
<!doctype html>
2948
<html>
2949
<head>
2950
<meta charset="<?php bloginfo( 'charset' ); ?>">
2951
<style>
2952
* {
2953
	text-align: center;
2954
	margin: 0;
2955
	padding: 0;
2956
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2957
}
2958
p {
2959
	margin-top: 1em;
2960
	font-size: 18px;
2961
}
2962
</style>
2963
<body>
2964
<p><?php echo esc_html( $message ); ?></p>
2965
</body>
2966
</html>
2967
<?php
2968
		if ( $deactivate ) {
2969
			$plugins = get_option( 'active_plugins' );
2970
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2971
			$update  = false;
2972
			foreach ( $plugins as $i => $plugin ) {
2973
				if ( $plugin === $jetpack ) {
2974
					$plugins[$i] = false;
2975
					$update = true;
2976
				}
2977
			}
2978
2979
			if ( $update ) {
2980
				update_option( 'active_plugins', array_filter( $plugins ) );
2981
			}
2982
		}
2983
		exit;
2984
	}
2985
2986
	/**
2987
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2988
	 * @static
2989
	 */
2990
	public static function plugin_activation( $network_wide ) {
2991
		Jetpack_Options::update_option( 'activated', 1 );
2992
2993
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2994
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2995
		}
2996
2997
		if ( $network_wide )
2998
			Jetpack::state( 'network_nag', true );
2999
3000
		Jetpack::plugin_initialize();
3001
	}
3002
	/**
3003
	 * Runs before bumping version numbers up to a new version
3004
	 * @param  (string) $version    Version:timestamp
3005
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
3006
	 * @return null              [description]
3007
	 */
3008
	public static function do_version_bump( $version, $old_version ) {
3009
3010
		if ( ! $old_version ) { // For new sites
3011
			// Setting up jetpack manage
3012
			Jetpack::activate_manage();
3013
		}
3014
	}
3015
3016
	/**
3017
	 * Sets the internal version number and activation state.
3018
	 * @static
3019
	 */
3020
	public static function plugin_initialize() {
3021
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3022
			Jetpack_Options::update_option( 'activated', 2 );
3023
		}
3024
3025 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3026
			$version = $old_version = JETPACK__VERSION . ':' . time();
3027
			/** This action is documented in class.jetpack.php */
3028
			do_action( 'updating_jetpack_version', $version, false );
3029
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3030
		}
3031
3032
		Jetpack::load_modules();
3033
3034
		Jetpack_Options::delete_option( 'do_activate' );
3035
	}
3036
3037
	/**
3038
	 * Removes all connection options
3039
	 * @static
3040
	 */
3041
	public static function plugin_deactivation( ) {
3042
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3043
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3044
			Jetpack_Network::init()->deactivate();
3045
		} else {
3046
			Jetpack::disconnect( false );
3047
			//Jetpack_Heartbeat::init()->deactivate();
3048
		}
3049
	}
3050
3051
	/**
3052
	 * Disconnects from the Jetpack servers.
3053
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3054
	 * @static
3055
	 */
3056
	public static function disconnect( $update_activated_state = true ) {
3057
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3058
		Jetpack::clean_nonces( true );
3059
3060
		Jetpack::load_xml_rpc_client();
3061
		$xml = new Jetpack_IXR_Client();
3062
		$xml->query( 'jetpack.deregister' );
3063
3064
		Jetpack_Options::delete_option(
3065
			array(
3066
				'register',
3067
				'blog_token',
3068
				'user_token',
3069
				'user_tokens',
3070
				'master_user',
3071
				'time_diff',
3072
				'fallback_no_verify_ssl_certs',
3073
			)
3074
		);
3075
3076
		if ( $update_activated_state ) {
3077
			Jetpack_Options::update_option( 'activated', 4 );
3078
		}
3079
3080
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
3081
		// Check then record unique disconnection if site has never been disconnected previously
3082
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
3083
			$jetpack_unique_connection['disconnected'] = 1;
3084
		}
3085
		else {
3086
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3087
				//track unique disconnect
3088
				$jetpack = Jetpack::init();
3089
3090
				$jetpack->stat( 'connections', 'unique-disconnect' );
3091
				$jetpack->do_stats( 'server_side' );
3092
			}
3093
			// increment number of times disconnected
3094
			$jetpack_unique_connection['disconnected'] += 1;
3095
		}
3096
3097
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3098
3099
		// Disable the Heartbeat cron
3100
		Jetpack_Heartbeat::init()->deactivate();
3101
	}
3102
3103
	/**
3104
	 * Unlinks the current user from the linked WordPress.com user
3105
	 */
3106
	public static function unlink_user( $user_id = null ) {
3107
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3108
			return false;
3109
3110
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3111
3112
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3113
			return false;
3114
3115
		if ( ! isset( $tokens[ $user_id ] ) )
3116
			return false;
3117
3118
		Jetpack::load_xml_rpc_client();
3119
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3120
		$xml->query( 'jetpack.unlink_user', $user_id );
3121
3122
		unset( $tokens[ $user_id ] );
3123
3124
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3125
3126
		/**
3127
		 * Fires after the current user has been unlinked from WordPress.com.
3128
		 *
3129
		 * @since 4.1.0
3130
		 *
3131
		 * @param int $user_id The current user's ID.
3132
		 */
3133
		do_action( 'jetpack_unlinked_user', $user_id );
3134
3135
		return true;
3136
	}
3137
3138
	/**
3139
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3140
	 */
3141
	public static function try_registration() {
3142
		// Let's get some testing in beta versions and such.
3143
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3144
			// Before attempting to connect, let's make sure that the domains are viable.
3145
			$domains_to_check = array_unique( array(
3146
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3147
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3148
			) );
3149
			foreach ( $domains_to_check as $domain ) {
3150
				$result = Jetpack_Data::is_usable_domain( $domain );
3151
				if ( is_wp_error( $result ) ) {
3152
					return $result;
3153
				}
3154
			}
3155
		}
3156
3157
		$result = Jetpack::register();
3158
3159
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3160
		if ( ! $result || is_wp_error( $result ) ) {
3161
			return $result;
3162
		} else {
3163
			return true;
3164
		}
3165
	}
3166
3167
	/**
3168
	 * Tracking an internal event log. Try not to put too much chaff in here.
3169
	 *
3170
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3171
	 */
3172
	public static function log( $code, $data = null ) {
3173
		// only grab the latest 200 entries
3174
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3175
3176
		// Append our event to the log
3177
		$log_entry = array(
3178
			'time'    => time(),
3179
			'user_id' => get_current_user_id(),
3180
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3181
			'code'    => $code,
3182
		);
3183
		// Don't bother storing it unless we've got some.
3184
		if ( ! is_null( $data ) ) {
3185
			$log_entry['data'] = $data;
3186
		}
3187
		$log[] = $log_entry;
3188
3189
		// Try add_option first, to make sure it's not autoloaded.
3190
		// @todo: Add an add_option method to Jetpack_Options
3191
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3192
			Jetpack_Options::update_option( 'log', $log );
3193
		}
3194
3195
		/**
3196
		 * Fires when Jetpack logs an internal event.
3197
		 *
3198
		 * @since 3.0.0
3199
		 *
3200
		 * @param array $log_entry {
3201
		 *	Array of details about the log entry.
3202
		 *
3203
		 *	@param string time Time of the event.
3204
		 *	@param int user_id ID of the user who trigerred the event.
3205
		 *	@param int blog_id Jetpack Blog ID.
3206
		 *	@param string code Unique name for the event.
3207
		 *	@param string data Data about the event.
3208
		 * }
3209
		 */
3210
		do_action( 'jetpack_log_entry', $log_entry );
3211
	}
3212
3213
	/**
3214
	 * Get the internal event log.
3215
	 *
3216
	 * @param $event (string) - only return the specific log events
3217
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3218
	 *
3219
	 * @return array of log events || WP_Error for invalid params
3220
	 */
3221
	public static function get_log( $event = false, $num = false ) {
3222
		if ( $event && ! is_string( $event ) ) {
3223
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3224
		}
3225
3226
		if ( $num && ! is_numeric( $num ) ) {
3227
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3228
		}
3229
3230
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3231
3232
		// If nothing set - act as it did before, otherwise let's start customizing the output
3233
		if ( ! $num && ! $event ) {
3234
			return $entire_log;
3235
		} else {
3236
			$entire_log = array_reverse( $entire_log );
3237
		}
3238
3239
		$custom_log_output = array();
3240
3241
		if ( $event ) {
3242
			foreach ( $entire_log as $log_event ) {
3243
				if ( $event == $log_event[ 'code' ] ) {
3244
					$custom_log_output[] = $log_event;
3245
				}
3246
			}
3247
		} else {
3248
			$custom_log_output = $entire_log;
3249
		}
3250
3251
		if ( $num ) {
3252
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3253
		}
3254
3255
		return $custom_log_output;
3256
	}
3257
3258
	/**
3259
	 * Log modification of important settings.
3260
	 */
3261
	public static function log_settings_change( $option, $old_value, $value ) {
3262
		switch( $option ) {
3263
			case 'jetpack_sync_non_public_post_stati':
3264
				self::log( $option, $value );
3265
				break;
3266
		}
3267
	}
3268
3269
	/**
3270
	 * Return stat data for WPCOM sync
3271
	 */
3272
	function get_stat_data() {
3273
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3274
		$additional_data = $this->get_additional_stat_data();
3275
3276
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3277
	}
3278
3279
	/**
3280
	 * Get additional stat data to sync to WPCOM
3281
	 */
3282
	function get_additional_stat_data( $prefix = '' ) {
3283
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3284
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3285
		$return["{$prefix}users"]          = count_users();
3286
		$return["{$prefix}site-count"]     = 0;
3287
		if ( function_exists( 'get_blog_count' ) ) {
3288
			$return["{$prefix}site-count"] = get_blog_count();
3289
		}
3290
		return $return;
3291
	}
3292
3293
	/* Admin Pages */
3294
3295
	function admin_init() {
3296
		// If the plugin is not connected, display a connect message.
3297
		if (
3298
			// the plugin was auto-activated and needs its candy
3299
			Jetpack_Options::get_option( 'do_activate' )
3300
		||
3301
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3302
			! Jetpack_Options::get_option( 'activated' )
3303
		) {
3304
			Jetpack::plugin_initialize();
3305
		}
3306
3307
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3308
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3309
				// Show connect notice on dashboard and plugins pages
3310
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3311
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3312
			}
3313
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3314
			// Upgrade: 1.1 -> 1.1.1
3315
			// Check and see if host can verify the Jetpack servers' SSL certificate
3316
			$args = array();
3317
			Jetpack_Client::_wp_remote_request(
3318
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3319
				$args,
3320
				true
3321
			);
3322
		} else {
3323
			// Show the notice on the Dashboard only for now
3324
3325
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3326
3327
			// Identity crisis notices
3328
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3329
		}
3330
3331
		// If the plugin has just been disconnected from WP.com, show the survey notice
3332
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3333
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3334
		}
3335
3336
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3337
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3338
		}
3339
3340
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3341
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3342
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3343
3344
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3345
			// Artificially throw errors in certain whitelisted cases during plugin activation
3346
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3347
3348
			// Kick off synchronization of user role when it changes
3349
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3350
		}
3351
3352
		// Jetpack Manage Activation Screen from .com
3353
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3354
3355
		// Add custom column in wp-admin/users.php to show whether user is linked.
3356
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3357
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3358
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3359
	}
3360
3361
	function admin_body_class( $admin_body_class = '' ) {
3362
		$classes = explode( ' ', trim( $admin_body_class ) );
3363
3364
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3365
3366
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3367
		return " $admin_body_class ";
3368
	}
3369
3370
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3371
		return $admin_body_class . ' jetpack-pagestyles ';
3372
	}
3373
3374
	function prepare_connect_notice() {
3375
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3376
3377
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3378
3379
		if ( Jetpack::state( 'network_nag' ) )
3380
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3381
	}
3382
	/**
3383
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3384
	 *
3385
	 * @return null
3386
	 */
3387
	function prepare_manage_jetpack_notice() {
3388
3389
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3390
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3391
	}
3392
3393
	function manage_activate_screen() {
3394
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3395
	}
3396
	/**
3397
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3398
	 * This function artificially throws errors for such cases (whitelisted).
3399
	 *
3400
	 * @param string $plugin The activated plugin.
3401
	 */
3402
	function throw_error_on_activate_plugin( $plugin ) {
3403
		$active_modules = Jetpack::get_active_modules();
3404
3405
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3406
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3407
			$throw = false;
3408
3409
			// Try and make sure it really was the stats plugin
3410
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3411
				if ( 'stats.php' == basename( $plugin ) ) {
3412
					$throw = true;
3413
				}
3414
			} else {
3415
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3416
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3417
					$throw = true;
3418
				}
3419
			}
3420
3421
			if ( $throw ) {
3422
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3423
			}
3424
		}
3425
	}
3426
3427
	function intercept_plugin_error_scrape_init() {
3428
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3429
	}
3430
3431
	function intercept_plugin_error_scrape( $action, $result ) {
3432
		if ( ! $result ) {
3433
			return;
3434
		}
3435
3436
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3437
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3438
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3439
			}
3440
		}
3441
	}
3442
3443
	function add_remote_request_handlers() {
3444
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3445
	}
3446
3447
	function remote_request_handlers() {
3448
		switch ( current_filter() ) {
3449
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3450
			$response = $this->upload_handler();
3451
			break;
3452
		default :
3453
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3454
			break;
3455
		}
3456
3457
		if ( ! $response ) {
3458
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3459
		}
3460
3461
		if ( is_wp_error( $response ) ) {
3462
			$status_code       = $response->get_error_data();
3463
			$error             = $response->get_error_code();
3464
			$error_description = $response->get_error_message();
3465
3466
			if ( ! is_int( $status_code ) ) {
3467
				$status_code = 400;
3468
			}
3469
3470
			status_header( $status_code );
3471
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3472
		}
3473
3474
		status_header( 200 );
3475
		if ( true === $response ) {
3476
			exit;
3477
		}
3478
3479
		die( json_encode( (object) $response ) );
3480
	}
3481
3482
	function upload_handler() {
3483
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3484
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3485
		}
3486
3487
		$user = wp_authenticate( '', '' );
3488
		if ( ! $user || is_wp_error( $user ) ) {
3489
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3490
		}
3491
3492
		wp_set_current_user( $user->ID );
3493
3494
		if ( ! current_user_can( 'upload_files' ) ) {
3495
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3496
		}
3497
3498
		if ( empty( $_FILES ) ) {
3499
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3500
		}
3501
3502
		foreach ( array_keys( $_FILES ) as $files_key ) {
3503
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3504
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3505
			}
3506
		}
3507
3508
		$media_keys = array_keys( $_FILES['media'] );
3509
3510
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3511
		if ( ! $token || is_wp_error( $token ) ) {
3512
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3513
		}
3514
3515
		$uploaded_files = array();
3516
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3517
		unset( $GLOBALS['post'] );
3518
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3519
			$file = array();
3520
			foreach ( $media_keys as $media_key ) {
3521
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3522
			}
3523
3524
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3525
3526
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3527
			if ( $hmac_provided !== $hmac_file ) {
3528
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3529
				continue;
3530
			}
3531
3532
			$_FILES['.jetpack.upload.'] = $file;
3533
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3534
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3535
				$post_id = 0;
3536
			}
3537
			$attachment_id = media_handle_upload(
3538
				'.jetpack.upload.',
3539
				$post_id,
3540
				array(),
3541
				array(
3542
					'action' => 'jetpack_upload_file',
3543
				)
3544
			);
3545
3546
			if ( ! $attachment_id ) {
3547
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3548
			} elseif ( is_wp_error( $attachment_id ) ) {
3549
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3550
			} else {
3551
				$attachment = get_post( $attachment_id );
3552
				$uploaded_files[$index] = (object) array(
3553
					'id'   => (string) $attachment_id,
3554
					'file' => $attachment->post_title,
3555
					'url'  => wp_get_attachment_url( $attachment_id ),
3556
					'type' => $attachment->post_mime_type,
3557
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3558
				);
3559
			}
3560
		}
3561
		if ( ! is_null( $global_post ) ) {
3562
			$GLOBALS['post'] = $global_post;
3563
		}
3564
3565
		return $uploaded_files;
3566
	}
3567
3568
	/**
3569
	 * Add help to the Jetpack page
3570
	 *
3571
	 * @since Jetpack (1.2.3)
3572
	 * @return false if not the Jetpack page
3573
	 */
3574
	function admin_help() {
3575
		$current_screen = get_current_screen();
3576
3577
		// Overview
3578
		$current_screen->add_help_tab(
3579
			array(
3580
				'id'		=> 'home',
3581
				'title'		=> __( 'Home', 'jetpack' ),
3582
				'content'	=>
3583
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3584
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3585
					'<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>',
3586
			)
3587
		);
3588
3589
		// Screen Content
3590
		if ( current_user_can( 'manage_options' ) ) {
3591
			$current_screen->add_help_tab(
3592
				array(
3593
					'id'		=> 'settings',
3594
					'title'		=> __( 'Settings', 'jetpack' ),
3595
					'content'	=>
3596
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3597
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3598
						'<ol>' .
3599
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3600
							'<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>' .
3601
						'</ol>' .
3602
						'<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>'
3603
				)
3604
			);
3605
		}
3606
3607
		// Help Sidebar
3608
		$current_screen->set_help_sidebar(
3609
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3610
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3611
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3612
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3613
		);
3614
	}
3615
3616
	function admin_menu_css() {
3617
		wp_enqueue_style( 'jetpack-icons' );
3618
	}
3619
3620
	function admin_menu_order() {
3621
		return true;
3622
	}
3623
3624 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3625
		$jp_menu_order = array();
3626
3627
		foreach ( $menu_order as $index => $item ) {
3628
			if ( $item != 'jetpack' ) {
3629
				$jp_menu_order[] = $item;
3630
			}
3631
3632
			if ( $index == 0 ) {
3633
				$jp_menu_order[] = 'jetpack';
3634
			}
3635
		}
3636
3637
		return $jp_menu_order;
3638
	}
3639
3640
	function admin_head() {
3641 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3642
			/** This action is documented in class.jetpack-admin-page.php */
3643
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3644
	}
3645
3646
	function admin_banner_styles() {
3647
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3648
3649
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3650
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3651
		wp_style_add_data( 'jetpack', 'suffix', $min );
3652
	}
3653
3654
	function admin_scripts() {
3655
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3656
		wp_localize_script(
3657
			'jetpack-js',
3658
			'jetpackL10n',
3659
			array(
3660
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3661
				'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?",
3662
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3663
			)
3664
		);
3665
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3666
	}
3667
3668
	function plugin_action_links( $actions ) {
3669
3670
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3671
3672
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3673
			return array_merge(
3674
				$jetpack_home,
3675
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3676
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3677
				$actions
3678
				);
3679
			}
3680
3681
		return array_merge( $jetpack_home, $actions );
3682
	}
3683
3684
	function admin_connect_notice() {
3685
		// Don't show the connect notice anywhere but the plugins.php after activating
3686
		$current = get_current_screen();
3687
		if ( 'plugins' !== $current->parent_base )
3688
			return;
3689
3690
		if ( ! current_user_can( 'jetpack_connect' ) )
3691
			return;
3692
3693
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3694
		?>
3695
		<div id="message" class="updated jp-banner">
3696
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3697
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3698
					<div class="jp-banner__description-container">
3699
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3700
						<p class="jp-banner__description"><?php _e( 'Please connect to or create a WordPress.com account to enable Jetpack, including powerful security, traffic, and customization services.', 'jetpack' ); ?></p>
3701
						<p class="jp-banner__button-container">
3702
							<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3703
							<a href="<?php echo Jetpack::admin_url( 'admin.php?page=jetpack' ) ?>" class="button" title="<?php esc_attr_e( 'Learn about the benefits you receive when you connect Jetpack to WordPress.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3704
						</p>
3705
					</div>
3706 View Code Duplication
			<?php else : ?>
3707
				<div class="jp-banner__content">
3708
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3709
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3710
				</div>
3711
				<div class="jp-banner__action-container">
3712
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3713
				</div>
3714
			<?php endif; ?>
3715
		</div>
3716
3717
		<?php
3718
	}
3719
3720
	/**
3721
	 * This is the first banner
3722
	 * It should be visible only to user that can update the option
3723
	 * Are not connected
3724
	 *
3725
	 * @return null
3726
	 */
3727
	function admin_jetpack_manage_notice() {
3728
		$screen = get_current_screen();
3729
3730
		// Don't show the connect notice on the jetpack settings page.
3731
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3732
			return;
3733
3734
		// Only show it if don't have the managment option set.
3735
		// And not dismissed it already.
3736
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3737
			return;
3738
		}
3739
3740
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3741
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3742
		/**
3743
		 * I think it would be great to have different wordsing depending on where you are
3744
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3745
		 * etc..
3746
		 */
3747
3748
		?>
3749
		<div id="message" class="updated jp-banner">
3750
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3751
				<div class="jp-banner__description-container">
3752
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3753
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3754
					<p class="jp-banner__button-container">
3755
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3756
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3757
					</p>
3758
				</div>
3759
		</div>
3760
		<?php
3761
	}
3762
3763
	/**
3764
	 * Returns the url that the user clicks to remove the notice for the big banner
3765
	 * @return (string)
3766
	 */
3767
	function opt_out_jetpack_manage_url() {
3768
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3769
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3770
	}
3771
	/**
3772
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3773
	 * @return (string)
3774
	 */
3775
	function opt_in_jetpack_manage_url() {
3776
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3777
	}
3778
3779
	function opt_in_jetpack_manage_notice() {
3780
		?>
3781
		<div class="wrap">
3782
			<div id="message" class="jetpack-message is-opt-in">
3783
				<?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(), 'https://jetpack.com/support/site-management' ); ?>
3784
			</div>
3785
		</div>
3786
		<?php
3787
3788
	}
3789
	/**
3790
	 * Determines whether to show the notice of not true = display notice
3791
	 * @return (bool)
3792
	 */
3793
	function can_display_jetpack_manage_notice() {
3794
		// never display the notice to users that can't do anything about it anyways
3795
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3796
			return false;
3797
3798
		// don't display if we are in development more
3799
		if( Jetpack::is_development_mode() ) {
3800
			return false;
3801
		}
3802
		// don't display if the site is private
3803
		if(  ! Jetpack_Options::get_option( 'public' ) )
3804
			return false;
3805
3806
		/**
3807
		 * Should the Jetpack Remote Site Management notice be displayed.
3808
		 *
3809
		 * @since 3.3.0
3810
		 *
3811
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3812
		 */
3813
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3814
	}
3815
3816
	function network_connect_notice() {
3817
		?>
3818
		<div id="message" class="updated jetpack-message">
3819
			<div class="squeezer">
3820
				<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>
3821
			</div>
3822
		</div>
3823
		<?php
3824
	}
3825
3826
	public static function jetpack_comment_notice() {
3827
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3828
			return '';
3829
		}
3830
3831
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3832
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3833
3834
		if ( $jetpack_old_version ) {
3835
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3836
				return '';
3837
			}
3838
		}
3839
3840
		if ( $jetpack_new_version ) {
3841
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3842
				return '';
3843
			}
3844
		}
3845
3846
		return '<br /><br />' . sprintf(
3847
			__( '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' ),
3848
			wp_nonce_url(
3849
				Jetpack::admin_url(
3850
					array(
3851
						'page'   => 'jetpack',
3852
						'action' => 'activate',
3853
						'module' => 'comments',
3854
					)
3855
				),
3856
				'jetpack_activate-comments'
3857
			),
3858
			__( 'click here', 'jetpack' )
3859
		);
3860
	}
3861
3862
	/**
3863
	 * Show the survey link when the user has just disconnected Jetpack.
3864
	 */
3865
	function disconnect_survey_notice() {
3866
		?>
3867
		<div class="wrap">
3868
			<div id="message" class="jetpack-message stay-visible">
3869
				<div class="squeezer">
3870
					<h2>
3871
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3872
						<br />
3873
						<?php echo sprintf(
3874
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3875
							'https://jetpack.com/survey-disconnected/',
3876
							'_blank'
3877
						); ?>
3878
					</h2>
3879
				</div>
3880
			</div>
3881
		</div>
3882
		<?php
3883
	}
3884
3885
	/*
3886
	 * Registration flow:
3887
	 * 1 - ::admin_page_load() action=register
3888
	 * 2 - ::try_registration()
3889
	 * 3 - ::register()
3890
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3891
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3892
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3893
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3894
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3895
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3896
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3897
	 *       jetpack_id, jetpack_secret, jetpack_public
3898
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3899
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3900
	 * 5 - user logs in with WP.com account
3901
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3902
	 *		- Jetpack_Client_Server::authorize()
3903
	 *		- Jetpack_Client_Server::get_token()
3904
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3905
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3906
	 *			- which responds with access_token, token_type, scope
3907
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3908
	 *		- Jetpack::activate_default_modules()
3909
	 *     		- Deactivates deprecated plugins
3910
	 *     		- Activates all default modules
3911
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3912
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3913
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3914
	 *     Done!
3915
	 */
3916
3917
	/**
3918
	 * Handles the page load events for the Jetpack admin page
3919
	 */
3920
	function admin_page_load() {
3921
		$error = false;
3922
3923
		// Make sure we have the right body class to hook stylings for subpages off of.
3924
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3925
3926
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3927
			// Should only be used in intermediate redirects to preserve state across redirects
3928
			Jetpack::restate();
3929
		}
3930
3931
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3932
			// User clicked in the iframe to link their accounts
3933
			if ( ! Jetpack::is_user_connected() ) {
3934
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3935
				if ( isset( $_GET['notes_iframe'] ) )
3936
					$connect_url .= '&notes_iframe';
3937
				wp_redirect( $connect_url );
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
			} else {
3940
				Jetpack::state( 'message', 'already_authorized' );
3941
				wp_safe_redirect( Jetpack::admin_url() );
3942
				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...
3943
			}
3944
		}
3945
3946
3947
		if ( isset( $_GET['action'] ) ) {
3948
			switch ( $_GET['action'] ) {
3949
			case 'authorize':
3950
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3951
					Jetpack::state( 'message', 'already_authorized' );
3952
					wp_safe_redirect( Jetpack::admin_url() );
3953
					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...
3954
				}
3955
				Jetpack::log( 'authorize' );
3956
				$client_server = new Jetpack_Client_Server;
3957
				$client_server->client_authorize();
3958
				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...
3959
			case 'register' :
3960
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3961
					$error = 'cheatin';
3962
					break;
3963
				}
3964
				check_admin_referer( 'jetpack-register' );
3965
				Jetpack::log( 'register' );
3966
				Jetpack::maybe_set_version_option();
3967
				$registered = Jetpack::try_registration();
3968
				if ( is_wp_error( $registered ) ) {
3969
					$error = $registered->get_error_code();
3970
					Jetpack::state( 'error_description', $registered->get_error_message() );
3971
					break;
3972
				}
3973
3974
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3975
3976
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3977
				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...
3978
			case 'activate' :
3979
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3980
					$error = 'cheatin';
3981
					break;
3982
				}
3983
3984
				$module = stripslashes( $_GET['module'] );
3985
				check_admin_referer( "jetpack_activate-$module" );
3986
				Jetpack::log( 'activate', $module );
3987
				Jetpack::activate_module( $module );
3988
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3989
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3990
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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