Completed
Push — add/seo-framework-conflict-og ( 37b773 )
by Jeremy
10:40
created

class.jetpack.php (18 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
		 * Do things that should run even in the network admin
374
		 * here, before we potentially fail out.
375
		 */
376
		add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
377
378
		/**
379
		 * We need sync object even in Multisite mode
380
		 */
381
		$this->sync = new Jetpack_Sync;
382
383
		/**
384
		 * Trigger a wp_version sync when updating WP versions
385
		 **/
386
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
387
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
388
389
		add_action( 'init', array( $this, 'sync_update_data') );
390
		add_action( 'init', array( $this, 'sync_theme_data' ) );
391
392
		/*
393
		 * Load things that should only be in Network Admin.
394
		 *
395
		 * For now blow away everything else until a more full
396
		 * understanding of what is needed at the network level is
397
		 * available
398
		 */
399
		if( is_multisite() ) {
400
			Jetpack_Network::init();
401
402
			// Only sync this info if we are on a multi site
403
			// @since  3.7
404
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
405
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
406
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
407
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
408
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
409
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
410
411
			if( is_network_admin() ) {
412
				// Sync network site data if it is updated or not.
413
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
414
				return; // End here to prevent single site actions from firing
415
			}
416
		}
417
418
419
		$theme_slug = get_option( 'stylesheet' );
420
421
422
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
423
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
424
		$this->sync->options(
425
			JETPACK__PLUGIN_DIR . 'jetpack.php',
426
			'home',
427
			'siteurl',
428
			'blogname',
429
			'gmt_offset',
430
			'timezone_string',
431
			'security_report',
432
			'stylesheet',
433
			"theme_mods_{$theme_slug}",
434
			'jetpack_sync_non_public_post_stati',
435
			'jetpack_options',
436
			'site_icon', // (int) - ID of core's Site Icon attachment ID
437
			'default_post_format',
438
			'default_category',
439
			'large_size_w',
440
			'large_size_h',
441
			'thumbnail_size_w',
442
			'thumbnail_size_h',
443
			'medium_size_w',
444
			'medium_size_h',
445
			'thumbnail_crop',
446
			'image_default_link_type'
447
		);
448
449
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
450
			$this->sync->options( __FILE__, 'jetpack_' . $option );
451
		}
452
453
		/**
454
		 * Sometimes you want to sync data to .com without adding options to .org sites.
455
		 * The mock option allows you to do just that.
456
		 */
457
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
458
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
459
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
460
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
461
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
462
463
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
464
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
465
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
466
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
467
468
		/**
469
		 * Trigger an update to the main_network_site when we update the blogname of a site.
470
		 *
471
		 */
472
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
473
474
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
475
476
		// Update the settings everytime the we register a new user to the site or we delete a user.
477
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
478
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
479
480
		// Unlink user before deleting the user from .com
481
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
482
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
483
484
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
485
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
486
487
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
488
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
489
490
			$this->require_jetpack_authentication();
491
492
			if ( Jetpack::is_active() ) {
493
				// Hack to preserve $HTTP_RAW_POST_DATA
494
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
495
496
				$signed = $this->verify_xml_rpc_signature();
497
				if ( $signed && ! is_wp_error( $signed ) ) {
498
					// The actual API methods.
499
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
500
				} else {
501
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
502
					// active Jetpack connection, so that additional users can link their account.
503
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
504
				}
505
			} else {
506
				// The bootstrap API methods.
507
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
508
			}
509
510
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
511
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
512
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
513
			$this->require_jetpack_authentication();
514
			$this->add_remote_request_handlers();
515
		} else {
516
			if ( Jetpack::is_active() ) {
517
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
518
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
519
			}
520
		}
521
522
		if ( Jetpack::is_active() ) {
523
			Jetpack_Heartbeat::init();
524
		}
525
526
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
527
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
528
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
529
		}
530
531
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
532
533
		add_action( 'admin_init', array( $this, 'admin_init' ) );
534
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
535
536
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
537
538
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
539
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
540
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
541
542
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
543
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
544
545
		// Jump Start AJAX callback function
546
		add_action( 'wp_ajax_jetpack_jumpstart_ajax',  array( $this, 'jetpack_jumpstart_ajax_callback' ) );
547
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
548
549
		// Identity Crisis AJAX callback function
550
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
551
552
		// JITM AJAX callback function
553
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
554
555
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
556
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
557
558
		// Universal ajax callback for all tracking events triggered via js
559
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
560
561
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
562
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
563
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
564
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
565
566
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
567
568
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
569
570
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
571
572
		/**
573
		 * These actions run checks to load additional files.
574
		 * They check for external files or plugins, so they need to run as late as possible.
575
		 */
576
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
577
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
578
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
579
580
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
581
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
582
583
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
584
585
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
586
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
587
588
		// A filter to control all just in time messages
589
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
590
591
		/**
592
		 * This is the hack to concatinate all css files into one.
593
		 * For description and reasoning see the implode_frontend_css method
594
		 *
595
		 * Super late priority so we catch all the registered styles
596
		 */
597
		if( !is_admin() ) {
598
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
599
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
600
		}
601
602
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
603
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
604
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
605
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
606
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
607
608
	}
609
610
	/*
611
	 * Make sure any site icon added to core can get
612
	 * synced back to dotcom, so we can display it there.
613
	 */
614
	function jetpack_sync_core_icon() {
615
		if ( function_exists( 'get_site_icon_url' ) ) {
616
			$url = get_site_icon_url();
617
		} else {
618
			return;
619
		}
620
621
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
622
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
623
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
624
			// This is the option that is synced with dotcom
625
			Jetpack_Options::update_option( 'site_icon_url', $url );
626
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
627
			Jetpack_Options::delete_option( 'site_icon_url' );
628
		}
629
	}
630
631
	function jetpack_admin_ajax_tracks_callback() {
632
		// Check for nonce
633
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
634
			wp_die( 'Permissions check failed.' );
635
		}
636
637
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
638
			wp_die( 'No valid event name or type.' );
639
		}
640
641
		$tracks_data = array();
642
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
643
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
644
		}
645
646
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
647
		wp_send_json_success();
648
		wp_die();
649
	}
650
651
	function jetpack_admin_ajax_callback() {
652
		// Check for nonce
653 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
654
			wp_die( 'permissions check failed' );
655
		}
656
657
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
658
			$slug = $_REQUEST['thisModuleSlug'];
659
660
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
661
				wp_die( 'That is not a Jetpack module slug' );
662
			}
663
664
			if ( Jetpack::is_module_active( $slug ) ) {
665
				Jetpack::deactivate_module( $slug );
666
			} else {
667
				Jetpack::activate_module( $slug, false, false );
668
			}
669
670
			$modules = Jetpack_Admin::init()->get_modules();
671
			echo json_encode( $modules[ $slug ] );
672
673
			exit;
674
		}
675
676
		wp_die();
677
	}
678
679
	/*
680
	 * Sometimes we need to refresh the data,
681
	 * especially if the page is visited via a 'history'
682
	 * event like back/forward
683
	 */
684
	function jetpack_admin_ajax_refresh_data() {
685
		// Check for nonce
686 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
687
			wp_die( 'permissions check failed' );
688
		}
689
690
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
691
			$modules = Jetpack_Admin::init()->get_modules();
692
			echo json_encode( $modules );
693
			exit;
694
		}
695
696
		wp_die();
697
	}
698
699
	/**
700
	 * The callback for the Jump Start ajax requests.
701
	 */
702
	function jetpack_jumpstart_ajax_callback() {
703
		// Check for nonce
704
		if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
705
			wp_die( 'permissions check failed' );
706
707
		if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
708
			// Update the jumpstart option
709
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
710
				Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
711
			}
712
713
			// Loops through the requested "Jump Start" modules, and activates them.
714
			// Custom 'no_message' state, so that no message will be shown on reload.
715
			$modules = $_REQUEST['jumpstartModSlug'];
716
			$module_slugs = array();
717
			foreach( $modules as $module => $value ) {
718
				$module_slugs[] = $value['module_slug'];
719
			}
720
721
			// Check for possible conflicting plugins
722
			$module_slugs_filtered = $this->filter_default_modules( $module_slugs );
723
724
			foreach ( $module_slugs_filtered as $module_slug ) {
725
				Jetpack::log( 'activate', $module_slug );
726
				Jetpack::activate_module( $module_slug, false, false );
727
				Jetpack::state( 'message', 'no_message' );
728
			}
729
730
			// Set the default sharing buttons and set to display on posts if none have been set.
731
			$sharing_services = get_option( 'sharing-services' );
732
			$sharing_options  = get_option( 'sharing-options' );
733
			if ( empty( $sharing_services['visible'] ) ) {
734
				// Default buttons to set
735
				$visible = array(
736
					'twitter',
737
					'facebook',
738
					'google-plus-1',
739
				);
740
				$hidden = array();
741
742
				// Set some sharing settings
743
				$sharing = new Sharing_Service();
744
				$sharing_options['global'] = array(
745
					'button_style'  => 'icon',
746
					'sharing_label' => $sharing->default_sharing_label,
747
					'open_links'    => 'same',
748
					'show'          => array( 'post' ),
749
					'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
750
				);
751
752
				update_option( 'sharing-options', $sharing_options );
753
754
				// Send a success response so that we can display an error message.
755
				$success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
756
				echo json_encode( $success );
757
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method jetpack_jumpstart_ajax_callback() contains an exit expression.

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

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

Loading history...
758
			}
759
760
		} elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
761
			// If dismissed, flag the jumpstart option as such.
762
			// Send a success response so that we can display an error message.
763
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
764
				$success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
765
				echo json_encode( $success );
766
				exit;
767
			}
768
769
		} elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
770
771
			// FOR TESTING ONLY
772
			// @todo remove
773
			$modules = (array) $_REQUEST['jumpstartModSlug'];
774
			foreach( $modules as $module => $value ) {
775
				if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
776
					Jetpack::log( 'deactivate', $value['module_slug'] );
777
					Jetpack::deactivate_module( $value['module_slug'] );
778
					Jetpack::state( 'message', 'no_message' );
779
				} else {
780
					Jetpack::log( 'activate', $value['module_slug'] );
781
					Jetpack::activate_module( $value['module_slug'], false, false );
782
					Jetpack::state( 'message', 'no_message' );
783
				}
784
			}
785
786
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
787
			echo "reload the page";
788
		}
789
790
		wp_die();
791
	}
792
793
	/**
794
	 * The callback for the JITM ajax requests.
795
	 */
796
	function jetpack_jitm_ajax_callback() {
797
		// Check for nonce
798
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
799
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
800
		}
801
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
802
			$module_slug = $_REQUEST['jitmModule'];
803
			Jetpack::log( 'activate', $module_slug );
804
			Jetpack::activate_module( $module_slug, false, false );
805
			Jetpack::state( 'message', 'no_message' );
806
807
			//A Jetpack module is being activated through a JITM, track it
808
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
809
			$this->do_stats( 'server_side' );
810
811
			wp_send_json_success();
812
		}
813
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
814
			// get the hide_jitm options array
815
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
816
			$module_slug = $_REQUEST['jitmModule'];
817
818
			if( ! $jetpack_hide_jitm ) {
819
				$jetpack_hide_jitm = array(
820
					$module_slug => 'hide'
821
				);
822
			} else {
823
				$jetpack_hide_jitm[$module_slug] = 'hide';
824
			}
825
826
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
827
828
			//jitm is being dismissed forever, track it
829
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
830
			$this->do_stats( 'server_side' );
831
832
			wp_send_json_success();
833
		}
834 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
835
			$module_slug = $_REQUEST['jitmModule'];
836
837
			// User went to WordPress.com, track this
838
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
839
			$this->do_stats( 'server_side' );
840
841
			wp_send_json_success();
842
		}
843 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
844
			$track = $_REQUEST['jitmModule'];
845
846
			// User is viewing JITM, track it.
847
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
848
			$this->do_stats( 'server_side' );
849
850
			wp_send_json_success();
851
		}
852
	}
853
854
	/**
855
	 * If there are any stats that need to be pushed, but haven't been, push them now.
856
	 */
857
	function __destruct() {
858
		if ( ! empty( $this->stats ) ) {
859
			$this->do_stats( 'server_side' );
860
		}
861
	}
862
863
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
864
		switch( $cap ) {
865
			case 'jetpack_connect' :
866
			case 'jetpack_reconnect' :
867
				if ( Jetpack::is_development_mode() ) {
868
					$caps = array( 'do_not_allow' );
869
					break;
870
				}
871
				/**
872
				 * Pass through. If it's not development mode, these should match disconnect.
873
				 * Let users disconnect if it's development mode, just in case things glitch.
874
				 */
875
			case 'jetpack_disconnect' :
876
				/**
877
				 * In multisite, can individual site admins manage their own connection?
878
				 *
879
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
880
				 */
881
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
882
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
883
						/**
884
						 * We need to update the option name -- it's terribly unclear which
885
						 * direction the override goes.
886
						 *
887
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
888
						 */
889
						$caps = array( 'do_not_allow' );
890
						break;
891
					}
892
				}
893
894
				$caps = array( 'manage_options' );
895
				break;
896
			case 'jetpack_manage_modules' :
897
			case 'jetpack_activate_modules' :
898
			case 'jetpack_deactivate_modules' :
899
				$caps = array( 'manage_options' );
900
				break;
901
			case 'jetpack_configure_modules' :
902
				$caps = array( 'manage_options' );
903
				break;
904
			case 'jetpack_network_admin_page':
905
			case 'jetpack_network_settings_page':
906
				$caps = array( 'manage_network_plugins' );
907
				break;
908
			case 'jetpack_network_sites_page':
909
				$caps = array( 'manage_sites' );
910
				break;
911
			case 'jetpack_admin_page' :
912
				if ( Jetpack::is_development_mode() ) {
913
					$caps = array( 'manage_options' );
914
					break;
915
				}
916
917
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
918
				if ( ! current_user_can( 'edit_posts' ) ) {
919
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
920
						// We need this in order to unlink the user.
921
						$this->admin_page_load();
922
					}
923
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
924
						$caps = array( 'do_not_allow' );
925
						break;
926
					}
927
				}
928
929
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
930
					$caps = array( 'do_not_allow' );
931
					break;
932
				}
933
				/**
934
				 * Pass through. If it's not development mode, these should match the admin page.
935
				 * Let users disconnect if it's development mode, just in case things glitch.
936
				 */
937
			case 'jetpack_connect_user' :
938
				if ( Jetpack::is_development_mode() ) {
939
					$caps = array( 'do_not_allow' );
940
					break;
941
				}
942
				$caps = array( 'read' );
943
				break;
944
		}
945
		return $caps;
946
	}
947
948
	function require_jetpack_authentication() {
949
		// Don't let anyone authenticate
950
		$_COOKIE = array();
951
		remove_all_filters( 'authenticate' );
952
953
		/**
954
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
955
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
956
		 * generate false-positives.
957
		 */
958
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
959
960
		if ( Jetpack::is_active() ) {
961
			// Allow Jetpack authentication
962
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
963
		}
964
	}
965
966
	/**
967
	 * Load language files
968
	 */
969
	public static function plugin_textdomain() {
970
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
971
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
972
	}
973
974
	/**
975
	 * Register assets for use in various modules and the Jetpack admin page.
976
	 *
977
	 * @uses wp_script_is, wp_register_script, plugins_url
978
	 * @action wp_loaded
979
	 * @return null
980
	 */
981
	public function register_assets() {
982
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
983
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
984
		}
985
986 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
987
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
988
		}
989
990 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
991
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
992
		}
993
994 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
995
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
996
		}
997
998
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
999
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
1000
1001
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1002
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1003
			if ( ! is_numeric( $fb_app_id ) ) {
1004
				$fb_app_id = '';
1005
			}
1006
			wp_localize_script(
1007
				'jetpack-facebook-embed',
1008
				'jpfbembed',
1009
				array(
1010
					'appid' => $fb_app_id,
1011
					'locale' => $this->get_locale(),
1012
				)
1013
			);
1014
		}
1015
1016
		/**
1017
		 * As jetpack_register_genericons is by default fired off a hook,
1018
		 * the hook may have already fired by this point.
1019
		 * So, let's just trigger it manually.
1020
		 */
1021
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1022
		jetpack_register_genericons();
1023
1024 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1025
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1026
	}
1027
1028
	/**
1029
	 * Guess locale from language code.
1030
	 *
1031
	 * @param string $lang Language code.
1032
	 * @return string|bool
1033
	 */
1034 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1035
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1036
			return 'en_US';
1037
		}
1038
1039
		if ( ! class_exists( 'GP_Locales' ) ) {
1040
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1041
				return false;
1042
			}
1043
1044
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1045
		}
1046
1047
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1048
			// WP.com: get_locale() returns 'it'
1049
			$locale = GP_Locales::by_slug( $lang );
1050
		} else {
1051
			// Jetpack: get_locale() returns 'it_IT';
1052
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1053
		}
1054
1055
		if ( ! $locale ) {
1056
			return false;
1057
		}
1058
1059
		if ( empty( $locale->facebook_locale ) ) {
1060
			if ( empty( $locale->wp_locale ) ) {
1061
				return false;
1062
			} else {
1063
				// Facebook SDK is smart enough to fall back to en_US if a
1064
				// locale isn't supported. Since supported Facebook locales
1065
				// can fall out of sync, we'll attempt to use the known
1066
				// wp_locale value and rely on said fallback.
1067
				return $locale->wp_locale;
1068
			}
1069
		}
1070
1071
		return $locale->facebook_locale;
1072
	}
1073
1074
	/**
1075
	 * Get the locale.
1076
	 *
1077
	 * @return string|bool
1078
	 */
1079
	function get_locale() {
1080
		$locale = $this->guess_locale_from_lang( get_locale() );
1081
1082
		if ( ! $locale ) {
1083
			$locale = 'en_US';
1084
		}
1085
1086
		return $locale;
1087
	}
1088
1089
	/**
1090
	 * Device Pixels support
1091
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1092
	 */
1093
	function devicepx() {
1094
		if ( Jetpack::is_active() ) {
1095
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
1096
		}
1097
	}
1098
1099
	/*
1100
	 * Returns the location of Jetpack's lib directory. This filter is applied
1101
	 * in require_lib().
1102
	 *
1103
	 * @filter require_lib_dir
1104
	 */
1105
	function require_lib_dir() {
1106
		return JETPACK__PLUGIN_DIR . '_inc/lib';
1107
	}
1108
1109
	/**
1110
	 * Return the network_site_url so that .com knows what network this site is a part of.
1111
	 * @param  bool $option
1112
	 * @return string
1113
	 */
1114
	public function jetpack_main_network_site_option( $option ) {
1115
		return network_site_url();
1116
	}
1117
	/**
1118
	 * Network Name.
1119
	 */
1120
	static function network_name( $option = null ) {
1121
		global $current_site;
1122
		return $current_site->site_name;
1123
	}
1124
	/**
1125
	 * Does the network allow new user and site registrations.
1126
	 * @return string
1127
	 */
1128
	static function network_allow_new_registrations( $option = null ) {
1129
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1130
	}
1131
	/**
1132
	 * Does the network allow admins to add new users.
1133
	 * @return boolian
1134
	 */
1135
	static function network_add_new_users( $option = null ) {
1136
		return (bool) get_site_option( 'add_new_users' );
1137
	}
1138
	/**
1139
	 * File upload psace left per site in MB.
1140
	 *  -1 means NO LIMIT.
1141
	 * @return number
1142
	 */
1143
	static function network_site_upload_space( $option = null ) {
1144
		// value in MB
1145
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1146
	}
1147
1148
	/**
1149
	 * Network allowed file types.
1150
	 * @return string
1151
	 */
1152
	static function network_upload_file_types( $option = null ) {
1153
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1154
	}
1155
1156
	/**
1157
	 * Maximum file upload size set by the network.
1158
	 * @return number
1159
	 */
1160
	static function network_max_upload_file_size( $option = null ) {
1161
		// value in KB
1162
		return get_site_option( 'fileupload_maxk', 300 );
1163
	}
1164
1165
	/**
1166
	 * Lets us know if a site allows admins to manage the network.
1167
	 * @return array
1168
	 */
1169
	static function network_enable_administration_menus( $option = null ) {
1170
		return get_site_option( 'menu_items' );
1171
	}
1172
1173
	/**
1174
	 * Return whether we are dealing with a multi network setup or not.
1175
	 * The reason we are type casting this is because we want to avoid the situation where
1176
	 * the result is false since when is_main_network_option return false it cases
1177
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1178
	 * database which could be set to anything as opposed to what this function returns.
1179
	 * @param  bool  $option
1180
	 *
1181
	 * @return boolean
1182
	 */
1183
	public function is_main_network_option( $option ) {
1184
		// return '1' or ''
1185
		return (string) (bool) Jetpack::is_multi_network();
1186
	}
1187
1188
	/**
1189
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1190
	 *
1191
	 * @param  string  $option
1192
	 * @return boolean
1193
	 */
1194
	public function is_multisite( $option ) {
1195
		return (string) (bool) is_multisite();
1196
	}
1197
1198
	/**
1199
	 * Implemented since there is no core is multi network function
1200
	 * Right now there is no way to tell if we which network is the dominant network on the system
1201
	 *
1202
	 * @since  3.3
1203
	 * @return boolean
1204
	 */
1205
	public static function is_multi_network() {
1206
		global  $wpdb;
1207
1208
		// if we don't have a multi site setup no need to do any more
1209
		if ( ! is_multisite() ) {
1210
			return false;
1211
		}
1212
1213
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1214
		if ( $num_sites > 1 ) {
1215
			return true;
1216
		} else {
1217
			return false;
1218
		}
1219
	}
1220
1221
	/**
1222
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1223
	 * @return null
1224
	 */
1225
	function update_jetpack_main_network_site_option() {
1226
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1227
		/**
1228
		 * Fires when the site URL is updated.
1229
		 * Determines if the site is the main site of a Mulitiste network.
1230
		 *
1231
		 * @since 3.3.0
1232
		 *
1233
		 * @param string jetpack_main_network_site.
1234
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1235
		 */
1236
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1237
		/**
1238
		 * Fires when the site URL is updated.
1239
		 * Determines if the is part of a multi network.
1240
		 *
1241
		 * @since 3.3.0
1242
		 *
1243
		 * @param string jetpack_is_main_network.
1244
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1245
		 */
1246
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1247
		/**
1248
		 * Fires when the site URL is updated.
1249
		 * Determines if the site is part of a multisite network.
1250
		 *
1251
		 * @since 3.4.0
1252
		 *
1253
		 * @param string jetpack_is_multi_site.
1254
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1255
		 */
1256
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1257
	}
1258
	/**
1259
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1260
	 *
1261
	 */
1262
	function update_jetpack_network_settings() {
1263
		// Only sync this info for the main network site.
1264
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1265
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1266
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1267
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1268
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1269
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1270
1271
	}
1272
1273
	/**
1274
	 * Get back if the current site is single user site.
1275
	 *
1276
	 * @return bool
1277
	 */
1278
	public static function is_single_user_site() {
1279
1280
		$user_query = new WP_User_Query( array(
1281
			'blog_id' => get_current_blog_id(),
1282
			'fields'  => 'ID',
1283
			'number' => 2
1284
		) );
1285
		return 1 === (int) $user_query->get_total();
1286
	}
1287
1288
	/**
1289
	 * Returns true if the site has file write access false otherwise.
1290
	 * @return string ( '1' | '0' )
1291
	 **/
1292
	public static function file_system_write_access() {
1293
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1294
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1295
		}
1296
1297
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1298
1299
		$filesystem_method = get_filesystem_method();
1300
		if ( $filesystem_method === 'direct' ) {
1301
			return 1;
1302
		}
1303
1304
		ob_start();
1305
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1306
		ob_end_clean();
1307
		if ( $filesystem_credentials_are_stored ) {
1308
			return 1;
1309
		}
1310
		return 0;
1311
	}
1312
1313
	/**
1314
	 * Finds out if a site is using a version control system.
1315
	 * @return string ( '1' | '0' )
1316
	 **/
1317
	public static function is_version_controlled() {
1318
1319
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1320
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1321
		}
1322
		$updater = new WP_Automatic_Updater();
1323
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1324
		// transients should not be empty
1325
		if ( empty( $is_version_controlled ) ) {
1326
			$is_version_controlled = '0';
1327
		}
1328
		return $is_version_controlled;
1329
	}
1330
1331
	/**
1332
	 * Determines whether the current theme supports featured images or not.
1333
	 * @return string ( '1' | '0' )
1334
	 */
1335
	public static function featured_images_enabled() {
1336
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1337
	}
1338
1339
	/*
1340
	 * Sync back wp_version
1341
	 */
1342
	public static function get_wp_version() {
1343
		global $wp_version;
1344
		return $wp_version;
1345
	}
1346
1347
	/**
1348
	 * Keeps wp_version in sync with .com when WordPress core updates
1349
	 **/
1350
	public static function update_get_wp_version( $update, $meta_data ) {
1351
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1352
			/** This action is documented in wp-includes/option.php */
1353
			/**
1354
			 * This triggers the sync for the jetpack version
1355
			 * See Jetpack_Sync options method for more info.
1356
			 */
1357
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1358
		}
1359
	}
1360
1361
	/**
1362
	 * Triggers a sync of update counts and update details
1363
	 */
1364
	function sync_update_data() {
1365
		// Anytime WordPress saves update data, we'll want to sync update data
1366
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1367
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1368
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1369
		// Anytime a connection to jetpack is made, sync the update data
1370
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1371
		// Anytime the Jetpack Version changes, sync the the update data
1372
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1373
1374
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1375
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1376
		}
1377
1378
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1379
	}
1380
1381
	/**
1382
	 * Triggers a sync of information specific to the current theme.
1383
	 */
1384
	function sync_theme_data() {
1385
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1386
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1387
	}
1388
1389
	/**
1390
	 * jetpack_updates is saved in the following schema:
1391
	 *
1392
	 * array (
1393
	 *      'plugins'                       => (int) Number of plugin updates available.
1394
	 *      'themes'                        => (int) Number of theme updates available.
1395
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1396
	 *      'translations'                  => (int) Number of translation updates available.
1397
	 *      'total'                         => (int) Total of all available updates.
1398
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1399
	 * )
1400
	 * @return array
1401
	 */
1402
	public static function get_updates() {
1403
		$update_data = wp_get_update_data();
1404
1405
		// Stores the individual update counts as well as the total count.
1406
		if ( isset( $update_data['counts'] ) ) {
1407
			$updates = $update_data['counts'];
1408
		}
1409
1410
		// If we need to update WordPress core, let's find the latest version number.
1411 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1412
			$cur = get_preferred_from_update_core();
1413
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1414
				$updates['wp_update_version'] = $cur->current;
1415
			}
1416
		}
1417
		return isset( $updates ) ? $updates : array();
1418
	}
1419
1420
	public static function get_update_details() {
1421
		$update_details = array(
1422
			'update_core' => get_site_transient( 'update_core' ),
1423
			'update_plugins' => get_site_transient( 'update_plugins' ),
1424
			'update_themes' => get_site_transient( 'update_themes' ),
1425
		);
1426
		return $update_details;
1427
	}
1428
1429
	public static function refresh_update_data() {
1430
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1431
			/**
1432
			 * Fires whenever the amount of updates needed for a site changes.
1433
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1434
			 *
1435
			 * @since 3.7.0
1436
			 *
1437
			 * @param string jetpack_updates
1438
			 * @param array Update counts calculated by Jetpack::get_updates
1439
			 */
1440
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1441
		}
1442
		/**
1443
		 * Fires whenever the amount of updates needed for a site changes.
1444
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1445
		 *
1446
		 * @since 3.7.0
1447
		 *
1448
		 * @param string jetpack_update_details
1449
		 * @param array Update details calculated by Jetpack::get_update_details
1450
		 */
1451
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1452
	}
1453
1454
	public static function refresh_theme_data() {
1455
		/**
1456
		 * Fires whenever a theme change is made.
1457
		 *
1458
		 * @since 3.8.1
1459
		 *
1460
		 * @param string featured_images_enabled
1461
		 * @param boolean Whether featured images are enabled or not
1462
		 */
1463
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1464
	}
1465
1466
	/**
1467
	 * Invalides the transient as well as triggers the update of the mock option.
1468
	 *
1469
	 * @return null
1470
	 */
1471
	function is_single_user_site_invalidate() {
1472
		/**
1473
		 * Fires when a user is added or removed from a site.
1474
		 * Determines if the site is a single user site.
1475
		 *
1476
		 * @since 3.4.0
1477
		 *
1478
		 * @param string jetpack_single_user_site.
1479
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1480
		 */
1481
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1482
	}
1483
1484
	/**
1485
	 * Is Jetpack active?
1486
	 */
1487
	public static function is_active() {
1488
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1489
	}
1490
1491
	/**
1492
	 * Is Jetpack in development (offline) mode?
1493
	 */
1494
	public static function is_development_mode() {
1495
		$development_mode = false;
1496
1497
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1498
			$development_mode = JETPACK_DEV_DEBUG;
1499
		}
1500
1501
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1502
			$development_mode = true;
1503
		}
1504
		/**
1505
		 * Filters Jetpack's development mode.
1506
		 *
1507
		 * @see http://jetpack.com/support/development-mode/
1508
		 *
1509
		 * @since 2.2.1
1510
		 *
1511
		 * @param bool $development_mode Is Jetpack's development mode active.
1512
		 */
1513
		return apply_filters( 'jetpack_development_mode', $development_mode );
1514
	}
1515
1516
	/**
1517
	* Get Jetpack development mode notice text and notice class.
1518
	*
1519
	* Mirrors the checks made in Jetpack::is_development_mode
1520
	*
1521
	*/
1522
	public static function show_development_mode_notice() {
1523
		if ( Jetpack::is_development_mode() ) {
1524
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1525
				$notice = sprintf(
1526
					/* translators: %s is a URL */
1527
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1528
					'http://jetpack.com/support/development-mode/'
1529
				);
1530
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1531
				$notice = sprintf(
1532
					/* translators: %s is a URL */
1533
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1534
					'http://jetpack.com/support/development-mode/'
1535
				);
1536
			} else {
1537
				$notice = sprintf(
1538
					/* translators: %s is a URL */
1539
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1540
					'http://jetpack.com/support/development-mode/'
1541
				);
1542
			}
1543
1544
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1545
		}
1546
1547
		// Throw up a notice if using a development version and as for feedback.
1548
		if ( Jetpack::is_development_version() ) {
1549
			/* translators: %s is a URL */
1550
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1551
1552
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1553
		}
1554
		// Throw up a notice if using staging mode
1555
		if ( Jetpack::is_staging_site() ) {
1556
			/* translators: %s is a URL */
1557
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1558
1559
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1560
		}
1561
	}
1562
1563
	/**
1564
	 * Whether Jetpack's version maps to a public release, or a development version.
1565
	 */
1566
	public static function is_development_version() {
1567
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1568
	}
1569
1570
	/**
1571
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1572
	 */
1573
	public static function is_user_connected( $user_id = false ) {
1574
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1575
		if ( ! $user_id ) {
1576
			return false;
1577
		}
1578
		return (bool) Jetpack_Data::get_access_token( $user_id );
1579
	}
1580
1581
	/**
1582
	 * Get the wpcom user data of the current|specified connected user.
1583
	 */
1584 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1585
		if ( ! $user_id ) {
1586
			$user_id = get_current_user_id();
1587
		}
1588
		Jetpack::load_xml_rpc_client();
1589
		$xml = new Jetpack_IXR_Client( array(
1590
			'user_id' => $user_id,
1591
		) );
1592
		$xml->query( 'wpcom.getUser' );
1593
		if ( ! $xml->isError() ) {
1594
			return $xml->getResponse();
1595
		}
1596
		return false;
1597
	}
1598
1599
	/**
1600
	 * Get the wpcom email of the current|specified connected user.
1601
	 */
1602 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1603
		if ( ! $user_id ) {
1604
			$user_id = get_current_user_id();
1605
		}
1606
		Jetpack::load_xml_rpc_client();
1607
		$xml = new Jetpack_IXR_Client( array(
1608
			'user_id' => $user_id,
1609
		) );
1610
		$xml->query( 'wpcom.getUserEmail' );
1611
		if ( ! $xml->isError() ) {
1612
			return $xml->getResponse();
1613
		}
1614
		return false;
1615
	}
1616
1617
	/**
1618
	 * Get the wpcom email of the master user.
1619
	 */
1620
	public static function get_master_user_email() {
1621
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1622
		if ( $master_user_id ) {
1623
			return self::get_connected_user_email( $master_user_id );
1624
		}
1625
		return '';
1626
	}
1627
1628
	function current_user_is_connection_owner() {
1629
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1630
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1631
	}
1632
1633
	/**
1634
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1635
	 */
1636
	function extra_oembed_providers() {
1637
		// Cloudup: https://dev.cloudup.com/#oembed
1638
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1639
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1640
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1641
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1642
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1643
	}
1644
1645
	/**
1646
	 * Synchronize connected user role changes
1647
	 */
1648
	function user_role_change( $user_id ) {
1649
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1650
			$current_user_id = get_current_user_id();
1651
			wp_set_current_user( $user_id );
1652
			$role = $this->translate_current_user_to_role();
1653
			$signed_role = $this->sign_role( $role );
1654
			wp_set_current_user( $current_user_id );
1655
1656
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1657
			$master_user_id = absint( $master_token->external_user_id );
1658
1659
			if ( ! $master_user_id )
1660
				return; // this shouldn't happen
1661
1662
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1663
			//@todo retry on failure
1664
1665
			//try to choose a new master if we're demoting the current one
1666
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1667
				$query = new WP_User_Query(
1668
					array(
1669
						'fields'  => array( 'id' ),
1670
						'role'    => 'administrator',
1671
						'orderby' => 'id',
1672
						'exclude' => array( $master_user_id ),
1673
					)
1674
				);
1675
				$new_master = false;
1676
				foreach ( $query->results as $result ) {
1677
					$uid = absint( $result->id );
1678
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1679
						$new_master = $uid;
1680
						break;
1681
					}
1682
				}
1683
1684
				if ( $new_master ) {
1685
					Jetpack_Options::update_option( 'master_user', $new_master );
1686
				}
1687
				// else disconnect..?
1688
			}
1689
		}
1690
	}
1691
1692
	/**
1693
	 * Loads the currently active modules.
1694
	 */
1695
	public static function load_modules() {
1696
		if ( ! self::is_active() && !self::is_development_mode() ) {
1697
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1698
				return;
1699
			}
1700
		}
1701
1702
		$version = Jetpack_Options::get_option( 'version' );
1703 View Code Duplication
		if ( ! $version ) {
1704
			$version = $old_version = JETPACK__VERSION . ':' . time();
1705
			/** This action is documented in class.jetpack.php */
1706
			do_action( 'updating_jetpack_version', $version, false );
1707
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1708
		}
1709
		list( $version ) = explode( ':', $version );
1710
1711
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1712
1713
		$modules_data = array();
1714
1715
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1716
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1717
			$updated_modules = array();
1718
			foreach ( $modules as $module ) {
1719
				$modules_data[ $module ] = Jetpack::get_module( $module );
1720
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1721
					continue;
1722
				}
1723
1724
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1725
					continue;
1726
				}
1727
1728
				$updated_modules[] = $module;
1729
			}
1730
1731
			$modules = array_diff( $modules, $updated_modules );
1732
		}
1733
1734
		$is_development_mode = Jetpack::is_development_mode();
1735
1736
		foreach ( $modules as $index => $module ) {
1737
			// If we're in dev mode, disable modules requiring a connection
1738
			if ( $is_development_mode ) {
1739
				// Prime the pump if we need to
1740
				if ( empty( $modules_data[ $module ] ) ) {
1741
					$modules_data[ $module ] = Jetpack::get_module( $module );
1742
				}
1743
				// If the module requires a connection, but we're in local mode, don't include it.
1744
				if ( $modules_data[ $module ]['requires_connection'] ) {
1745
					continue;
1746
				}
1747
			}
1748
1749
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1750
				continue;
1751
			}
1752
1753
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1754
				unset( $modules[ $index ] );
1755
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1756
				continue;
1757
			}
1758
1759
			/**
1760
			 * Fires when a specific module is loaded.
1761
			 * The dynamic part of the hook, $module, is the module slug.
1762
			 *
1763
			 * @since 1.1.0
1764
			 */
1765
			do_action( 'jetpack_module_loaded_' . $module );
1766
		}
1767
1768
		/**
1769
		 * Fires when all the modules are loaded.
1770
		 *
1771
		 * @since 1.1.0
1772
		 */
1773
		do_action( 'jetpack_modules_loaded' );
1774
1775
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
1776
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1777
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1778
	}
1779
1780
	/**
1781
	 * Check if Jetpack's REST API compat file should be included
1782
	 * @action plugins_loaded
1783
	 * @return null
1784
	 */
1785
	public function check_rest_api_compat() {
1786
		/**
1787
		 * Filters the list of REST API compat files to be included.
1788
		 *
1789
		 * @since 2.2.5
1790
		 *
1791
		 * @param array $args Array of REST API compat files to include.
1792
		 */
1793
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1794
1795
		if ( function_exists( 'bbpress' ) )
1796
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1797
1798
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1799
			require_once $_jetpack_rest_api_compat_include;
1800
	}
1801
1802
	/**
1803
	 * Gets all plugins currently active in values, regardless of whether they're
1804
	 * traditionally activated or network activated.
1805
	 *
1806
	 * @todo Store the result in core's object cache maybe?
1807
	 */
1808
	public static function get_active_plugins() {
1809
		$active_plugins = (array) get_option( 'active_plugins', array() );
1810
1811
		if ( is_multisite() ) {
1812
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1813
			// whereas active_plugins stores them in the values.
1814
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1815
			if ( $network_plugins ) {
1816
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1817
			}
1818
		}
1819
1820
		sort( $active_plugins );
1821
1822
		return array_unique( $active_plugins );
1823
	}
1824
1825
	/**
1826
	 * Gets and parses additional plugin data to send with the heartbeat data
1827
	 *
1828
	 * @since 3.8.1
1829
	 *
1830
	 * @return array Array of plugin data
1831
	 */
1832
	public static function get_parsed_plugin_data() {
1833
		if ( ! function_exists( 'get_plugins' ) ) {
1834
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1835
		}
1836
		$all_plugins    = get_plugins();
1837
		$active_plugins = Jetpack::get_active_plugins();
1838
1839
		$plugins = array();
1840
		foreach ( $all_plugins as $path => $plugin_data ) {
1841
			$plugins[ $path ] = array(
1842
					'is_active' => in_array( $path, $active_plugins ),
1843
					'file'      => $path,
1844
					'name'      => $plugin_data['Name'],
1845
					'version'   => $plugin_data['Version'],
1846
					'author'    => $plugin_data['Author'],
1847
			);
1848
		}
1849
1850
		return $plugins;
1851
	}
1852
1853
	/**
1854
	 * Gets and parses theme data to send with the heartbeat data
1855
	 *
1856
	 * @since 3.8.1
1857
	 *
1858
	 * @return array Array of theme data
1859
	 */
1860
	public static function get_parsed_theme_data() {
1861
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1862
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1863
1864
		$themes = array();
1865
		foreach ( $all_themes as $slug => $theme_data ) {
1866
			$theme_headers = array();
1867
			foreach ( $header_keys as $header_key ) {
1868
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1869
			}
1870
1871
			$themes[ $slug ] = array(
1872
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1873
					'slug' => $slug,
1874
					'theme_root' => $theme_data->get_theme_root_uri(),
1875
					'parent' => $theme_data->parent(),
1876
					'headers' => $theme_headers
1877
			);
1878
		}
1879
1880
		return $themes;
1881
	}
1882
1883
	/**
1884
	 * Checks whether a specific plugin is active.
1885
	 *
1886
	 * We don't want to store these in a static variable, in case
1887
	 * there are switch_to_blog() calls involved.
1888
	 */
1889
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1890
		return in_array( $plugin, self::get_active_plugins() );
1891
	}
1892
1893
	/**
1894
	 * Check if Jetpack's Open Graph tags should be used.
1895
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1896
	 *
1897
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1898
	 * @action plugins_loaded
1899
	 * @return null
1900
	 */
1901
	public function check_open_graph() {
1902
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1903
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1904
		}
1905
1906
		$active_plugins = self::get_active_plugins();
1907
1908
		if ( ! empty( $active_plugins ) ) {
1909
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1910
				if ( in_array( $plugin, $active_plugins ) ) {
1911
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1912
					break;
1913
				}
1914
			}
1915
		}
1916
1917
		/**
1918
		 * Allow the addition of Open Graph Meta Tags to all pages.
1919
		 *
1920
		 * @since 2.0.3
1921
		 *
1922
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1923
		 */
1924
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1925
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1926
		}
1927
	}
1928
1929
	/**
1930
	 * Check if Jetpack's Twitter tags should be used.
1931
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1932
	 *
1933
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1934
	 * @action plugins_loaded
1935
	 * @return null
1936
	 */
1937
	public function check_twitter_tags() {
1938
1939
		$active_plugins = self::get_active_plugins();
1940
1941
		if ( ! empty( $active_plugins ) ) {
1942
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1943
				if ( in_array( $plugin, $active_plugins ) ) {
1944
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1945
					break;
1946
				}
1947
			}
1948
		}
1949
1950
		/**
1951
		 * Allow Twitter Card Meta tags to be disabled.
1952
		 *
1953
		 * @since 2.6.0
1954
		 *
1955
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1956
		 */
1957
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1958
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1959
		}
1960
	}
1961
1962
1963
1964
1965
	/*
1966
	 *
1967
	 * Jetpack Security Reports
1968
	 *
1969
	 * Allowed types: login_form, backup, file_scanning, spam
1970
	 *
1971
	 * Args for login_form and spam: 'blocked'=>(int)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1972
	 *
1973
	 * Args for backup and file_scanning: 'last'=>(timestamp)(optional), 'next'=>(timestamp)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1974
	 *
1975
	 *
1976
	 * Example code to submit a security report:
1977
	 *
1978
	 *  function akismet_submit_jetpack_security_report() {
1979
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1980
	 *  }
1981
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1982
	 *
1983
	 */
1984
1985
1986
	/**
1987
	 * Calls for security report submissions.
1988
	 *
1989
	 * @return null
1990
	 */
1991
	public static function perform_security_reporting() {
1992
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1993
1994
		if ( $no_check_needed ) {
1995
			return;
1996
		}
1997
1998
		/**
1999
		 * Fires before a security report is created.
2000
		 *
2001
		 * @since 3.4.0
2002
		 */
2003
		do_action( 'jetpack_security_report' );
2004
2005
		Jetpack_Options::update_option( 'security_report', self::$security_report );
2006
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
2007
	}
2008
2009
	/**
2010
	 * Allows plugins to submit security reports.
2011
 	 *
2012
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2013
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2014
	 * @param array   $args         See definitions above
2015
	 */
2016
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2017
2018
		if( !doing_action( 'jetpack_security_report' ) ) {
2019
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
2020
		}
2021
2022
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
2023
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
2024
		}
2025
2026
		if( !function_exists( 'get_plugin_data' ) ) {
2027
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
2028
		}
2029
2030
		//Get rid of any non-allowed args
2031
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
2032
2033
		$plugin = get_plugin_data( $plugin_file );
2034
2035
		if ( !$plugin['Name'] ) {
2036
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
2037
		}
2038
2039
		// Sanitize everything to make sure we're not syncing something wonky
2040
		$type = sanitize_key( $type );
2041
2042
		$args['plugin'] = $plugin;
2043
2044
		// Cast blocked, last and next as integers.
2045
		// Last and next should be in unix timestamp format
2046
		if ( isset( $args['blocked'] ) ) {
2047
			$args['blocked'] = (int) $args['blocked'];
2048
		}
2049
		if ( isset( $args['last'] ) ) {
2050
			$args['last'] = (int) $args['last'];
2051
		}
2052
		if ( isset( $args['next'] ) ) {
2053
			$args['next'] = (int) $args['next'];
2054
		}
2055
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
2056
			$args['status'] = 'ok';
2057
		}
2058
		if ( isset( $args['message'] ) ) {
2059
2060
			if( $args['status'] == 'ok' ) {
2061
				unset( $args['message'] );
2062
			}
2063
2064
			$allowed_html = array(
2065
			    'a' => array(
2066
			        'href' => array(),
2067
			        'title' => array()
2068
			    ),
2069
			    'em' => array(),
2070
			    'strong' => array(),
2071
			);
2072
2073
			$args['message'] = wp_kses( $args['message'], $allowed_html );
2074
		}
2075
2076
		$plugin_name = $plugin[ 'Name' ];
2077
2078
		self::$security_report[ $type ][ $plugin_name ] = $args;
2079
	}
2080
2081
	/**
2082
	 * Collects a new report if needed, then returns it.
2083
	 */
2084
	public function get_security_report() {
2085
		self::perform_security_reporting();
2086
		return Jetpack_Options::get_option( 'security_report' );
2087
	}
2088
2089
2090
/* Jetpack Options API */
2091
2092
	public static function get_option_names( $type = 'compact' ) {
2093
		return Jetpack_Options::get_option_names( $type );
2094
	}
2095
2096
	/**
2097
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2098
 	 *
2099
	 * @param string $name    Option name
2100
	 * @param mixed  $default (optional)
2101
	 */
2102
	public static function get_option( $name, $default = false ) {
2103
		return Jetpack_Options::get_option( $name, $default );
2104
	}
2105
2106
	/**
2107
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
2108
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
2109
	* $name must be a registered option name.
2110
	*/
2111
	public static function create_nonce( $name ) {
2112
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
2113
2114
		Jetpack_Options::update_option( $name, $secret );
2115
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
2116
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2117
			return new Jetpack_Error( 'missing_secrets' );
2118
2119
		return array(
2120
			'secret_1' => $secret_1,
2121
			'secret_2' => $secret_2,
2122
			'eol'      => $eol,
2123
		);
2124
	}
2125
2126
	/**
2127
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2128
 	 *
2129
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2130
	 * @param string $name  Option name
2131
	 * @param mixed  $value Option value
2132
	 */
2133
	public static function update_option( $name, $value ) {
2134
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2135
		return Jetpack_Options::update_option( $name, $value );
2136
	}
2137
2138
	/**
2139
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2140
 	 *
2141
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2142
	 * @param array $array array( option name => option value, ... )
2143
	 */
2144
	public static function update_options( $array ) {
2145
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2146
		return Jetpack_Options::update_options( $array );
2147
	}
2148
2149
	/**
2150
	 * Deletes the given option.  May be passed multiple option names as an array.
2151
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2152
	 *
2153
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2154
	 * @param string|array $names
2155
	 */
2156
	public static function delete_option( $names ) {
2157
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2158
		return Jetpack_Options::delete_option( $names );
2159
	}
2160
2161
	/**
2162
	 * Enters a user token into the user_tokens option
2163
	 *
2164
	 * @param int $user_id
2165
	 * @param string $token
2166
	 * return bool
2167
	 */
2168
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2169
		// not designed for concurrent updates
2170
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2171
		if ( ! is_array( $user_tokens ) )
2172
			$user_tokens = array();
2173
		$user_tokens[$user_id] = $token;
2174
		if ( $is_master_user ) {
2175
			$master_user = $user_id;
2176
			$options     = compact( 'user_tokens', 'master_user' );
2177
		} else {
2178
			$options = compact( 'user_tokens' );
2179
		}
2180
		return Jetpack_Options::update_options( $options );
2181
	}
2182
2183
	/**
2184
	 * Returns an array of all PHP files in the specified absolute path.
2185
	 * Equivalent to glob( "$absolute_path/*.php" ).
2186
	 *
2187
	 * @param string $absolute_path The absolute path of the directory to search.
2188
	 * @return array Array of absolute paths to the PHP files.
2189
	 */
2190
	public static function glob_php( $absolute_path ) {
2191
		if ( function_exists( 'glob' ) ) {
2192
			return glob( "$absolute_path/*.php" );
2193
		}
2194
2195
		$absolute_path = untrailingslashit( $absolute_path );
2196
		$files = array();
2197
		if ( ! $dir = @opendir( $absolute_path ) ) {
2198
			return $files;
2199
		}
2200
2201
		while ( false !== $file = readdir( $dir ) ) {
2202
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2203
				continue;
2204
			}
2205
2206
			$file = "$absolute_path/$file";
2207
2208
			if ( ! is_file( $file ) ) {
2209
				continue;
2210
			}
2211
2212
			$files[] = $file;
2213
		}
2214
2215
		closedir( $dir );
2216
2217
		return $files;
2218
	}
2219
2220
	public static function activate_new_modules( $redirect = false ) {
2221
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2222
			return;
2223
		}
2224
2225
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2226 View Code Duplication
		if ( ! $jetpack_old_version ) {
2227
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2228
			/** This action is documented in class.jetpack.php */
2229
			do_action( 'updating_jetpack_version', $version, false );
2230
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2231
		}
2232
2233
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2234
2235
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2236
			return;
2237
		}
2238
2239
		$active_modules     = Jetpack::get_active_modules();
2240
		$reactivate_modules = array();
2241
		foreach ( $active_modules as $active_module ) {
2242
			$module = Jetpack::get_module( $active_module );
2243
			if ( ! isset( $module['changed'] ) ) {
2244
				continue;
2245
			}
2246
2247
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2248
				continue;
2249
			}
2250
2251
			$reactivate_modules[] = $active_module;
2252
			Jetpack::deactivate_module( $active_module );
2253
		}
2254
2255
		$new_version = JETPACK__VERSION . ':' . time();
2256
		/** This action is documented in class.jetpack.php */
2257
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2258
		Jetpack_Options::update_options(
2259
			array(
2260
				'version'     => $new_version,
2261
				'old_version' => $jetpack_old_version,
2262
			)
2263
		);
2264
2265
		Jetpack::state( 'message', 'modules_activated' );
2266
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2267
2268
		if ( $redirect ) {
2269
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2270
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2271
				$page = $_GET['page'];
2272
			}
2273
2274
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2275
			exit;
2276
		}
2277
	}
2278
2279
	/**
2280
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2281
	 * Make sure to tuck away module "library" files in a sub-directory.
2282
	 */
2283
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2284
		static $modules = null;
2285
2286
		if ( ! isset( $modules ) ) {
2287
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2288
			// Use the cache if we're on the front-end and it's available...
2289
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2290
				$modules = $available_modules_option[ JETPACK__VERSION ];
2291
			} else {
2292
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2293
2294
				$modules = array();
2295
2296
				foreach ( $files as $file ) {
2297
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2298
						continue;
2299
					}
2300
2301
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2302
				}
2303
2304
				Jetpack_Options::update_option( 'available_modules', array(
2305
					JETPACK__VERSION => $modules,
2306
				) );
2307
			}
2308
		}
2309
2310
		/**
2311
		 * Filters the array of modules available to be activated.
2312
		 *
2313
		 * @since 2.4.0
2314
		 *
2315
		 * @param array $modules Array of available modules.
2316
		 * @param string $min_version Minimum version number required to use modules.
2317
		 * @param string $max_version Maximum version number required to use modules.
2318
		 */
2319
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2320
2321
		if ( ! $min_version && ! $max_version ) {
2322
			return array_keys( $mods );
2323
		}
2324
2325
		$r = array();
2326
		foreach ( $mods as $slug => $introduced ) {
2327
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2328
				continue;
2329
			}
2330
2331
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2332
				continue;
2333
			}
2334
2335
			$r[] = $slug;
2336
		}
2337
2338
		return $r;
2339
	}
2340
2341
	/**
2342
	 * Default modules loaded on activation.
2343
	 */
2344
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2345
		$return = array();
2346
2347
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2348
			$module_data = Jetpack::get_module( $module );
2349
2350
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2351
				case 'yes' :
2352
					$return[] = $module;
2353
					break;
2354
				case 'public' :
2355
					if ( Jetpack_Options::get_option( 'public' ) ) {
2356
						$return[] = $module;
2357
					}
2358
					break;
2359
				case 'no' :
2360
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2361
					break;
2362
			}
2363
		}
2364
		/**
2365
		 * Filters the array of default modules.
2366
		 *
2367
		 * @since 2.5.0
2368
		 *
2369
		 * @param array $return Array of default modules.
2370
		 * @param string $min_version Minimum version number required to use modules.
2371
		 * @param string $max_version Maximum version number required to use modules.
2372
		 */
2373
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2374
	}
2375
2376
	/**
2377
	 * Checks activated modules during auto-activation to determine
2378
	 * if any of those modules are being deprecated.  If so, close
2379
	 * them out, and add any replacement modules.
2380
	 *
2381
	 * Runs at priority 99 by default.
2382
	 *
2383
	 * This is run late, so that it can still activate a module if
2384
	 * the new module is a replacement for another that the user
2385
	 * currently has active, even if something at the normal priority
2386
	 * would kibosh everything.
2387
	 *
2388
	 * @since 2.6
2389
	 * @uses jetpack_get_default_modules filter
2390
	 * @param array $modules
2391
	 * @return array
2392
	 */
2393
	function handle_deprecated_modules( $modules ) {
2394
		$deprecated_modules = array(
2395
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2396
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2397
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2398
		);
2399
2400
		// Don't activate SSO if they never completed activating WPCC.
2401
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2402
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2403
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2404
				$deprecated_modules['wpcc'] = null;
2405
			}
2406
		}
2407
2408
		foreach ( $deprecated_modules as $module => $replacement ) {
2409
			if ( Jetpack::is_module_active( $module ) ) {
2410
				self::deactivate_module( $module );
2411
				if ( $replacement ) {
2412
					$modules[] = $replacement;
2413
				}
2414
			}
2415
		}
2416
2417
		return array_unique( $modules );
2418
	}
2419
2420
	/**
2421
	 * Checks activated plugins during auto-activation to determine
2422
	 * if any of those plugins are in the list with a corresponding module
2423
	 * that is not compatible with the plugin. The module will not be allowed
2424
	 * to auto-activate.
2425
	 *
2426
	 * @since 2.6
2427
	 * @uses jetpack_get_default_modules filter
2428
	 * @param array $modules
2429
	 * @return array
2430
	 */
2431
	function filter_default_modules( $modules ) {
2432
2433
		$active_plugins = self::get_active_plugins();
2434
2435
		if ( ! empty( $active_plugins ) ) {
2436
2437
			// For each module we'd like to auto-activate...
2438
			foreach ( $modules as $key => $module ) {
2439
				// If there are potential conflicts for it...
2440
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2441
					// For each potential conflict...
2442
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2443
						// If that conflicting plugin is active...
2444
						if ( in_array( $plugin, $active_plugins ) ) {
2445
							// Remove that item from being auto-activated.
2446
							unset( $modules[ $key ] );
2447
						}
2448
					}
2449
				}
2450
			}
2451
		}
2452
2453
		return $modules;
2454
	}
2455
2456
	/**
2457
	 * Extract a module's slug from its full path.
2458
	 */
2459
	public static function get_module_slug( $file ) {
2460
		return str_replace( '.php', '', basename( $file ) );
2461
	}
2462
2463
	/**
2464
	 * Generate a module's path from its slug.
2465
	 */
2466
	public static function get_module_path( $slug ) {
2467
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2468
	}
2469
2470
	/**
2471
	 * Load module data from module file. Headers differ from WordPress
2472
	 * plugin headers to avoid them being identified as standalone
2473
	 * plugins on the WordPress plugins page.
2474
	 */
2475
	public static function get_module( $module ) {
2476
		$headers = array(
2477
			'name'                      => 'Module Name',
2478
			'description'               => 'Module Description',
2479
			'jumpstart_desc'            => 'Jumpstart Description',
2480
			'sort'                      => 'Sort Order',
2481
			'recommendation_order'      => 'Recommendation Order',
2482
			'introduced'                => 'First Introduced',
2483
			'changed'                   => 'Major Changes In',
2484
			'deactivate'                => 'Deactivate',
2485
			'free'                      => 'Free',
2486
			'requires_connection'       => 'Requires Connection',
2487
			'auto_activate'             => 'Auto Activate',
2488
			'module_tags'               => 'Module Tags',
2489
			'feature'                   => 'Feature',
2490
			'additional_search_queries' => 'Additional Search Queries',
2491
		);
2492
2493
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2494
2495
		$mod = Jetpack::get_file_data( $file, $headers );
2496
		if ( empty( $mod['name'] ) ) {
2497
			return false;
2498
		}
2499
2500
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2501
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2502
		$mod['deactivate']              = empty( $mod['deactivate'] );
2503
		$mod['free']                    = empty( $mod['free'] );
2504
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2505
2506
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2507
			$mod['auto_activate'] = 'No';
2508
		} else {
2509
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2510
		}
2511
2512
		if ( $mod['module_tags'] ) {
2513
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2514
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2515
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2516
		} else {
2517
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2518
		}
2519
2520
		if ( $mod['feature'] ) {
2521
			$mod['feature'] = explode( ',', $mod['feature'] );
2522
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2523
		} else {
2524
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2525
		}
2526
2527
		/**
2528
		 * Filters the feature array on a module.
2529
		 *
2530
		 * This filter allows you to control where each module is filtered: Recommended,
2531
		 * Jumpstart, and the default "Other" listing.
2532
		 *
2533
		 * @since 3.5.0
2534
		 *
2535
		 * @param array   $mod['feature'] The areas to feature this module:
2536
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2537
		 *     'Recommended' shows on the main Jetpack admin screen.
2538
		 *     'Other' should be the default if no other value is in the array.
2539
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2540
		 * @param array   $mod All the currently assembled module data.
2541
		 */
2542
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2543
2544
		/**
2545
		 * Filter the returned data about a module.
2546
		 *
2547
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2548
		 * so please be careful.
2549
		 *
2550
		 * @since 3.6.0
2551
		 *
2552
		 * @param array   $mod    The details of the requested module.
2553
		 * @param string  $module The slug of the module, e.g. sharedaddy
2554
		 * @param string  $file   The path to the module source file.
2555
		 */
2556
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2557
	}
2558
2559
	/**
2560
	 * Like core's get_file_data implementation, but caches the result.
2561
	 */
2562
	public static function get_file_data( $file, $headers ) {
2563
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2564
		$file_name = basename( $file );
2565
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2566
		$key              = md5( $file_name . serialize( $headers ) );
2567
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2568
2569
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2570
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2571
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2572
		}
2573
2574
		$data = get_file_data( $file, $headers );
2575
2576
		// Strip out any old Jetpack versions that are cluttering the option.
2577
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2578
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2579
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2580
2581
		return $data;
2582
	}
2583
2584
	/**
2585
	 * Return translated module tag.
2586
	 *
2587
	 * @param string $tag Tag as it appears in each module heading.
2588
	 *
2589
	 * @return mixed
2590
	 */
2591
	public static function translate_module_tag( $tag ) {
2592
		return jetpack_get_module_i18n_tag( $tag );
2593
	}
2594
2595
	/**
2596
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2597
	 *
2598
	 * @since 3.9.2
2599
	 *
2600
	 * @param array $modules
2601
	 *
2602
	 * @return string|void
2603
	 */
2604
	public static function get_translated_modules( $modules ) {
2605
		foreach ( $modules as $index => $module ) {
2606
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2607
			if ( isset( $module['name'] ) ) {
2608
				$modules[ $index ]['name'] = $i18n_module['name'];
2609
			}
2610
			if ( isset( $module['description'] ) ) {
2611
				$modules[ $index ]['description'] = $i18n_module['description'];
2612
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2613
			}
2614
		}
2615
		return $modules;
2616
	}
2617
2618
	/**
2619
	 * Get a list of activated modules as an array of module slugs.
2620
	 */
2621
	public static function get_active_modules() {
2622
		$active = Jetpack_Options::get_option( 'active_modules' );
2623
		if ( ! is_array( $active ) )
2624
			$active = array();
2625
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2626
			$active[] = 'vaultpress';
2627
		} else {
2628
			$active = array_diff( $active, array( 'vaultpress' ) );
2629
		}
2630
2631
		//If protect is active on the main site of a multisite, it should be active on all sites.
2632
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2633
			$active[] = 'protect';
2634
		}
2635
2636
		return array_unique( $active );
2637
	}
2638
2639
	/**
2640
	 * Check whether or not a Jetpack module is active.
2641
	 *
2642
	 * @param string $module The slug of a Jetpack module.
2643
	 * @return bool
2644
	 *
2645
	 * @static
2646
	 */
2647
	public static function is_module_active( $module ) {
2648
		return in_array( $module, self::get_active_modules() );
2649
	}
2650
2651
	public static function is_module( $module ) {
2652
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2653
	}
2654
2655
	/**
2656
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2657
	 *
2658
	 * @param bool $catch True to start catching, False to stop.
2659
	 *
2660
	 * @static
2661
	 */
2662
	public static function catch_errors( $catch ) {
2663
		static $display_errors, $error_reporting;
2664
2665
		if ( $catch ) {
2666
			$display_errors  = @ini_set( 'display_errors', 1 );
2667
			$error_reporting = @error_reporting( E_ALL );
2668
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2669
		} else {
2670
			@ini_set( 'display_errors', $display_errors );
2671
			@error_reporting( $error_reporting );
2672
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2673
		}
2674
	}
2675
2676
	/**
2677
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2678
	 */
2679
	public static function catch_errors_on_shutdown() {
2680
		Jetpack::state( 'php_errors', ob_get_clean() );
2681
	}
2682
2683
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2684
		$jetpack = Jetpack::init();
2685
2686
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2687
		$modules = array_merge( $other_modules, $modules );
2688
2689
		// Look for standalone plugins and disable if active.
2690
2691
		$to_deactivate = array();
2692
		foreach ( $modules as $module ) {
2693
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2694
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2695
			}
2696
		}
2697
2698
		$deactivated = array();
2699
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2700
			list( $probable_file, $probable_title ) = $deactivate_me;
2701
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2702
				$deactivated[] = $module;
2703
			}
2704
		}
2705
2706
		if ( $deactivated && $redirect ) {
2707
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2708
2709
			$url = add_query_arg(
2710
				array(
2711
					'action'   => 'activate_default_modules',
2712
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2713
				),
2714
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2715
			);
2716
			wp_safe_redirect( $url );
2717
			exit;
2718
		}
2719
2720
		/**
2721
		 * Fires before default modules are activated.
2722
		 *
2723
		 * @since 1.9.0
2724
		 *
2725
		 * @param string $min_version Minimum version number required to use modules.
2726
		 * @param string $max_version Maximum version number required to use modules.
2727
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2728
		 */
2729
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2730
2731
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2732
		Jetpack::restate();
2733
		Jetpack::catch_errors( true );
2734
2735
		$active = Jetpack::get_active_modules();
2736
2737
		foreach ( $modules as $module ) {
2738
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2739
				$active[] = $module;
2740
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2741
				continue;
2742
			}
2743
2744
			if ( in_array( $module, $active ) ) {
2745
				$module_info = Jetpack::get_module( $module );
2746
				if ( ! $module_info['deactivate'] ) {
2747
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2748 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2749
						$active_state = explode( ',', $active_state );
2750
					} else {
2751
						$active_state = array();
2752
					}
2753
					$active_state[] = $module;
2754
					Jetpack::state( $state, implode( ',', $active_state ) );
2755
				}
2756
				continue;
2757
			}
2758
2759
			$file = Jetpack::get_module_path( $module );
2760
			if ( ! file_exists( $file ) ) {
2761
				continue;
2762
			}
2763
2764
			// we'll override this later if the plugin can be included without fatal error
2765
			if ( $redirect ) {
2766
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2767
			}
2768
			Jetpack::state( 'error', 'module_activation_failed' );
2769
			Jetpack::state( 'module', $module );
2770
			ob_start();
2771
			require $file;
2772
			/**
2773
			 * Fires when a specific module is activated.
2774
			 *
2775
			 * @since 1.9.0
2776
			 *
2777
			 * @param string $module Module slug.
2778
			 */
2779
			do_action( 'jetpack_activate_module', $module );
2780
			$active[] = $module;
2781
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2782 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2783
				$active_state = explode( ',', $active_state );
2784
			} else {
2785
				$active_state = array();
2786
			}
2787
			$active_state[] = $module;
2788
			Jetpack::state( $state, implode( ',', $active_state ) );
2789
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2790
			ob_end_clean();
2791
		}
2792
		Jetpack::state( 'error', false );
2793
		Jetpack::state( 'module', false );
2794
		Jetpack::catch_errors( false );
2795
		/**
2796
		 * Fires when default modules are activated.
2797
		 *
2798
		 * @since 1.9.0
2799
		 *
2800
		 * @param string $min_version Minimum version number required to use modules.
2801
		 * @param string $max_version Maximum version number required to use modules.
2802
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2803
		 */
2804
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2805
	}
2806
2807
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2808
		/**
2809
		 * Fires before a module is activated.
2810
		 *
2811
		 * @since 2.6.0
2812
		 *
2813
		 * @param string $module Module slug.
2814
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2815
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2816
		 */
2817
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2818
2819
		$jetpack = Jetpack::init();
2820
2821
		if ( ! strlen( $module ) )
2822
			return false;
2823
2824
		if ( ! Jetpack::is_module( $module ) )
2825
			return false;
2826
2827
		// If it's already active, then don't do it again
2828
		$active = Jetpack::get_active_modules();
2829
		foreach ( $active as $act ) {
2830
			if ( $act == $module )
2831
				return true;
2832
		}
2833
2834
		$module_data = Jetpack::get_module( $module );
2835
2836
		if ( ! Jetpack::is_active() ) {
2837
			if ( !Jetpack::is_development_mode() )
2838
				return false;
2839
2840
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2841
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2842
				return false;
2843
		}
2844
2845
		// Check and see if the old plugin is active
2846
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2847
			// Deactivate the old plugin
2848
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2849
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2850
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2851
				Jetpack::state( 'deactivated_plugins', $module );
2852
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2853
				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...
2854
			}
2855
		}
2856
2857
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2858
		Jetpack::state( 'module', $module );
2859
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2860
2861
		Jetpack::catch_errors( true );
2862
		ob_start();
2863
		require Jetpack::get_module_path( $module );
2864
		/** This action is documented in class.jetpack.php */
2865
		do_action( 'jetpack_activate_module', $module );
2866
		$active[] = $module;
2867
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2868
		Jetpack::state( 'error', false ); // the override
2869
		Jetpack::state( 'message', 'module_activated' );
2870
		Jetpack::state( 'module', $module );
2871
		ob_end_clean();
2872
		Jetpack::catch_errors( false );
2873
2874
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2875 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2876
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2877
2878
			//Jump start is being dismissed send data to MC Stats
2879
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2880
2881
			$jetpack->do_stats( 'server_side' );
2882
		}
2883
2884
		if ( $redirect ) {
2885
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2886
		}
2887
		if ( $exit ) {
2888
			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...
2889
		}
2890
		return true;
2891
	}
2892
2893
	function activate_module_actions( $module ) {
2894
		/**
2895
		 * Fires when a module is activated.
2896
		 * The dynamic part of the filter, $module, is the module slug.
2897
		 *
2898
		 * @since 1.9.0
2899
		 *
2900
		 * @param string $module Module slug.
2901
		 */
2902
		do_action( "jetpack_activate_module_$module", $module );
2903
2904
		$this->sync->sync_all_module_options( $module );
2905
	}
2906
2907
	public static function deactivate_module( $module ) {
2908
		/**
2909
		 * Fires when a module is deactivated.
2910
		 *
2911
		 * @since 1.9.0
2912
		 *
2913
		 * @param string $module Module slug.
2914
		 */
2915
		do_action( 'jetpack_pre_deactivate_module', $module );
2916
2917
		$jetpack = Jetpack::init();
2918
2919
		$active = Jetpack::get_active_modules();
2920
		$new    = array_filter( array_diff( $active, (array) $module ) );
2921
2922
		/**
2923
		 * Fires when a module is deactivated.
2924
		 * The dynamic part of the filter, $module, is the module slug.
2925
		 *
2926
		 * @since 1.9.0
2927
		 *
2928
		 * @param string $module Module slug.
2929
		 */
2930
		do_action( "jetpack_deactivate_module_$module", $module );
2931
2932
		// A flag for Jump Start so it's not shown again.
2933 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2934
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2935
2936
			//Jump start is being dismissed send data to MC Stats
2937
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2938
2939
			$jetpack->do_stats( 'server_side' );
2940
		}
2941
2942
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2943
	}
2944
2945
	public static function enable_module_configurable( $module ) {
2946
		$module = Jetpack::get_module_slug( $module );
2947
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2948
	}
2949
2950
	public static function module_configuration_url( $module ) {
2951
		$module = Jetpack::get_module_slug( $module );
2952
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2953
	}
2954
2955
	public static function module_configuration_load( $module, $method ) {
2956
		$module = Jetpack::get_module_slug( $module );
2957
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2958
	}
2959
2960
	public static function module_configuration_head( $module, $method ) {
2961
		$module = Jetpack::get_module_slug( $module );
2962
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2963
	}
2964
2965
	public static function module_configuration_screen( $module, $method ) {
2966
		$module = Jetpack::get_module_slug( $module );
2967
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2968
	}
2969
2970
	public static function module_configuration_activation_screen( $module, $method ) {
2971
		$module = Jetpack::get_module_slug( $module );
2972
		add_action( 'display_activate_module_setting_' . $module, $method );
2973
	}
2974
2975
/* Installation */
2976
2977
	public static function bail_on_activation( $message, $deactivate = true ) {
2978
?>
2979
<!doctype html>
2980
<html>
2981
<head>
2982
<meta charset="<?php bloginfo( 'charset' ); ?>">
2983
<style>
2984
* {
2985
	text-align: center;
2986
	margin: 0;
2987
	padding: 0;
2988
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2989
}
2990
p {
2991
	margin-top: 1em;
2992
	font-size: 18px;
2993
}
2994
</style>
2995
<body>
2996
<p><?php echo esc_html( $message ); ?></p>
2997
</body>
2998
</html>
2999
<?php
3000
		if ( $deactivate ) {
3001
			$plugins = get_option( 'active_plugins' );
3002
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3003
			$update  = false;
3004
			foreach ( $plugins as $i => $plugin ) {
3005
				if ( $plugin === $jetpack ) {
3006
					$plugins[$i] = false;
3007
					$update = true;
3008
				}
3009
			}
3010
3011
			if ( $update ) {
3012
				update_option( 'active_plugins', array_filter( $plugins ) );
3013
			}
3014
		}
3015
		exit;
3016
	}
3017
3018
	/**
3019
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3020
	 * @static
3021
	 */
3022
	public static function plugin_activation( $network_wide ) {
3023
		Jetpack_Options::update_option( 'activated', 1 );
3024
3025
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3026
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3027
		}
3028
3029
		if ( $network_wide )
3030
			Jetpack::state( 'network_nag', true );
3031
3032
		Jetpack::plugin_initialize();
3033
	}
3034
	/**
3035
	 * Runs before bumping version numbers up to a new version
3036
	 * @param  (string) $version    Version:timestamp
3037
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
3038
	 * @return null              [description]
3039
	 */
3040
	public static function do_version_bump( $version, $old_version ) {
3041
3042
		if ( ! $old_version ) { // For new sites
3043
			// Setting up jetpack manage
3044
			Jetpack::activate_manage();
3045
		}
3046
	}
3047
3048
	/**
3049
	 * Sets the internal version number and activation state.
3050
	 * @static
3051
	 */
3052
	public static function plugin_initialize() {
3053
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3054
			Jetpack_Options::update_option( 'activated', 2 );
3055
		}
3056
3057 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3058
			$version = $old_version = JETPACK__VERSION . ':' . time();
3059
			/** This action is documented in class.jetpack.php */
3060
			do_action( 'updating_jetpack_version', $version, false );
3061
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3062
		}
3063
3064
		Jetpack::load_modules();
3065
3066
		Jetpack_Options::delete_option( 'do_activate' );
3067
	}
3068
3069
	/**
3070
	 * Removes all connection options
3071
	 * @static
3072
	 */
3073
	public static function plugin_deactivation( ) {
3074
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3075
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3076
			Jetpack_Network::init()->deactivate();
3077
		} else {
3078
			Jetpack::disconnect( false );
3079
			//Jetpack_Heartbeat::init()->deactivate();
3080
		}
3081
	}
3082
3083
	/**
3084
	 * Disconnects from the Jetpack servers.
3085
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3086
	 * @static
3087
	 */
3088
	public static function disconnect( $update_activated_state = true ) {
3089
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3090
		Jetpack::clean_nonces( true );
3091
3092
		Jetpack::load_xml_rpc_client();
3093
		$xml = new Jetpack_IXR_Client();
3094
		$xml->query( 'jetpack.deregister' );
3095
3096
		Jetpack_Options::delete_option(
3097
			array(
3098
				'register',
3099
				'blog_token',
3100
				'user_token',
3101
				'user_tokens',
3102
				'master_user',
3103
				'time_diff',
3104
				'fallback_no_verify_ssl_certs',
3105
			)
3106
		);
3107
3108
		if ( $update_activated_state ) {
3109
			Jetpack_Options::update_option( 'activated', 4 );
3110
		}
3111
3112
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
3113
		// Check then record unique disconnection if site has never been disconnected previously
3114
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
3115
			$jetpack_unique_connection['disconnected'] = 1;
3116
		}
3117
		else {
3118
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3119
				//track unique disconnect
3120
				$jetpack = Jetpack::init();
3121
3122
				$jetpack->stat( 'connections', 'unique-disconnect' );
3123
				$jetpack->do_stats( 'server_side' );
3124
			}
3125
			// increment number of times disconnected
3126
			$jetpack_unique_connection['disconnected'] += 1;
3127
		}
3128
3129
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3130
3131
		// Disable the Heartbeat cron
3132
		Jetpack_Heartbeat::init()->deactivate();
3133
	}
3134
3135
	/**
3136
	 * Unlinks the current user from the linked WordPress.com user
3137
	 */
3138
	public static function unlink_user( $user_id = null ) {
3139
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3140
			return false;
3141
3142
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3143
3144
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3145
			return false;
3146
3147
		if ( ! isset( $tokens[ $user_id ] ) )
3148
			return false;
3149
3150
		Jetpack::load_xml_rpc_client();
3151
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3152
		$xml->query( 'jetpack.unlink_user', $user_id );
3153
3154
		unset( $tokens[ $user_id ] );
3155
3156
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3157
3158
		return true;
3159
	}
3160
3161
	/**
3162
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3163
	 */
3164
	public static function try_registration() {
3165
		// Let's get some testing in beta versions and such.
3166
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3167
			// Before attempting to connect, let's make sure that the domains are viable.
3168
			$domains_to_check = array_unique( array(
3169
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3170
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3171
			) );
3172
			foreach ( $domains_to_check as $domain ) {
3173
				$result = Jetpack_Data::is_usable_domain( $domain );
3174
				if ( is_wp_error( $result ) ) {
3175
					return $result;
3176
				}
3177
			}
3178
		}
3179
3180
		$result = Jetpack::register();
3181
3182
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3183
		if ( ! $result || is_wp_error( $result ) ) {
3184
			return $result;
3185
		} else {
3186
			return true;
3187
		}
3188
	}
3189
3190
	/**
3191
	 * Tracking an internal event log. Try not to put too much chaff in here.
3192
	 *
3193
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3194
	 */
3195
	public static function log( $code, $data = null ) {
3196
		// only grab the latest 200 entries
3197
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3198
3199
		// Append our event to the log
3200
		$log_entry = array(
3201
			'time'    => time(),
3202
			'user_id' => get_current_user_id(),
3203
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3204
			'code'    => $code,
3205
		);
3206
		// Don't bother storing it unless we've got some.
3207
		if ( ! is_null( $data ) ) {
3208
			$log_entry['data'] = $data;
3209
		}
3210
		$log[] = $log_entry;
3211
3212
		// Try add_option first, to make sure it's not autoloaded.
3213
		// @todo: Add an add_option method to Jetpack_Options
3214
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3215
			Jetpack_Options::update_option( 'log', $log );
3216
		}
3217
3218
		/**
3219
		 * Fires when Jetpack logs an internal event.
3220
		 *
3221
		 * @since 3.0.0
3222
		 *
3223
		 * @param array $log_entry {
3224
		 *	Array of details about the log entry.
3225
		 *
3226
		 *	@param string time Time of the event.
3227
		 *	@param int user_id ID of the user who trigerred the event.
3228
		 *	@param int blog_id Jetpack Blog ID.
3229
		 *	@param string code Unique name for the event.
3230
		 *	@param string data Data about the event.
3231
		 * }
3232
		 */
3233
		do_action( 'jetpack_log_entry', $log_entry );
3234
	}
3235
3236
	/**
3237
	 * Get the internal event log.
3238
	 *
3239
	 * @param $event (string) - only return the specific log events
3240
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3241
	 *
3242
	 * @return array of log events || WP_Error for invalid params
3243
	 */
3244
	public static function get_log( $event = false, $num = false ) {
3245
		if ( $event && ! is_string( $event ) ) {
3246
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3247
		}
3248
3249
		if ( $num && ! is_numeric( $num ) ) {
3250
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3251
		}
3252
3253
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3254
3255
		// If nothing set - act as it did before, otherwise let's start customizing the output
3256
		if ( ! $num && ! $event ) {
3257
			return $entire_log;
3258
		} else {
3259
			$entire_log = array_reverse( $entire_log );
3260
		}
3261
3262
		$custom_log_output = array();
3263
3264
		if ( $event ) {
3265
			foreach ( $entire_log as $log_event ) {
3266
				if ( $event == $log_event[ 'code' ] ) {
3267
					$custom_log_output[] = $log_event;
3268
				}
3269
			}
3270
		} else {
3271
			$custom_log_output = $entire_log;
3272
		}
3273
3274
		if ( $num ) {
3275
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3276
		}
3277
3278
		return $custom_log_output;
3279
	}
3280
3281
	/**
3282
	 * Log modification of important settings.
3283
	 */
3284
	public static function log_settings_change( $option, $old_value, $value ) {
3285
		switch( $option ) {
3286
			case 'jetpack_sync_non_public_post_stati':
3287
				self::log( $option, $value );
3288
				break;
3289
		}
3290
	}
3291
3292
	/**
3293
	 * Return stat data for WPCOM sync
3294
	 */
3295
	function get_stat_data() {
3296
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3297
		$additional_data = $this->get_additional_stat_data();
3298
3299
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3300
	}
3301
3302
	/**
3303
	 * Get additional stat data to sync to WPCOM
3304
	 */
3305
	function get_additional_stat_data( $prefix = '' ) {
3306
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3307
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3308
		$return["{$prefix}users"]          = count_users();
3309
		$return["{$prefix}site-count"]     = 0;
3310
		if ( function_exists( 'get_blog_count' ) ) {
3311
			$return["{$prefix}site-count"] = get_blog_count();
3312
		}
3313
		return $return;
3314
	}
3315
3316
	/* Admin Pages */
3317
3318
	function admin_init() {
3319
		// If the plugin is not connected, display a connect message.
3320
		if (
3321
			// the plugin was auto-activated and needs its candy
3322
			Jetpack_Options::get_option( 'do_activate' )
3323
		||
3324
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3325
			! Jetpack_Options::get_option( 'activated' )
3326
		) {
3327
			Jetpack::plugin_initialize();
3328
		}
3329
3330
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3331
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3332
				// Show connect notice on dashboard and plugins pages
3333
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3334
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3335
			}
3336
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3337
			// Upgrade: 1.1 -> 1.1.1
3338
			// Check and see if host can verify the Jetpack servers' SSL certificate
3339
			$args = array();
3340
			Jetpack_Client::_wp_remote_request(
3341
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3342
				$args,
3343
				true
3344
			);
3345
		} else {
3346
			// Show the notice on the Dashboard only for now
3347
3348
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3349
3350
			// Identity crisis notices
3351
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3352
		}
3353
3354
		// If the plugin has just been disconnected from WP.com, show the survey notice
3355
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3356
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3357
		}
3358
3359
		if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3360
			add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
3361
		}
3362
3363
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3364
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3365
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3366
3367
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3368
			// Artificially throw errors in certain whitelisted cases during plugin activation
3369
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3370
3371
			// Kick off synchronization of user role when it changes
3372
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3373
		}
3374
3375
		// Jetpack Manage Activation Screen from .com
3376
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3377
	}
3378
3379
	function admin_body_class( $admin_body_class = '' ) {
3380
		$classes = explode( ' ', trim( $admin_body_class ) );
3381
3382
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3383
3384
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3385
		return " $admin_body_class ";
3386
	}
3387
3388
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3389
		return $admin_body_class . ' jetpack-pagestyles ';
3390
	}
3391
3392
	function prepare_connect_notice() {
3393
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3394
3395
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3396
3397
		if ( Jetpack::state( 'network_nag' ) )
3398
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3399
	}
3400
	/**
3401
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3402
	 *
3403
	 * @return null
3404
	 */
3405
	function prepare_manage_jetpack_notice() {
3406
3407
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3408
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3409
	}
3410
3411
	function manage_activate_screen() {
3412
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3413
	}
3414
	/**
3415
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3416
	 * This function artificially throws errors for such cases (whitelisted).
3417
	 *
3418
	 * @param string $plugin The activated plugin.
3419
	 */
3420
	function throw_error_on_activate_plugin( $plugin ) {
3421
		$active_modules = Jetpack::get_active_modules();
3422
3423
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3424
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3425
			$throw = false;
3426
3427
			// Try and make sure it really was the stats plugin
3428
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3429
				if ( 'stats.php' == basename( $plugin ) ) {
3430
					$throw = true;
3431
				}
3432
			} else {
3433
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3434
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3435
					$throw = true;
3436
				}
3437
			}
3438
3439
			if ( $throw ) {
3440
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3441
			}
3442
		}
3443
	}
3444
3445
	function intercept_plugin_error_scrape_init() {
3446
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3447
	}
3448
3449
	function intercept_plugin_error_scrape( $action, $result ) {
3450
		if ( ! $result ) {
3451
			return;
3452
		}
3453
3454
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3455
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3456
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3457
			}
3458
		}
3459
	}
3460
3461
	function add_remote_request_handlers() {
3462
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3463
	}
3464
3465
	function remote_request_handlers() {
3466
		switch ( current_filter() ) {
3467
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3468
			$response = $this->upload_handler();
3469
			break;
3470
		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...
3471
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3472
			break;
3473
		}
3474
3475
		if ( ! $response ) {
3476
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3477
		}
3478
3479
		if ( is_wp_error( $response ) ) {
3480
			$status_code       = $response->get_error_data();
3481
			$error             = $response->get_error_code();
3482
			$error_description = $response->get_error_message();
3483
3484
			if ( ! is_int( $status_code ) ) {
3485
				$status_code = 400;
3486
			}
3487
3488
			status_header( $status_code );
3489
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3490
		}
3491
3492
		status_header( 200 );
3493
		if ( true === $response ) {
3494
			exit;
3495
		}
3496
3497
		die( json_encode( (object) $response ) );
3498
	}
3499
3500
	function upload_handler() {
3501
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3502
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3503
		}
3504
3505
		$user = wp_authenticate( '', '' );
3506
		if ( ! $user || is_wp_error( $user ) ) {
3507
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3508
		}
3509
3510
		wp_set_current_user( $user->ID );
3511
3512
		if ( ! current_user_can( 'upload_files' ) ) {
3513
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3514
		}
3515
3516
		if ( empty( $_FILES ) ) {
3517
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3518
		}
3519
3520
		foreach ( array_keys( $_FILES ) as $files_key ) {
3521
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3522
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3523
			}
3524
		}
3525
3526
		$media_keys = array_keys( $_FILES['media'] );
3527
3528
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3529
		if ( ! $token || is_wp_error( $token ) ) {
3530
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3531
		}
3532
3533
		$uploaded_files = array();
3534
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3535
		unset( $GLOBALS['post'] );
3536
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3537
			$file = array();
3538
			foreach ( $media_keys as $media_key ) {
3539
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3540
			}
3541
3542
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3543
3544
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3545
			if ( $hmac_provided !== $hmac_file ) {
3546
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3547
				continue;
3548
			}
3549
3550
			$_FILES['.jetpack.upload.'] = $file;
3551
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3552
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3553
				$post_id = 0;
3554
			}
3555
			$attachment_id = media_handle_upload(
3556
				'.jetpack.upload.',
3557
				$post_id,
3558
				array(),
3559
				array(
3560
					'action' => 'jetpack_upload_file',
3561
				)
3562
			);
3563
3564
			if ( ! $attachment_id ) {
3565
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3566
			} elseif ( is_wp_error( $attachment_id ) ) {
3567
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3568
			} else {
3569
				$attachment = get_post( $attachment_id );
3570
				$uploaded_files[$index] = (object) array(
3571
					'id'   => (string) $attachment_id,
3572
					'file' => $attachment->post_title,
3573
					'url'  => wp_get_attachment_url( $attachment_id ),
3574
					'type' => $attachment->post_mime_type,
3575
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3576
				);
3577
			}
3578
		}
3579
		if ( ! is_null( $global_post ) ) {
3580
			$GLOBALS['post'] = $global_post;
3581
		}
3582
3583
		return $uploaded_files;
3584
	}
3585
3586
	/**
3587
	 * Add help to the Jetpack page
3588
	 *
3589
	 * @since Jetpack (1.2.3)
3590
	 * @return false if not the Jetpack page
3591
	 */
3592
	function admin_help() {
3593
		$current_screen = get_current_screen();
3594
3595
		// Overview
3596
		$current_screen->add_help_tab(
3597
			array(
3598
				'id'		=> 'home',
3599
				'title'		=> __( 'Home', 'jetpack' ),
3600
				'content'	=>
3601
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3602
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3603
					'<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>',
3604
			)
3605
		);
3606
3607
		// Screen Content
3608
		if ( current_user_can( 'manage_options' ) ) {
3609
			$current_screen->add_help_tab(
3610
				array(
3611
					'id'		=> 'settings',
3612
					'title'		=> __( 'Settings', 'jetpack' ),
3613
					'content'	=>
3614
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3615
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3616
						'<ol>' .
3617
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3618
							'<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>' .
3619
						'</ol>' .
3620
						'<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>'
3621
				)
3622
			);
3623
		}
3624
3625
		// Help Sidebar
3626
		$current_screen->set_help_sidebar(
3627
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3628
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3629
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3630
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3631
		);
3632
	}
3633
3634
	function admin_menu_css() {
3635
		wp_enqueue_style( 'jetpack-icons' );
3636
	}
3637
3638
	function admin_menu_order() {
3639
		return true;
3640
	}
3641
3642 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3643
		$jp_menu_order = array();
3644
3645
		foreach ( $menu_order as $index => $item ) {
3646
			if ( $item != 'jetpack' ) {
3647
				$jp_menu_order[] = $item;
3648
			}
3649
3650
			if ( $index == 0 ) {
3651
				$jp_menu_order[] = 'jetpack';
3652
			}
3653
		}
3654
3655
		return $jp_menu_order;
3656
	}
3657
3658
	function admin_head() {
3659 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3660
			/** This action is documented in class.jetpack-admin-page.php */
3661
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3662
	}
3663
3664
	function admin_banner_styles() {
3665
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3666
3667
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3668
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3669
		wp_style_add_data( 'jetpack', 'suffix', $min );
3670
	}
3671
3672
	function admin_scripts() {
3673
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3674
		wp_localize_script(
3675
			'jetpack-js',
3676
			'jetpackL10n',
3677
			array(
3678
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3679
				'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?",
3680
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3681
			)
3682
		);
3683
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3684
	}
3685
3686
	function plugin_action_links( $actions ) {
3687
3688
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3689
3690
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3691
			return array_merge(
3692
				$jetpack_home,
3693
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3694
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3695
				$actions
3696
				);
3697
			}
3698
3699
		return array_merge( $jetpack_home, $actions );
3700
	}
3701
3702
	function admin_connect_notice() {
3703
		// Don't show the connect notice anywhere but the plugins.php after activating
3704
		$current = get_current_screen();
3705
		if ( 'plugins' !== $current->parent_base )
3706
			return;
3707
3708
		if ( ! current_user_can( 'jetpack_connect' ) )
3709
			return;
3710
3711
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3712
		?>
3713
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3714
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"></a>
3715
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3716
				<div class="jp-banner__content is-connection">
3717
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3718
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3719
				</div>
3720
				<div class="jp-banner__action-container is-connection">
3721
						<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3722
				</div>
3723 View Code Duplication
			<?php else : ?>
3724
				<div class="jp-banner__content">
3725
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3726
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3727
				</div>
3728
				<div class="jp-banner__action-container">
3729
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3730
				</div>
3731
			<?php endif; ?>
3732
		</div>
3733
3734
		<?php
3735
	}
3736
3737
	/**
3738
	 * This is the first banner
3739
	 * It should be visible only to user that can update the option
3740
	 * Are not connected
3741
	 *
3742
	 * @return null
3743
	 */
3744
	function admin_jetpack_manage_notice() {
3745
		$screen = get_current_screen();
3746
3747
		// Don't show the connect notice on the jetpack settings page.
3748
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3749
			return;
3750
3751
		// Only show it if don't have the managment option set.
3752
		// And not dismissed it already.
3753
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3754
			return;
3755
		}
3756
3757
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3758
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3759
		/**
3760
		 * I think it would be great to have different wordsing depending on where you are
3761
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3762
		 * etc..
3763
		 */
3764
3765
		?>
3766
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3767
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $opt_out_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice for now.', 'jetpack' ); ?>"></a>
3768
			<div class="jp-banner__content">
3769
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3770
				<p><?php printf( __( 'Manage multiple sites from one dashboard at wordpress.com/sites. Enabling allows all existing, connected Administrators to modify your site from WordPress.com. <a href="%s" target="_blank">Learn More</a>.', 'jetpack' ), 'http://jetpack.com/support/site-management' ); ?></p>
3771
			</div>
3772
			<div class="jp-banner__action-container is-opt-in">
3773
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3774
			</div>
3775
		</div>
3776
		<?php
3777
	}
3778
3779
	/**
3780
	 * Returns the url that the user clicks to remove the notice for the big banner
3781
	 * @return (string)
3782
	 */
3783
	function opt_out_jetpack_manage_url() {
3784
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3785
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3786
	}
3787
	/**
3788
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3789
	 * @return (string)
3790
	 */
3791
	function opt_in_jetpack_manage_url() {
3792
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3793
	}
3794
3795
	function opt_in_jetpack_manage_notice() {
3796
		?>
3797
		<div class="wrap">
3798
			<div id="message" class="jetpack-message is-opt-in">
3799
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'http://jetpack.com/support/site-management' ); ?>
3800
			</div>
3801
		</div>
3802
		<?php
3803
3804
	}
3805
	/**
3806
	 * Determines whether to show the notice of not true = display notice
3807
	 * @return (bool)
3808
	 */
3809
	function can_display_jetpack_manage_notice() {
3810
		// never display the notice to users that can't do anything about it anyways
3811
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3812
			return false;
3813
3814
		// don't display if we are in development more
3815
		if( Jetpack::is_development_mode() ) {
3816
			return false;
3817
		}
3818
		// don't display if the site is private
3819
		if(  ! Jetpack_Options::get_option( 'public' ) )
3820
			return false;
3821
3822
		/**
3823
		 * Should the Jetpack Remote Site Management notice be displayed.
3824
		 *
3825
		 * @since 3.3.0
3826
		 *
3827
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3828
		 */
3829
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3830
	}
3831
3832
	function network_connect_notice() {
3833
		?>
3834
		<div id="message" class="updated jetpack-message">
3835
			<div class="squeezer">
3836
				<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>
3837
			</div>
3838
		</div>
3839
		<?php
3840
	}
3841
3842
	public static function jetpack_comment_notice() {
3843
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3844
			return '';
3845
		}
3846
3847
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3848
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3849
3850
		if ( $jetpack_old_version ) {
3851
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3852
				return '';
3853
			}
3854
		}
3855
3856
		if ( $jetpack_new_version ) {
3857
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3858
				return '';
3859
			}
3860
		}
3861
3862
		return '<br /><br />' . sprintf(
3863
			__( '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' ),
3864
			wp_nonce_url(
3865
				Jetpack::admin_url(
3866
					array(
3867
						'page'   => 'jetpack',
3868
						'action' => 'activate',
3869
						'module' => 'comments',
3870
					)
3871
				),
3872
				'jetpack_activate-comments'
3873
			),
3874
			__( 'click here', 'jetpack' )
3875
		);
3876
	}
3877
3878
	/**
3879
	 * Show the survey link when the user has just disconnected Jetpack.
3880
	 */
3881
	function disconnect_survey_notice() {
3882
		?>
3883
		<div class="wrap">
3884
			<div id="message" class="jetpack-message stay-visible">
3885
				<div class="squeezer">
3886
					<h2>
3887
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3888
						<br />
3889
						<?php echo sprintf(
3890
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3891
							'https://jetpack.com/survey-disconnected/',
3892
							'_blank'
3893
						); ?>
3894
					</h2>
3895
				</div>
3896
			</div>
3897
		</div>
3898
		<?php
3899
	}
3900
3901
	/*
3902
	 * Registration flow:
3903
	 * 1 - ::admin_page_load() action=register
3904
	 * 2 - ::try_registration()
3905
	 * 3 - ::register()
3906
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3907
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3908
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3909
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3910
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3911
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3912
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3913
	 *       jetpack_id, jetpack_secret, jetpack_public
3914
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3915
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3916
	 * 5 - user logs in with WP.com account
3917
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3918
	 *		- Jetpack_Client_Server::authorize()
3919
	 *		- Jetpack_Client_Server::get_token()
3920
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3921
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3922
	 *			- which responds with access_token, token_type, scope
3923
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3924
	 *		- Jetpack::activate_default_modules()
3925
	 *     		- Deactivates deprecated plugins
3926
	 *     		- Activates all default modules
3927
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3928
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3929
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3930
	 *     Done!
3931
	 */
3932
3933
	/**
3934
	 * Handles the page load events for the Jetpack admin page
3935
	 */
3936
	function admin_page_load() {
3937
		$error = false;
3938
3939
		// Make sure we have the right body class to hook stylings for subpages off of.
3940
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3941
3942
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3943
			// Should only be used in intermediate redirects to preserve state across redirects
3944
			Jetpack::restate();
3945
		}
3946
3947
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3948
			// User clicked in the iframe to link their accounts
3949
			if ( ! Jetpack::is_user_connected() ) {
3950
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3951
				if ( isset( $_GET['notes_iframe'] ) )
3952
					$connect_url .= '&notes_iframe';
3953
				wp_redirect( $connect_url );
3954
				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...
3955
			} else {
3956
				Jetpack::state( 'message', 'already_authorized' );
3957
				wp_safe_redirect( Jetpack::admin_url() );
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
			}
3960
		}
3961
3962
3963
		if ( isset( $_GET['action'] ) ) {
3964
			switch ( $_GET['action'] ) {
3965
			case 'authorize':
3966
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3967
					Jetpack::state( 'message', 'already_authorized' );
3968
					wp_safe_redirect( Jetpack::admin_url() );
3969
					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...
3970
				}
3971
				Jetpack::log( 'authorize' );
3972
				$client_server = new Jetpack_Client_Server;
3973
				$client_server->client_authorize();
3974
				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...
3975
			case 'register' :
3976
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3977
					$error = 'cheatin';
3978
					break;
3979
				}
3980
				check_admin_referer( 'jetpack-register' );
3981
				Jetpack::log( 'register' );
3982
				Jetpack::maybe_set_version_option();
3983
				$registered = Jetpack::try_registration();
3984
				if ( is_wp_error( $registered ) ) {
3985
					$error = $registered->get_error_code();
3986
					Jetpack::state( 'error_description', $registered->get_error_message() );
3987
					break;
3988
				}
3989
				
3990
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3991
3992
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3993
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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