Completed
Push — fix/early-require-error ( 10ec1f )
by
unknown
11:18
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
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
198
		'facebook/facebook.php',                                 // Facebook (official plugin)
199
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
200
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
201
		                                                         // Facebook Featured Image & OG Meta Tags
202
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
203
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
204
		                                                         // Facebook Open Graph Meta Tags for WordPress
205
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
206
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
207
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
208
		                                                         // Fedmich's Facebook Open Graph Meta
209
		'header-footer/plugin.php',                              // Header and Footer
210
		'network-publisher/networkpub.php',                      // Network Publisher
211
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
212
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
213
		                                                         // NextScripts SNAP
214
		'opengraph/opengraph.php',                               // Open Graph
215
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
216
		                                                         // Open Graph Protocol Framework
217
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
218
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
219
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
220
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
221
		'sharepress/sharepress.php',                             // SharePress
222
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
223
		'social-discussions/social-discussions.php',             // Social Discussions
224
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
225
		'socialize/socialize.php',                               // Socialize
226
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
227
		                                                         // Tweet, Like, Google +1 and Share
228
		'wordbooker/wordbooker.php',                             // Wordbooker
229
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
230
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
231
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
232
		                                                         // WP Facebook Like Send & Open Graph Meta
233
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
234
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
235
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
236
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
237
	);
238
239
	/**
240
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
241
	 */
242
	private $twitter_cards_conflicting_plugins = array(
243
	//	'twitter/twitter.php',                       // The official one handles this on its own.
244
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
245
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
246
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
247
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
248
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
249
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
250
		'twitter-cards/twitter-cards.php',           // Twitter Cards
251
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
252
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
253
	);
254
255
	/**
256
	 * Message to display in admin_notice
257
	 * @var string
258
	 */
259
	public $message = '';
260
261
	/**
262
	 * Error to display in admin_notice
263
	 * @var string
264
	 */
265
	public $error = '';
266
267
	/**
268
	 * Modules that need more privacy description.
269
	 * @var string
270
	 */
271
	public $privacy_checks = '';
272
273
	/**
274
	 * Stats to record once the page loads
275
	 *
276
	 * @var array
277
	 */
278
	public $stats = array();
279
280
	/**
281
	 * Allows us to build a temporary security report
282
	 *
283
	 * @var array
284
	 */
285
	static $security_report = array();
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	static $instance = false;
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			if ( did_action( 'plugins_loaded' ) )
311
				self::plugin_textdomain();
312
			else
313
				add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
314
315
			self::$instance = new Jetpack;
316
317
			self::$instance->plugin_upgrade();
318
319
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
320
321
		}
322
323
		return self::$instance;
324
	}
325
326
	/**
327
	 * Must never be called statically
328
	 */
329
	function plugin_upgrade() {
330
		if ( Jetpack::is_active() ) {
331
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
332
			if ( JETPACK__VERSION != $version ) {
333
334
				// Check which active modules actually exist and remove others from active_modules list
335
				$unfiltered_modules = Jetpack::get_active_modules();
336
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
337
				if ( array_diff( $unfiltered_modules, $modules ) ) {
338
					Jetpack_Options::update_option( 'active_modules', $modules );
339
				}
340
341
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
342
				/**
343
				 * Fires when synchronizing all registered options and constants.
344
				 *
345
				 * @since 3.3.0
346
				 */
347
				do_action( 'jetpack_sync_all_registered_options' );
348
			}
349
		}
350
	}
351
352
	static function activate_manage( ) {
353
354
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
355
			self::activate_module( 'manage', false, false );
356
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
357
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
358
		}
359
360
	}
361
362
	/**
363
	 * Constructor.  Initializes WordPress hooks
364
	 */
365
	private function __construct() {
366
		/*
367
		 * Check for and alert any deprecated hooks
368
		 */
369
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
370
371
		/*
372
		 * Do things that should run even in the network admin
373
		 * here, before we potentially fail out.
374
		 */
375
		add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
376
377
		/**
378
		 * We need sync object even in Multisite mode
379
		 */
380
		$this->sync = new Jetpack_Sync;
381
382
		/**
383
		 * Trigger a wp_version sync when updating WP versions
384
		 **/
385
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
386
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
387
388
		add_action( 'init', array( $this, 'sync_update_data') );
389
		add_action( 'init', array( $this, 'sync_theme_data' ) );
390
391
		/*
392
		 * Load things that should only be in Network Admin.
393
		 *
394
		 * For now blow away everything else until a more full
395
		 * understanding of what is needed at the network level is
396
		 * available
397
		 */
398
		if( is_multisite() ) {
399
			Jetpack_Network::init();
400
401
			// Only sync this info if we are on a multi site
402
			// @since  3.7
403
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
404
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
405
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
406
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
407
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
408
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
409
410
			if( is_network_admin() ) {
411
				// Sync network site data if it is updated or not.
412
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
413
				return; // End here to prevent single site actions from firing
414
			}
415
		}
416
417
418
		$theme_slug = get_option( 'stylesheet' );
419
420
421
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
422
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
423
		$this->sync->options(
424
			JETPACK__PLUGIN_DIR . 'jetpack.php',
425
			'home',
426
			'siteurl',
427
			'blogname',
428
			'gmt_offset',
429
			'timezone_string',
430
			'security_report',
431
			'stylesheet',
432
			"theme_mods_{$theme_slug}",
433
			'jetpack_sync_non_public_post_stati',
434
			'jetpack_options',
435
			'site_icon', // (int) - ID of core's Site Icon attachment ID
436
			'default_post_format',
437
			'default_category',
438
			'large_size_w',
439
			'large_size_h',
440
			'thumbnail_size_w',
441
			'thumbnail_size_h',
442
			'medium_size_w',
443
			'medium_size_h',
444
			'thumbnail_crop',
445
			'image_default_link_type'
446
		);
447
448
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
449
			$this->sync->options( __FILE__, 'jetpack_' . $option );
450
		}
451
452
		/**
453
		 * Sometimes you want to sync data to .com without adding options to .org sites.
454
		 * The mock option allows you to do just that.
455
		 */
456
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
457
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
458
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
459
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
460
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
461
462
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
463
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
464
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
465
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
466
467
		/**
468
		 * Trigger an update to the main_network_site when we update the blogname of a site.
469
		 *
470
		 */
471
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
472
473
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
474
475
		// Update the settings everytime the we register a new user to the site or we delete a user.
476
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
477
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
478
479
		// Unlink user before deleting the user from .com
480
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
481
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
482
483
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
484
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
485
486
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
487
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
488
489
			$this->require_jetpack_authentication();
490
491
			if ( Jetpack::is_active() ) {
492
				// Hack to preserve $HTTP_RAW_POST_DATA
493
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
494
495
				$signed = $this->verify_xml_rpc_signature();
496
				if ( $signed && ! is_wp_error( $signed ) ) {
497
					// The actual API methods.
498
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
499
				} else {
500
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
501
					// active Jetpack connection, so that additional users can link their account.
502
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
503
				}
504
			} else {
505
				// The bootstrap API methods.
506
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
507
			}
508
509
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
510
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
511
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
512
			$this->require_jetpack_authentication();
513
			$this->add_remote_request_handlers();
514
		} else {
515
			if ( Jetpack::is_active() ) {
516
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
517
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
518
			}
519
		}
520
521
		if ( Jetpack::is_active() ) {
522
			Jetpack_Heartbeat::init();
523
		}
524
525
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
526
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
527
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
528
		}
529
530
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
531
532
		add_action( 'admin_init', array( $this, 'admin_init' ) );
533
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
534
535
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
536
537
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
538
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
539
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
540
541
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
542
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
543
544
		// Jump Start AJAX callback function
545
		add_action( 'wp_ajax_jetpack_jumpstart_ajax',  array( $this, 'jetpack_jumpstart_ajax_callback' ) );
546
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
547
548
		// Identity Crisis AJAX callback function
549
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
550
551
		// JITM AJAX callback function
552
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
553
554
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
555
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
556
557
		// Universal ajax callback for all tracking events triggered via js
558
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
559
560
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
561
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
562
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
563
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
564
565
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
566
567
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
568
569
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
570
571
		/**
572
		 * These actions run checks to load additional files.
573
		 * They check for external files or plugins, so they need to run as late as possible.
574
		 */
575
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
576
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
577
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
578
579
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
580
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
581
582
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
583
584
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
585
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
586
587
		// A filter to control all just in time messages
588
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
589
590
		/**
591
		 * This is the hack to concatinate all css files into one.
592
		 * For description and reasoning see the implode_frontend_css method
593
		 *
594
		 * Super late priority so we catch all the registered styles
595
		 */
596
		if( !is_admin() ) {
597
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
598
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
599
		}
600
601
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
602
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
603
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
604
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
605
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
606
607
	}
608
609
	/*
610
	 * Make sure any site icon added to core can get
611
	 * synced back to dotcom, so we can display it there.
612
	 */
613
	function jetpack_sync_core_icon() {
614
		if ( function_exists( 'get_site_icon_url' ) ) {
615
			$url = get_site_icon_url();
616
		} else {
617
			return;
618
		}
619
620
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
621
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
622
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
623
			// This is the option that is synced with dotcom
624
			Jetpack_Options::update_option( 'site_icon_url', $url );
625
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
626
			Jetpack_Options::delete_option( 'site_icon_url' );
627
		}
628
	}
629
630
	function jetpack_admin_ajax_tracks_callback() {
631
		// Check for nonce
632
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
633
			wp_die( 'Permissions check failed.' );
634
		}
635
636
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
637
			wp_die( 'No valid event name or type.' );
638
		}
639
640
		$tracks_data = array();
641
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
642
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
643
		}
644
645
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
646
		wp_send_json_success();
647
		wp_die();
648
	}
649
650
	function jetpack_admin_ajax_callback() {
651
		// Check for nonce
652 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
653
			wp_die( 'permissions check failed' );
654
		}
655
656
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
657
			$slug = $_REQUEST['thisModuleSlug'];
658
659
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
660
				wp_die( 'That is not a Jetpack module slug' );
661
			}
662
663
			if ( Jetpack::is_module_active( $slug ) ) {
664
				Jetpack::deactivate_module( $slug );
665
			} else {
666
				Jetpack::activate_module( $slug, false, false );
667
			}
668
669
			$modules = Jetpack_Admin::init()->get_modules();
670
			echo json_encode( $modules[ $slug ] );
671
672
			exit;
673
		}
674
675
		wp_die();
676
	}
677
678
	/*
679
	 * Sometimes we need to refresh the data,
680
	 * especially if the page is visited via a 'history'
681
	 * event like back/forward
682
	 */
683
	function jetpack_admin_ajax_refresh_data() {
684
		// Check for nonce
685 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
686
			wp_die( 'permissions check failed' );
687
		}
688
689
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
690
			$modules = Jetpack_Admin::init()->get_modules();
691
			echo json_encode( $modules );
692
			exit;
693
		}
694
695
		wp_die();
696
	}
697
698
	/**
699
	 * The callback for the Jump Start ajax requests.
700
	 */
701
	function jetpack_jumpstart_ajax_callback() {
702
		// Check for nonce
703
		if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
704
			wp_die( 'permissions check failed' );
705
706
		if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
707
			// Update the jumpstart option
708
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
709
				Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
710
			}
711
712
			// Loops through the requested "Jump Start" modules, and activates them.
713
			// Custom 'no_message' state, so that no message will be shown on reload.
714
			$modules = $_REQUEST['jumpstartModSlug'];
715
			$module_slugs = array();
716
			foreach( $modules as $module => $value ) {
717
				$module_slugs[] = $value['module_slug'];
718
			}
719
720
			// Check for possible conflicting plugins
721
			$module_slugs_filtered = $this->filter_default_modules( $module_slugs );
722
723
			foreach ( $module_slugs_filtered as $module_slug ) {
724
				Jetpack::log( 'activate', $module_slug );
725
				Jetpack::activate_module( $module_slug, false, false );
726
				Jetpack::state( 'message', 'no_message' );
727
			}
728
729
			// Set the default sharing buttons and set to display on posts if none have been set.
730
			$sharing_services = get_option( 'sharing-services' );
731
			$sharing_options  = get_option( 'sharing-options' );
732
			if ( empty( $sharing_services['visible'] ) ) {
733
				// Default buttons to set
734
				$visible = array(
735
					'twitter',
736
					'facebook',
737
					'google-plus-1',
738
				);
739
				$hidden = array();
740
741
				// Set some sharing settings
742
				$sharing = new Sharing_Service();
743
				$sharing_options['global'] = array(
744
					'button_style'  => 'icon',
745
					'sharing_label' => $sharing->default_sharing_label,
746
					'open_links'    => 'same',
747
					'show'          => array( 'post' ),
748
					'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
749
				);
750
751
				update_option( 'sharing-options', $sharing_options );
752
753
				// Send a success response so that we can display an error message.
754
				$success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
755
				echo json_encode( $success );
756
				exit;
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...
757
			}
758
759
		} elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
760
			// If dismissed, flag the jumpstart option as such.
761
			// Send a success response so that we can display an error message.
762
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
763
				$success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
764
				echo json_encode( $success );
765
				exit;
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...
766
			}
767
768
		} elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
769
770
			// FOR TESTING ONLY
771
			// @todo remove
772
			$modules = (array) $_REQUEST['jumpstartModSlug'];
773
			foreach( $modules as $module => $value ) {
774
				if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
775
					Jetpack::log( 'deactivate', $value['module_slug'] );
776
					Jetpack::deactivate_module( $value['module_slug'] );
777
					Jetpack::state( 'message', 'no_message' );
778
				} else {
779
					Jetpack::log( 'activate', $value['module_slug'] );
780
					Jetpack::activate_module( $value['module_slug'], false, false );
781
					Jetpack::state( 'message', 'no_message' );
782
				}
783
			}
784
785
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
786
			echo "reload the page";
787
		}
788
789
		wp_die();
790
	}
791
792
	/**
793
	 * The callback for the JITM ajax requests.
794
	 */
795
	function jetpack_jitm_ajax_callback() {
796
		// Check for nonce
797
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
798
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
799
		}
800
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
801
			$module_slug = $_REQUEST['jitmModule'];
802
			Jetpack::log( 'activate', $module_slug );
803
			Jetpack::activate_module( $module_slug, false, false );
804
			Jetpack::state( 'message', 'no_message' );
805
806
			//A Jetpack module is being activated through a JITM, track it
807
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
808
			$this->do_stats( 'server_side' );
809
810
			wp_send_json_success();
811
		}
812
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
813
			// get the hide_jitm options array
814
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
815
			$module_slug = $_REQUEST['jitmModule'];
816
817
			if( ! $jetpack_hide_jitm ) {
818
				$jetpack_hide_jitm = array(
819
					$module_slug => 'hide'
820
				);
821
			} else {
822
				$jetpack_hide_jitm[$module_slug] = 'hide';
823
			}
824
825
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
826
827
			//jitm is being dismissed forever, track it
828
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
829
			$this->do_stats( 'server_side' );
830
831
			wp_send_json_success();
832
		}
833 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
834
			$module_slug = $_REQUEST['jitmModule'];
835
836
			// User went to WordPress.com, track this
837
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
838
			$this->do_stats( 'server_side' );
839
840
			wp_send_json_success();
841
		}
842 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
843
			$track = $_REQUEST['jitmModule'];
844
845
			// User is viewing JITM, track it.
846
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
847
			$this->do_stats( 'server_side' );
848
849
			wp_send_json_success();
850
		}
851
	}
852
853
	/**
854
	 * If there are any stats that need to be pushed, but haven't been, push them now.
855
	 */
856
	function __destruct() {
857
		if ( ! empty( $this->stats ) ) {
858
			$this->do_stats( 'server_side' );
859
		}
860
	}
861
862
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
863
		switch( $cap ) {
864
			case 'jetpack_connect' :
865
			case 'jetpack_reconnect' :
866
				if ( Jetpack::is_development_mode() ) {
867
					$caps = array( 'do_not_allow' );
868
					break;
869
				}
870
				/**
871
				 * Pass through. If it's not development mode, these should match disconnect.
872
				 * Let users disconnect if it's development mode, just in case things glitch.
873
				 */
874
			case 'jetpack_disconnect' :
875
				/**
876
				 * In multisite, can individual site admins manage their own connection?
877
				 *
878
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
879
				 */
880
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
881
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
882
						/**
883
						 * We need to update the option name -- it's terribly unclear which
884
						 * direction the override goes.
885
						 *
886
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
887
						 */
888
						$caps = array( 'do_not_allow' );
889
						break;
890
					}
891
				}
892
893
				$caps = array( 'manage_options' );
894
				break;
895
			case 'jetpack_manage_modules' :
896
			case 'jetpack_activate_modules' :
897
			case 'jetpack_deactivate_modules' :
898
				$caps = array( 'manage_options' );
899
				break;
900
			case 'jetpack_configure_modules' :
901
				$caps = array( 'manage_options' );
902
				break;
903
			case 'jetpack_network_admin_page':
904
			case 'jetpack_network_settings_page':
905
				$caps = array( 'manage_network_plugins' );
906
				break;
907
			case 'jetpack_network_sites_page':
908
				$caps = array( 'manage_sites' );
909
				break;
910
			case 'jetpack_admin_page' :
911
				if ( Jetpack::is_development_mode() ) {
912
					$caps = array( 'manage_options' );
913
					break;
914
				}
915
916
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
917
				if ( ! current_user_can( 'edit_posts' ) ) {
918
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
919
						// We need this in order to unlink the user.
920
						$this->admin_page_load();
921
					}
922
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
923
						$caps = array( 'do_not_allow' );
924
						break;
925
					}
926
				}
927
928
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
929
					$caps = array( 'do_not_allow' );
930
					break;
931
				}
932
				/**
933
				 * Pass through. If it's not development mode, these should match the admin page.
934
				 * Let users disconnect if it's development mode, just in case things glitch.
935
				 */
936
			case 'jetpack_connect_user' :
937
				if ( Jetpack::is_development_mode() ) {
938
					$caps = array( 'do_not_allow' );
939
					break;
940
				}
941
				$caps = array( 'read' );
942
				break;
943
		}
944
		return $caps;
945
	}
946
947
	function require_jetpack_authentication() {
948
		// Don't let anyone authenticate
949
		$_COOKIE = array();
950
		remove_all_filters( 'authenticate' );
951
952
		/**
953
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
954
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
955
		 * generate false-positives.
956
		 */
957
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
958
959
		if ( Jetpack::is_active() ) {
960
			// Allow Jetpack authentication
961
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
962
		}
963
	}
964
965
	/**
966
	 * Load language files
967
	 */
968
	public static function plugin_textdomain() {
969
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
970
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
971
	}
972
973
	/**
974
	 * Register assets for use in various modules and the Jetpack admin page.
975
	 *
976
	 * @uses wp_script_is, wp_register_script, plugins_url
977
	 * @action wp_loaded
978
	 * @return null
979
	 */
980
	public function register_assets() {
981
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
982
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
983
		}
984
985 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
986
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
987
		}
988
989 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
990
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
991
		}
992
993 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
994
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
995
		}
996
997
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
998
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
999
1000
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1001
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1002
			if ( ! is_numeric( $fb_app_id ) ) {
1003
				$fb_app_id = '';
1004
			}
1005
			wp_localize_script(
1006
				'jetpack-facebook-embed',
1007
				'jpfbembed',
1008
				array(
1009
					'appid' => $fb_app_id,
1010
					'locale' => $this->get_locale(),
1011
				)
1012
			);
1013
		}
1014
1015
		/**
1016
		 * As jetpack_register_genericons is by default fired off a hook,
1017
		 * the hook may have already fired by this point.
1018
		 * So, let's just trigger it manually.
1019
		 */
1020
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1021
		jetpack_register_genericons();
1022
1023 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1024
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1025
	}
1026
1027
	/**
1028
	 * Guess locale from language code.
1029
	 *
1030
	 * @param string $lang Language code.
1031
	 * @return string|bool
1032
	 */
1033 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1034
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1035
			return 'en_US';
1036
		}
1037
1038
		if ( ! class_exists( 'GP_Locales' ) ) {
1039
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1040
				return false;
1041
			}
1042
1043
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1044
		}
1045
1046
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1047
			// WP.com: get_locale() returns 'it'
1048
			$locale = GP_Locales::by_slug( $lang );
1049
		} else {
1050
			// Jetpack: get_locale() returns 'it_IT';
1051
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1052
		}
1053
1054
		if ( ! $locale ) {
1055
			return false;
1056
		}
1057
1058
		if ( empty( $locale->facebook_locale ) ) {
1059
			if ( empty( $locale->wp_locale ) ) {
1060
				return false;
1061
			} else {
1062
				// Facebook SDK is smart enough to fall back to en_US if a
1063
				// locale isn't supported. Since supported Facebook locales
1064
				// can fall out of sync, we'll attempt to use the known
1065
				// wp_locale value and rely on said fallback.
1066
				return $locale->wp_locale;
1067
			}
1068
		}
1069
1070
		return $locale->facebook_locale;
1071
	}
1072
1073
	/**
1074
	 * Get the locale.
1075
	 *
1076
	 * @return string|bool
1077
	 */
1078
	function get_locale() {
1079
		$locale = $this->guess_locale_from_lang( get_locale() );
1080
1081
		if ( ! $locale ) {
1082
			$locale = 'en_US';
1083
		}
1084
1085
		return $locale;
1086
	}
1087
1088
	/**
1089
	 * Device Pixels support
1090
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1091
	 */
1092
	function devicepx() {
1093
		if ( Jetpack::is_active() ) {
1094
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
1095
		}
1096
	}
1097
1098
	/*
1099
	 * Returns the location of Jetpack's lib directory. This filter is applied
1100
	 * in require_lib().
1101
	 *
1102
	 * @filter require_lib_dir
1103
	 */
1104
	function require_lib_dir() {
1105
		return JETPACK__PLUGIN_DIR . '_inc/lib';
1106
	}
1107
1108
	/**
1109
	 * Return the network_site_url so that .com knows what network this site is a part of.
1110
	 * @param  bool $option
1111
	 * @return string
1112
	 */
1113
	public function jetpack_main_network_site_option( $option ) {
1114
		return network_site_url();
1115
	}
1116
	/**
1117
	 * Network Name.
1118
	 */
1119
	static function network_name( $option = null ) {
1120
		global $current_site;
1121
		return $current_site->site_name;
1122
	}
1123
	/**
1124
	 * Does the network allow new user and site registrations.
1125
	 * @return string
1126
	 */
1127
	static function network_allow_new_registrations( $option = null ) {
1128
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1129
	}
1130
	/**
1131
	 * Does the network allow admins to add new users.
1132
	 * @return boolian
1133
	 */
1134
	static function network_add_new_users( $option = null ) {
1135
		return (bool) get_site_option( 'add_new_users' );
1136
	}
1137
	/**
1138
	 * File upload psace left per site in MB.
1139
	 *  -1 means NO LIMIT.
1140
	 * @return number
1141
	 */
1142
	static function network_site_upload_space( $option = null ) {
1143
		// value in MB
1144
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1145
	}
1146
1147
	/**
1148
	 * Network allowed file types.
1149
	 * @return string
1150
	 */
1151
	static function network_upload_file_types( $option = null ) {
1152
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1153
	}
1154
1155
	/**
1156
	 * Maximum file upload size set by the network.
1157
	 * @return number
1158
	 */
1159
	static function network_max_upload_file_size( $option = null ) {
1160
		// value in KB
1161
		return get_site_option( 'fileupload_maxk', 300 );
1162
	}
1163
1164
	/**
1165
	 * Lets us know if a site allows admins to manage the network.
1166
	 * @return array
1167
	 */
1168
	static function network_enable_administration_menus( $option = null ) {
1169
		return get_site_option( 'menu_items' );
1170
	}
1171
1172
	/**
1173
	 * Return whether we are dealing with a multi network setup or not.
1174
	 * The reason we are type casting this is because we want to avoid the situation where
1175
	 * the result is false since when is_main_network_option return false it cases
1176
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1177
	 * database which could be set to anything as opposed to what this function returns.
1178
	 * @param  bool  $option
1179
	 *
1180
	 * @return boolean
1181
	 */
1182
	public function is_main_network_option( $option ) {
1183
		// return '1' or ''
1184
		return (string) (bool) Jetpack::is_multi_network();
1185
	}
1186
1187
	/**
1188
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1189
	 *
1190
	 * @param  string  $option
1191
	 * @return boolean
1192
	 */
1193
	public function is_multisite( $option ) {
1194
		return (string) (bool) is_multisite();
1195
	}
1196
1197
	/**
1198
	 * Implemented since there is no core is multi network function
1199
	 * Right now there is no way to tell if we which network is the dominant network on the system
1200
	 *
1201
	 * @since  3.3
1202
	 * @return boolean
1203
	 */
1204
	public static function is_multi_network() {
1205
		global  $wpdb;
1206
1207
		// if we don't have a multi site setup no need to do any more
1208
		if ( ! is_multisite() ) {
1209
			return false;
1210
		}
1211
1212
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1213
		if ( $num_sites > 1 ) {
1214
			return true;
1215
		} else {
1216
			return false;
1217
		}
1218
	}
1219
1220
	/**
1221
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1222
	 * @return null
1223
	 */
1224
	function update_jetpack_main_network_site_option() {
1225
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1226
		/**
1227
		 * Fires when the site URL is updated.
1228
		 * Determines if the site is the main site of a Mulitiste network.
1229
		 *
1230
		 * @since 3.3.0
1231
		 *
1232
		 * @param string jetpack_main_network_site.
1233
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1234
		 */
1235
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1236
		/**
1237
		 * Fires when the site URL is updated.
1238
		 * Determines if the is part of a multi network.
1239
		 *
1240
		 * @since 3.3.0
1241
		 *
1242
		 * @param string jetpack_is_main_network.
1243
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1244
		 */
1245
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1246
		/**
1247
		 * Fires when the site URL is updated.
1248
		 * Determines if the site is part of a multisite network.
1249
		 *
1250
		 * @since 3.4.0
1251
		 *
1252
		 * @param string jetpack_is_multi_site.
1253
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1254
		 */
1255
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1256
	}
1257
	/**
1258
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1259
	 *
1260
	 */
1261
	function update_jetpack_network_settings() {
1262
		// Only sync this info for the main network site.
1263
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1264
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1265
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1266
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1267
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1268
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1269
1270
	}
1271
1272
	/**
1273
	 * Get back if the current site is single user site.
1274
	 *
1275
	 * @return bool
1276
	 */
1277
	public static function is_single_user_site() {
1278
1279
		$user_query = new WP_User_Query( array(
1280
			'blog_id' => get_current_blog_id(),
1281
			'fields'  => 'ID',
1282
			'number' => 2
1283
		) );
1284
		return 1 === (int) $user_query->get_total();
1285
	}
1286
1287
	/**
1288
	 * Returns true if the site has file write access false otherwise.
1289
	 * @return string ( '1' | '0' )
1290
	 **/
1291
	public static function file_system_write_access() {
1292
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1293
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1294
		}
1295
1296
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1297
1298
		$filesystem_method = get_filesystem_method();
1299
		if ( $filesystem_method === 'direct' ) {
1300
			return 1;
1301
		}
1302
1303
		ob_start();
1304
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1305
		ob_end_clean();
1306
		if ( $filesystem_credentials_are_stored ) {
1307
			return 1;
1308
		}
1309
		return 0;
1310
	}
1311
1312
	/**
1313
	 * Finds out if a site is using a version control system.
1314
	 * @return string ( '1' | '0' )
1315
	 **/
1316
	public static function is_version_controlled() {
1317
1318
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1319
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1320
		}
1321
		$updater = new WP_Automatic_Updater();
1322
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1323
		// transients should not be empty
1324
		if ( empty( $is_version_controlled ) ) {
1325
			$is_version_controlled = '0';
1326
		}
1327
		return $is_version_controlled;
1328
	}
1329
1330
	/**
1331
	 * Determines whether the current theme supports featured images or not.
1332
	 * @return string ( '1' | '0' )
1333
	 */
1334
	public static function featured_images_enabled() {
1335
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1336
	}
1337
1338
	/*
1339
	 * Sync back wp_version
1340
	 */
1341
	public static function get_wp_version() {
1342
		global $wp_version;
1343
		return $wp_version;
1344
	}
1345
1346
	/**
1347
	 * Keeps wp_version in sync with .com when WordPress core updates
1348
	 **/
1349
	public static function update_get_wp_version( $update, $meta_data ) {
1350
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1351
			/** This action is documented in wp-includes/option.php */
1352
			/**
1353
			 * This triggers the sync for the jetpack version
1354
			 * See Jetpack_Sync options method for more info.
1355
			 */
1356
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1357
		}
1358
	}
1359
1360
	/**
1361
	 * Triggers a sync of update counts and update details
1362
	 */
1363
	function sync_update_data() {
1364
		// Anytime WordPress saves update data, we'll want to sync update data
1365
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1366
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1367
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1368
		// Anytime a connection to jetpack is made, sync the update data
1369
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1370
		// Anytime the Jetpack Version changes, sync the the update data
1371
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1372
1373
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1374
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1375
		}
1376
1377
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1378
	}
1379
1380
	/**
1381
	 * Triggers a sync of information specific to the current theme.
1382
	 */
1383
	function sync_theme_data() {
1384
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1385
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1386
	}
1387
1388
	/**
1389
	 * jetpack_updates is saved in the following schema:
1390
	 *
1391
	 * array (
1392
	 *      'plugins'                       => (int) Number of plugin updates available.
1393
	 *      'themes'                        => (int) Number of theme updates available.
1394
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1395
	 *      'translations'                  => (int) Number of translation updates available.
1396
	 *      'total'                         => (int) Total of all available updates.
1397
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1398
	 * )
1399
	 * @return array
1400
	 */
1401
	public static function get_updates() {
1402
		$update_data = wp_get_update_data();
1403
1404
		// Stores the individual update counts as well as the total count.
1405
		if ( isset( $update_data['counts'] ) ) {
1406
			$updates = $update_data['counts'];
1407
		}
1408
1409
		// If we need to update WordPress core, let's find the latest version number.
1410 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1411
			$cur = get_preferred_from_update_core();
1412
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1413
				$updates['wp_update_version'] = $cur->current;
1414
			}
1415
		}
1416
		return isset( $updates ) ? $updates : array();
1417
	}
1418
1419
	public static function get_update_details() {
1420
		$update_details = array(
1421
			'update_core' => get_site_transient( 'update_core' ),
1422
			'update_plugins' => get_site_transient( 'update_plugins' ),
1423
			'update_themes' => get_site_transient( 'update_themes' ),
1424
		);
1425
		return $update_details;
1426
	}
1427
1428
	public static function refresh_update_data() {
1429
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1430
			/**
1431
			 * Fires whenever the amount of updates needed for a site changes.
1432
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1433
			 *
1434
			 * @since 3.7.0
1435
			 *
1436
			 * @param string jetpack_updates
1437
			 * @param array Update counts calculated by Jetpack::get_updates
1438
			 */
1439
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1440
		}
1441
		/**
1442
		 * Fires whenever the amount of updates needed for a site changes.
1443
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1444
		 *
1445
		 * @since 3.7.0
1446
		 *
1447
		 * @param string jetpack_update_details
1448
		 * @param array Update details calculated by Jetpack::get_update_details
1449
		 */
1450
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1451
	}
1452
1453
	public static function refresh_theme_data() {
1454
		/**
1455
		 * Fires whenever a theme change is made.
1456
		 *
1457
		 * @since 3.8.1
1458
		 *
1459
		 * @param string featured_images_enabled
1460
		 * @param boolean Whether featured images are enabled or not
1461
		 */
1462
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1463
	}
1464
1465
	/**
1466
	 * Invalides the transient as well as triggers the update of the mock option.
1467
	 *
1468
	 * @return null
1469
	 */
1470
	function is_single_user_site_invalidate() {
1471
		/**
1472
		 * Fires when a user is added or removed from a site.
1473
		 * Determines if the site is a single user site.
1474
		 *
1475
		 * @since 3.4.0
1476
		 *
1477
		 * @param string jetpack_single_user_site.
1478
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1479
		 */
1480
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1481
	}
1482
1483
	/**
1484
	 * Is Jetpack active?
1485
	 */
1486
	public static function is_active() {
1487
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1488
	}
1489
1490
	/**
1491
	 * Is Jetpack in development (offline) mode?
1492
	 */
1493
	public static function is_development_mode() {
1494
		$development_mode = false;
1495
1496
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1497
			$development_mode = JETPACK_DEV_DEBUG;
1498
		}
1499
1500
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1501
			$development_mode = true;
1502
		}
1503
		/**
1504
		 * Filters Jetpack's development mode.
1505
		 *
1506
		 * @see http://jetpack.com/support/development-mode/
1507
		 *
1508
		 * @since 2.2.1
1509
		 *
1510
		 * @param bool $development_mode Is Jetpack's development mode active.
1511
		 */
1512
		return apply_filters( 'jetpack_development_mode', $development_mode );
1513
	}
1514
1515
	/**
1516
	* Get Jetpack development mode notice text and notice class.
1517
	*
1518
	* Mirrors the checks made in Jetpack::is_development_mode
1519
	*
1520
	*/
1521
	public static function show_development_mode_notice() {
1522
		if ( Jetpack::is_development_mode() ) {
1523
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1524
				$notice = sprintf(
1525
					/* translators: %s is a URL */
1526
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1527
					'http://jetpack.com/support/development-mode/'
1528
				);
1529
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1530
				$notice = sprintf(
1531
					/* translators: %s is a URL */
1532
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1533
					'http://jetpack.com/support/development-mode/'
1534
				);
1535
			} else {
1536
				$notice = sprintf(
1537
					/* translators: %s is a URL */
1538
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1539
					'http://jetpack.com/support/development-mode/'
1540
				);
1541
			}
1542
1543
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1544
		}
1545
1546
		// Throw up a notice if using a development version and as for feedback.
1547
		if ( Jetpack::is_development_version() ) {
1548
			/* translators: %s is a URL */
1549
			$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/' );
1550
1551
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1552
		}
1553
		// Throw up a notice if using staging mode
1554
		if ( Jetpack::is_staging_site() ) {
1555
			/* translators: %s is a URL */
1556
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1557
1558
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1559
		}
1560
	}
1561
1562
	/**
1563
	 * Whether Jetpack's version maps to a public release, or a development version.
1564
	 */
1565
	public static function is_development_version() {
1566
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1567
	}
1568
1569
	/**
1570
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1571
	 */
1572
	public static function is_user_connected( $user_id = false ) {
1573
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1574
		if ( ! $user_id ) {
1575
			return false;
1576
		}
1577
		return (bool) Jetpack_Data::get_access_token( $user_id );
1578
	}
1579
1580
	/**
1581
	 * Get the wpcom user data of the current|specified connected user.
1582
	 */
1583 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1584
		if ( ! $user_id ) {
1585
			$user_id = get_current_user_id();
1586
		}
1587
		Jetpack::load_xml_rpc_client();
1588
		$xml = new Jetpack_IXR_Client( array(
1589
			'user_id' => $user_id,
1590
		) );
1591
		$xml->query( 'wpcom.getUser' );
1592
		if ( ! $xml->isError() ) {
1593
			return $xml->getResponse();
1594
		}
1595
		return false;
1596
	}
1597
1598
	/**
1599
	 * Get the wpcom email of the current|specified connected user.
1600
	 */
1601 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1602
		if ( ! $user_id ) {
1603
			$user_id = get_current_user_id();
1604
		}
1605
		Jetpack::load_xml_rpc_client();
1606
		$xml = new Jetpack_IXR_Client( array(
1607
			'user_id' => $user_id,
1608
		) );
1609
		$xml->query( 'wpcom.getUserEmail' );
1610
		if ( ! $xml->isError() ) {
1611
			return $xml->getResponse();
1612
		}
1613
		return false;
1614
	}
1615
1616
	/**
1617
	 * Get the wpcom email of the master user.
1618
	 */
1619
	public static function get_master_user_email() {
1620
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1621
		if ( $master_user_id ) {
1622
			return self::get_connected_user_email( $master_user_id );
1623
		}
1624
		return '';
1625
	}
1626
1627
	function current_user_is_connection_owner() {
1628
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1629
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1630
	}
1631
1632
	/**
1633
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1634
	 */
1635
	function extra_oembed_providers() {
1636
		// Cloudup: https://dev.cloudup.com/#oembed
1637
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1638
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1639
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1640
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1641
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1642
	}
1643
1644
	/**
1645
	 * Synchronize connected user role changes
1646
	 */
1647
	function user_role_change( $user_id ) {
1648
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1649
			$current_user_id = get_current_user_id();
1650
			wp_set_current_user( $user_id );
1651
			$role = $this->translate_current_user_to_role();
1652
			$signed_role = $this->sign_role( $role );
1653
			wp_set_current_user( $current_user_id );
1654
1655
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1656
			$master_user_id = absint( $master_token->external_user_id );
1657
1658
			if ( ! $master_user_id )
1659
				return; // this shouldn't happen
1660
1661
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1662
			//@todo retry on failure
1663
1664
			//try to choose a new master if we're demoting the current one
1665
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1666
				$query = new WP_User_Query(
1667
					array(
1668
						'fields'  => array( 'id' ),
1669
						'role'    => 'administrator',
1670
						'orderby' => 'id',
1671
						'exclude' => array( $master_user_id ),
1672
					)
1673
				);
1674
				$new_master = false;
1675
				foreach ( $query->results as $result ) {
1676
					$uid = absint( $result->id );
1677
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1678
						$new_master = $uid;
1679
						break;
1680
					}
1681
				}
1682
1683
				if ( $new_master ) {
1684
					Jetpack_Options::update_option( 'master_user', $new_master );
1685
				}
1686
				// else disconnect..?
1687
			}
1688
		}
1689
	}
1690
1691
	/**
1692
	 * Loads the currently active modules.
1693
	 */
1694
	public static function load_modules() {
1695
		if ( ! self::is_active() && !self::is_development_mode() ) {
1696
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1697
				return;
1698
			}
1699
		}
1700
1701
		$version = Jetpack_Options::get_option( 'version' );
1702 View Code Duplication
		if ( ! $version ) {
1703
			$version = $old_version = JETPACK__VERSION . ':' . time();
1704
			/** This action is documented in class.jetpack.php */
1705
			do_action( 'updating_jetpack_version', $version, false );
1706
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1707
		}
1708
		list( $version ) = explode( ':', $version );
1709
1710
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1711
1712
		$modules_data = array();
1713
1714
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1715
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1716
			$updated_modules = array();
1717
			foreach ( $modules as $module ) {
1718
				$modules_data[ $module ] = Jetpack::get_module( $module );
1719
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1720
					continue;
1721
				}
1722
1723
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1724
					continue;
1725
				}
1726
1727
				$updated_modules[] = $module;
1728
			}
1729
1730
			$modules = array_diff( $modules, $updated_modules );
1731
		}
1732
1733
		$is_development_mode = Jetpack::is_development_mode();
1734
1735
		foreach ( $modules as $index => $module ) {
1736
			// If we're in dev mode, disable modules requiring a connection
1737
			if ( $is_development_mode ) {
1738
				// Prime the pump if we need to
1739
				if ( empty( $modules_data[ $module ] ) ) {
1740
					$modules_data[ $module ] = Jetpack::get_module( $module );
1741
				}
1742
				// If the module requires a connection, but we're in local mode, don't include it.
1743
				if ( $modules_data[ $module ]['requires_connection'] ) {
1744
					continue;
1745
				}
1746
			}
1747
1748
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1749
				continue;
1750
			}
1751
1752
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1753
				unset( $modules[ $index ] );
1754
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1755
				continue;
1756
			}
1757
1758
			/**
1759
			 * Fires when a specific module is loaded.
1760
			 * The dynamic part of the hook, $module, is the module slug.
1761
			 *
1762
			 * @since 1.1.0
1763
			 */
1764
			do_action( 'jetpack_module_loaded_' . $module );
1765
		}
1766
1767
		/**
1768
		 * Fires when all the modules are loaded.
1769
		 *
1770
		 * @since 1.1.0
1771
		 */
1772
		do_action( 'jetpack_modules_loaded' );
1773
1774
		// 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.
1775
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1776
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1777
	}
1778
1779
	/**
1780
	 * Check if Jetpack's REST API compat file should be included
1781
	 * @action plugins_loaded
1782
	 * @return null
1783
	 */
1784
	public function check_rest_api_compat() {
1785
		/**
1786
		 * Filters the list of REST API compat files to be included.
1787
		 *
1788
		 * @since 2.2.5
1789
		 *
1790
		 * @param array $args Array of REST API compat files to include.
1791
		 */
1792
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1793
1794
		if ( function_exists( 'bbpress' ) )
1795
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1796
1797
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1798
			require_once $_jetpack_rest_api_compat_include;
1799
	}
1800
1801
	/**
1802
	 * Gets all plugins currently active in values, regardless of whether they're
1803
	 * traditionally activated or network activated.
1804
	 *
1805
	 * @todo Store the result in core's object cache maybe?
1806
	 */
1807
	public static function get_active_plugins() {
1808
		$active_plugins = (array) get_option( 'active_plugins', array() );
1809
1810
		if ( is_multisite() ) {
1811
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1812
			// whereas active_plugins stores them in the values.
1813
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1814
			if ( $network_plugins ) {
1815
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1816
			}
1817
		}
1818
1819
		sort( $active_plugins );
1820
1821
		return array_unique( $active_plugins );
1822
	}
1823
1824
	/**
1825
	 * Gets and parses additional plugin data to send with the heartbeat data
1826
	 *
1827
	 * @since 3.8.1
1828
	 *
1829
	 * @return array Array of plugin data
1830
	 */
1831
	public static function get_parsed_plugin_data() {
1832
		if ( ! function_exists( 'get_plugins' ) ) {
1833
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1834
		}
1835
		$all_plugins    = get_plugins();
1836
		$active_plugins = Jetpack::get_active_plugins();
1837
1838
		$plugins = array();
1839
		foreach ( $all_plugins as $path => $plugin_data ) {
1840
			$plugins[ $path ] = array(
1841
					'is_active' => in_array( $path, $active_plugins ),
1842
					'file'      => $path,
1843
					'name'      => $plugin_data['Name'],
1844
					'version'   => $plugin_data['Version'],
1845
					'author'    => $plugin_data['Author'],
1846
			);
1847
		}
1848
1849
		return $plugins;
1850
	}
1851
1852
	/**
1853
	 * Gets and parses theme data to send with the heartbeat data
1854
	 *
1855
	 * @since 3.8.1
1856
	 *
1857
	 * @return array Array of theme data
1858
	 */
1859
	public static function get_parsed_theme_data() {
1860
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1861
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1862
1863
		$themes = array();
1864
		foreach ( $all_themes as $slug => $theme_data ) {
1865
			$theme_headers = array();
1866
			foreach ( $header_keys as $header_key ) {
1867
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1868
			}
1869
1870
			$themes[ $slug ] = array(
1871
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1872
					'slug' => $slug,
1873
					'theme_root' => $theme_data->get_theme_root_uri(),
1874
					'parent' => $theme_data->parent(),
1875
					'headers' => $theme_headers
1876
			);
1877
		}
1878
1879
		return $themes;
1880
	}
1881
1882
	/**
1883
	 * Checks whether a specific plugin is active.
1884
	 *
1885
	 * We don't want to store these in a static variable, in case
1886
	 * there are switch_to_blog() calls involved.
1887
	 */
1888
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1889
		return in_array( $plugin, self::get_active_plugins() );
1890
	}
1891
1892
	/**
1893
	 * Check if Jetpack's Open Graph tags should be used.
1894
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1895
	 *
1896
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1897
	 * @action plugins_loaded
1898
	 * @return null
1899
	 */
1900
	public function check_open_graph() {
1901
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1902
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1903
		}
1904
1905
		$active_plugins = self::get_active_plugins();
1906
1907
		if ( ! empty( $active_plugins ) ) {
1908
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1909
				if ( in_array( $plugin, $active_plugins ) ) {
1910
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1911
					break;
1912
				}
1913
			}
1914
		}
1915
1916
		/**
1917
		 * Allow the addition of Open Graph Meta Tags to all pages.
1918
		 *
1919
		 * @since 2.0.3
1920
		 *
1921
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1922
		 */
1923
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1924
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1925
		}
1926
	}
1927
1928
	/**
1929
	 * Check if Jetpack's Twitter tags should be used.
1930
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1931
	 *
1932
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1933
	 * @action plugins_loaded
1934
	 * @return null
1935
	 */
1936
	public function check_twitter_tags() {
1937
1938
		$active_plugins = self::get_active_plugins();
1939
1940
		if ( ! empty( $active_plugins ) ) {
1941
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1942
				if ( in_array( $plugin, $active_plugins ) ) {
1943
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1944
					break;
1945
				}
1946
			}
1947
		}
1948
1949
		/**
1950
		 * Allow Twitter Card Meta tags to be disabled.
1951
		 *
1952
		 * @since 2.6.0
1953
		 *
1954
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1955
		 */
1956
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1957
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1958
		}
1959
	}
1960
1961
1962
1963
1964
	/*
1965
	 *
1966
	 * Jetpack Security Reports
1967
	 *
1968
	 * Allowed types: login_form, backup, file_scanning, spam
1969
	 *
1970
	 * 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)
1971
	 *
1972
	 * 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)
1973
	 *
1974
	 *
1975
	 * Example code to submit a security report:
1976
	 *
1977
	 *  function akismet_submit_jetpack_security_report() {
1978
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1979
	 *  }
1980
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1981
	 *
1982
	 */
1983
1984
1985
	/**
1986
	 * Calls for security report submissions.
1987
	 *
1988
	 * @return null
1989
	 */
1990
	public static function perform_security_reporting() {
1991
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1992
1993
		if ( $no_check_needed ) {
1994
			return;
1995
		}
1996
1997
		/**
1998
		 * Fires before a security report is created.
1999
		 *
2000
		 * @since 3.4.0
2001
		 */
2002
		do_action( 'jetpack_security_report' );
2003
2004
		Jetpack_Options::update_option( 'security_report', self::$security_report );
2005
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
2006
	}
2007
2008
	/**
2009
	 * Allows plugins to submit security reports.
2010
 	 *
2011
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2012
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2013
	 * @param array   $args         See definitions above
2014
	 */
2015
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2016
2017
		if( !doing_action( 'jetpack_security_report' ) ) {
2018
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
2019
		}
2020
2021
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
2022
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
2023
		}
2024
2025
		if( !function_exists( 'get_plugin_data' ) ) {
2026
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
2027
		}
2028
2029
		//Get rid of any non-allowed args
2030
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
2031
2032
		$plugin = get_plugin_data( $plugin_file );
2033
2034
		if ( !$plugin['Name'] ) {
2035
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
2036
		}
2037
2038
		// Sanitize everything to make sure we're not syncing something wonky
2039
		$type = sanitize_key( $type );
2040
2041
		$args['plugin'] = $plugin;
2042
2043
		// Cast blocked, last and next as integers.
2044
		// Last and next should be in unix timestamp format
2045
		if ( isset( $args['blocked'] ) ) {
2046
			$args['blocked'] = (int) $args['blocked'];
2047
		}
2048
		if ( isset( $args['last'] ) ) {
2049
			$args['last'] = (int) $args['last'];
2050
		}
2051
		if ( isset( $args['next'] ) ) {
2052
			$args['next'] = (int) $args['next'];
2053
		}
2054
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
2055
			$args['status'] = 'ok';
2056
		}
2057
		if ( isset( $args['message'] ) ) {
2058
2059
			if( $args['status'] == 'ok' ) {
2060
				unset( $args['message'] );
2061
			}
2062
2063
			$allowed_html = array(
2064
			    'a' => array(
2065
			        'href' => array(),
2066
			        'title' => array()
2067
			    ),
2068
			    'em' => array(),
2069
			    'strong' => array(),
2070
			);
2071
2072
			$args['message'] = wp_kses( $args['message'], $allowed_html );
2073
		}
2074
2075
		$plugin_name = $plugin[ 'Name' ];
2076
2077
		self::$security_report[ $type ][ $plugin_name ] = $args;
2078
	}
2079
2080
	/**
2081
	 * Collects a new report if needed, then returns it.
2082
	 */
2083
	public function get_security_report() {
2084
		self::perform_security_reporting();
2085
		return Jetpack_Options::get_option( 'security_report' );
2086
	}
2087
2088
2089
/* Jetpack Options API */
2090
2091
	public static function get_option_names( $type = 'compact' ) {
2092
		return Jetpack_Options::get_option_names( $type );
2093
	}
2094
2095
	/**
2096
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2097
 	 *
2098
	 * @param string $name    Option name
2099
	 * @param mixed  $default (optional)
2100
	 */
2101
	public static function get_option( $name, $default = false ) {
2102
		return Jetpack_Options::get_option( $name, $default );
2103
	}
2104
2105
	/**
2106
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
2107
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
2108
	* $name must be a registered option name.
2109
	*/
2110
	public static function create_nonce( $name ) {
2111
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
2112
2113
		Jetpack_Options::update_option( $name, $secret );
2114
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
2115
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2116
			return new Jetpack_Error( 'missing_secrets' );
2117
2118
		return array(
2119
			'secret_1' => $secret_1,
2120
			'secret_2' => $secret_2,
2121
			'eol'      => $eol,
2122
		);
2123
	}
2124
2125
	/**
2126
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2127
 	 *
2128
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2129
	 * @param string $name  Option name
2130
	 * @param mixed  $value Option value
2131
	 */
2132
	public static function update_option( $name, $value ) {
2133
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2134
		return Jetpack_Options::update_option( $name, $value );
2135
	}
2136
2137
	/**
2138
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2139
 	 *
2140
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2141
	 * @param array $array array( option name => option value, ... )
2142
	 */
2143
	public static function update_options( $array ) {
2144
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2145
		return Jetpack_Options::update_options( $array );
2146
	}
2147
2148
	/**
2149
	 * Deletes the given option.  May be passed multiple option names as an array.
2150
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2151
	 *
2152
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2153
	 * @param string|array $names
2154
	 */
2155
	public static function delete_option( $names ) {
2156
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2157
		return Jetpack_Options::delete_option( $names );
2158
	}
2159
2160
	/**
2161
	 * Enters a user token into the user_tokens option
2162
	 *
2163
	 * @param int $user_id
2164
	 * @param string $token
2165
	 * return bool
2166
	 */
2167
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2168
		// not designed for concurrent updates
2169
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2170
		if ( ! is_array( $user_tokens ) )
2171
			$user_tokens = array();
2172
		$user_tokens[$user_id] = $token;
2173
		if ( $is_master_user ) {
2174
			$master_user = $user_id;
2175
			$options     = compact( 'user_tokens', 'master_user' );
2176
		} else {
2177
			$options = compact( 'user_tokens' );
2178
		}
2179
		return Jetpack_Options::update_options( $options );
2180
	}
2181
2182
	/**
2183
	 * Returns an array of all PHP files in the specified absolute path.
2184
	 * Equivalent to glob( "$absolute_path/*.php" ).
2185
	 *
2186
	 * @param string $absolute_path The absolute path of the directory to search.
2187
	 * @return array Array of absolute paths to the PHP files.
2188
	 */
2189
	public static function glob_php( $absolute_path ) {
2190
		if ( function_exists( 'glob' ) ) {
2191
			return glob( "$absolute_path/*.php" );
2192
		}
2193
2194
		$absolute_path = untrailingslashit( $absolute_path );
2195
		$files = array();
2196
		if ( ! $dir = @opendir( $absolute_path ) ) {
2197
			return $files;
2198
		}
2199
2200
		while ( false !== $file = readdir( $dir ) ) {
2201
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2202
				continue;
2203
			}
2204
2205
			$file = "$absolute_path/$file";
2206
2207
			if ( ! is_file( $file ) ) {
2208
				continue;
2209
			}
2210
2211
			$files[] = $file;
2212
		}
2213
2214
		closedir( $dir );
2215
2216
		return $files;
2217
	}
2218
2219
	public static function activate_new_modules( $redirect = false ) {
2220
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2221
			return;
2222
		}
2223
2224
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2225 View Code Duplication
		if ( ! $jetpack_old_version ) {
2226
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2227
			/** This action is documented in class.jetpack.php */
2228
			do_action( 'updating_jetpack_version', $version, false );
2229
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2230
		}
2231
2232
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2233
2234
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2235
			return;
2236
		}
2237
2238
		$active_modules     = Jetpack::get_active_modules();
2239
		$reactivate_modules = array();
2240
		foreach ( $active_modules as $active_module ) {
2241
			$module = Jetpack::get_module( $active_module );
2242
			if ( ! isset( $module['changed'] ) ) {
2243
				continue;
2244
			}
2245
2246
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2247
				continue;
2248
			}
2249
2250
			$reactivate_modules[] = $active_module;
2251
			Jetpack::deactivate_module( $active_module );
2252
		}
2253
2254
		$new_version = JETPACK__VERSION . ':' . time();
2255
		/** This action is documented in class.jetpack.php */
2256
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2257
		Jetpack_Options::update_options(
2258
			array(
2259
				'version'     => $new_version,
2260
				'old_version' => $jetpack_old_version,
2261
			)
2262
		);
2263
2264
		Jetpack::state( 'message', 'modules_activated' );
2265
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2266
2267
		if ( $redirect ) {
2268
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2269
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2270
				$page = $_GET['page'];
2271
			}
2272
2273
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2274
			exit;
2275
		}
2276
	}
2277
2278
	/**
2279
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2280
	 * Make sure to tuck away module "library" files in a sub-directory.
2281
	 */
2282
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2283
		static $modules = null;
2284
2285
		if ( ! isset( $modules ) ) {
2286
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2287
			// Use the cache if we're on the front-end and it's available...
2288
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2289
				$modules = $available_modules_option[ JETPACK__VERSION ];
2290
			} else {
2291
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2292
2293
				$modules = array();
2294
2295
				foreach ( $files as $file ) {
2296
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2297
						continue;
2298
					}
2299
2300
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2301
				}
2302
2303
				Jetpack_Options::update_option( 'available_modules', array(
2304
					JETPACK__VERSION => $modules,
2305
				) );
2306
			}
2307
		}
2308
2309
		/**
2310
		 * Filters the array of modules available to be activated.
2311
		 *
2312
		 * @since 2.4.0
2313
		 *
2314
		 * @param array $modules Array of available modules.
2315
		 * @param string $min_version Minimum version number required to use modules.
2316
		 * @param string $max_version Maximum version number required to use modules.
2317
		 */
2318
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2319
2320
		if ( ! $min_version && ! $max_version ) {
2321
			return array_keys( $mods );
2322
		}
2323
2324
		$r = array();
2325
		foreach ( $mods as $slug => $introduced ) {
2326
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2327
				continue;
2328
			}
2329
2330
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2331
				continue;
2332
			}
2333
2334
			$r[] = $slug;
2335
		}
2336
2337
		return $r;
2338
	}
2339
2340
	/**
2341
	 * Default modules loaded on activation.
2342
	 */
2343
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2344
		$return = array();
2345
2346
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2347
			$module_data = Jetpack::get_module( $module );
2348
2349
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2350
				case 'yes' :
2351
					$return[] = $module;
2352
					break;
2353
				case 'public' :
2354
					if ( Jetpack_Options::get_option( 'public' ) ) {
2355
						$return[] = $module;
2356
					}
2357
					break;
2358
				case 'no' :
2359
				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...
2360
					break;
2361
			}
2362
		}
2363
		/**
2364
		 * Filters the array of default modules.
2365
		 *
2366
		 * @since 2.5.0
2367
		 *
2368
		 * @param array $return Array of default modules.
2369
		 * @param string $min_version Minimum version number required to use modules.
2370
		 * @param string $max_version Maximum version number required to use modules.
2371
		 */
2372
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2373
	}
2374
2375
	/**
2376
	 * Checks activated modules during auto-activation to determine
2377
	 * if any of those modules are being deprecated.  If so, close
2378
	 * them out, and add any replacement modules.
2379
	 *
2380
	 * Runs at priority 99 by default.
2381
	 *
2382
	 * This is run late, so that it can still activate a module if
2383
	 * the new module is a replacement for another that the user
2384
	 * currently has active, even if something at the normal priority
2385
	 * would kibosh everything.
2386
	 *
2387
	 * @since 2.6
2388
	 * @uses jetpack_get_default_modules filter
2389
	 * @param array $modules
2390
	 * @return array
2391
	 */
2392
	function handle_deprecated_modules( $modules ) {
2393
		$deprecated_modules = array(
2394
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2395
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2396
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2397
		);
2398
2399
		// Don't activate SSO if they never completed activating WPCC.
2400
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2401
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2402
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2403
				$deprecated_modules['wpcc'] = null;
2404
			}
2405
		}
2406
2407
		foreach ( $deprecated_modules as $module => $replacement ) {
2408
			if ( Jetpack::is_module_active( $module ) ) {
2409
				self::deactivate_module( $module );
2410
				if ( $replacement ) {
2411
					$modules[] = $replacement;
2412
				}
2413
			}
2414
		}
2415
2416
		return array_unique( $modules );
2417
	}
2418
2419
	/**
2420
	 * Checks activated plugins during auto-activation to determine
2421
	 * if any of those plugins are in the list with a corresponding module
2422
	 * that is not compatible with the plugin. The module will not be allowed
2423
	 * to auto-activate.
2424
	 *
2425
	 * @since 2.6
2426
	 * @uses jetpack_get_default_modules filter
2427
	 * @param array $modules
2428
	 * @return array
2429
	 */
2430
	function filter_default_modules( $modules ) {
2431
2432
		$active_plugins = self::get_active_plugins();
2433
2434
		if ( ! empty( $active_plugins ) ) {
2435
2436
			// For each module we'd like to auto-activate...
2437
			foreach ( $modules as $key => $module ) {
2438
				// If there are potential conflicts for it...
2439
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2440
					// For each potential conflict...
2441
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2442
						// If that conflicting plugin is active...
2443
						if ( in_array( $plugin, $active_plugins ) ) {
2444
							// Remove that item from being auto-activated.
2445
							unset( $modules[ $key ] );
2446
						}
2447
					}
2448
				}
2449
			}
2450
		}
2451
2452
		return $modules;
2453
	}
2454
2455
	/**
2456
	 * Extract a module's slug from its full path.
2457
	 */
2458
	public static function get_module_slug( $file ) {
2459
		return str_replace( '.php', '', basename( $file ) );
2460
	}
2461
2462
	/**
2463
	 * Generate a module's path from its slug.
2464
	 */
2465
	public static function get_module_path( $slug ) {
2466
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2467
	}
2468
2469
	/**
2470
	 * Load module data from module file. Headers differ from WordPress
2471
	 * plugin headers to avoid them being identified as standalone
2472
	 * plugins on the WordPress plugins page.
2473
	 */
2474
	public static function get_module( $module ) {
2475
		$headers = array(
2476
			'name'                      => 'Module Name',
2477
			'description'               => 'Module Description',
2478
			'jumpstart_desc'            => 'Jumpstart Description',
2479
			'sort'                      => 'Sort Order',
2480
			'recommendation_order'      => 'Recommendation Order',
2481
			'introduced'                => 'First Introduced',
2482
			'changed'                   => 'Major Changes In',
2483
			'deactivate'                => 'Deactivate',
2484
			'free'                      => 'Free',
2485
			'requires_connection'       => 'Requires Connection',
2486
			'auto_activate'             => 'Auto Activate',
2487
			'module_tags'               => 'Module Tags',
2488
			'feature'                   => 'Feature',
2489
			'additional_search_queries' => 'Additional Search Queries',
2490
		);
2491
2492
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2493
2494
		$mod = Jetpack::get_file_data( $file, $headers );
2495
		if ( empty( $mod['name'] ) ) {
2496
			return false;
2497
		}
2498
2499
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2500
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2501
		$mod['deactivate']              = empty( $mod['deactivate'] );
2502
		$mod['free']                    = empty( $mod['free'] );
2503
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2504
2505
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2506
			$mod['auto_activate'] = 'No';
2507
		} else {
2508
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2509
		}
2510
2511
		if ( $mod['module_tags'] ) {
2512
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2513
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2514
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2515
		} else {
2516
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2517
		}
2518
2519
		if ( $mod['feature'] ) {
2520
			$mod['feature'] = explode( ',', $mod['feature'] );
2521
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2522
		} else {
2523
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2524
		}
2525
2526
		/**
2527
		 * Filters the feature array on a module.
2528
		 *
2529
		 * This filter allows you to control where each module is filtered: Recommended,
2530
		 * Jumpstart, and the default "Other" listing.
2531
		 *
2532
		 * @since 3.5.0
2533
		 *
2534
		 * @param array   $mod['feature'] The areas to feature this module:
2535
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2536
		 *     'Recommended' shows on the main Jetpack admin screen.
2537
		 *     'Other' should be the default if no other value is in the array.
2538
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2539
		 * @param array   $mod All the currently assembled module data.
2540
		 */
2541
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2542
2543
		/**
2544
		 * Filter the returned data about a module.
2545
		 *
2546
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2547
		 * so please be careful.
2548
		 *
2549
		 * @since 3.6.0
2550
		 *
2551
		 * @param array   $mod    The details of the requested module.
2552
		 * @param string  $module The slug of the module, e.g. sharedaddy
2553
		 * @param string  $file   The path to the module source file.
2554
		 */
2555
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2556
	}
2557
2558
	/**
2559
	 * Like core's get_file_data implementation, but caches the result.
2560
	 */
2561
	public static function get_file_data( $file, $headers ) {
2562
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2563
		$file_name = basename( $file );
2564
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2565
		$key              = md5( $file_name . serialize( $headers ) );
2566
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2567
2568
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2569
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2570
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2571
		}
2572
2573
		$data = get_file_data( $file, $headers );
2574
2575
		// Strip out any old Jetpack versions that are cluttering the option.
2576
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2577
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2578
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2579
2580
		return $data;
2581
	}
2582
2583
	/**
2584
	 * Return translated module tag.
2585
	 *
2586
	 * @param string $tag Tag as it appears in each module heading.
2587
	 *
2588
	 * @return mixed
2589
	 */
2590
	public static function translate_module_tag( $tag ) {
2591
		return jetpack_get_module_i18n_tag( $tag );
2592
	}
2593
2594
	/**
2595
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2596
	 *
2597
	 * @since 3.9.2
2598
	 *
2599
	 * @param array $modules
2600
	 *
2601
	 * @return string|void
2602
	 */
2603
	public static function get_translated_modules( $modules ) {
2604
		foreach ( $modules as $index => $module ) {
2605
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2606
			if ( isset( $module['name'] ) ) {
2607
				$modules[ $index ]['name'] = $i18n_module['name'];
2608
			}
2609
			if ( isset( $module['description'] ) ) {
2610
				$modules[ $index ]['description'] = $i18n_module['description'];
2611
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2612
			}
2613
		}
2614
		return $modules;
2615
	}
2616
2617
	/**
2618
	 * Get a list of activated modules as an array of module slugs.
2619
	 */
2620
	public static function get_active_modules() {
2621
		$active = Jetpack_Options::get_option( 'active_modules' );
2622
		if ( ! is_array( $active ) )
2623
			$active = array();
2624
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2625
			$active[] = 'vaultpress';
2626
		} else {
2627
			$active = array_diff( $active, array( 'vaultpress' ) );
2628
		}
2629
2630
		//If protect is active on the main site of a multisite, it should be active on all sites.
2631
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2632
			$active[] = 'protect';
2633
		}
2634
2635
		return array_unique( $active );
2636
	}
2637
2638
	/**
2639
	 * Check whether or not a Jetpack module is active.
2640
	 *
2641
	 * @param string $module The slug of a Jetpack module.
2642
	 * @return bool
2643
	 *
2644
	 * @static
2645
	 */
2646
	public static function is_module_active( $module ) {
2647
		return in_array( $module, self::get_active_modules() );
2648
	}
2649
2650
	public static function is_module( $module ) {
2651
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2652
	}
2653
2654
	/**
2655
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2656
	 *
2657
	 * @param bool $catch True to start catching, False to stop.
2658
	 *
2659
	 * @static
2660
	 */
2661
	public static function catch_errors( $catch ) {
2662
		static $display_errors, $error_reporting;
2663
2664
		if ( $catch ) {
2665
			$display_errors  = @ini_set( 'display_errors', 1 );
2666
			$error_reporting = @error_reporting( E_ALL );
2667
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2668
		} else {
2669
			@ini_set( 'display_errors', $display_errors );
2670
			@error_reporting( $error_reporting );
2671
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2672
		}
2673
	}
2674
2675
	/**
2676
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2677
	 */
2678
	public static function catch_errors_on_shutdown() {
2679
		Jetpack::state( 'php_errors', ob_get_clean() );
2680
	}
2681
2682
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2683
		$jetpack = Jetpack::init();
2684
2685
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2686
		$modules = array_merge( $other_modules, $modules );
2687
2688
		// Look for standalone plugins and disable if active.
2689
2690
		$to_deactivate = array();
2691
		foreach ( $modules as $module ) {
2692
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2693
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2694
			}
2695
		}
2696
2697
		$deactivated = array();
2698
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2699
			list( $probable_file, $probable_title ) = $deactivate_me;
2700
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2701
				$deactivated[] = $module;
2702
			}
2703
		}
2704
2705
		if ( $deactivated && $redirect ) {
2706
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2707
2708
			$url = add_query_arg(
2709
				array(
2710
					'action'   => 'activate_default_modules',
2711
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2712
				),
2713
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2714
			);
2715
			wp_safe_redirect( $url );
2716
			exit;
2717
		}
2718
2719
		/**
2720
		 * Fires before default modules are activated.
2721
		 *
2722
		 * @since 1.9.0
2723
		 *
2724
		 * @param string $min_version Minimum version number required to use modules.
2725
		 * @param string $max_version Maximum version number required to use modules.
2726
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2727
		 */
2728
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2729
2730
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2731
		Jetpack::restate();
2732
		Jetpack::catch_errors( true );
2733
2734
		$active = Jetpack::get_active_modules();
2735
2736
		foreach ( $modules as $module ) {
2737
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2738
				$active[] = $module;
2739
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2740
				continue;
2741
			}
2742
2743
			if ( in_array( $module, $active ) ) {
2744
				$module_info = Jetpack::get_module( $module );
2745
				if ( ! $module_info['deactivate'] ) {
2746
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2747 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2748
						$active_state = explode( ',', $active_state );
2749
					} else {
2750
						$active_state = array();
2751
					}
2752
					$active_state[] = $module;
2753
					Jetpack::state( $state, implode( ',', $active_state ) );
2754
				}
2755
				continue;
2756
			}
2757
2758
			$file = Jetpack::get_module_path( $module );
2759
			if ( ! file_exists( $file ) ) {
2760
				continue;
2761
			}
2762
2763
			// we'll override this later if the plugin can be included without fatal error
2764
			if ( $redirect ) {
2765
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2766
			}
2767
			Jetpack::state( 'error', 'module_activation_failed' );
2768
			Jetpack::state( 'module', $module );
2769
			ob_start();
2770
			require $file;
2771
			/**
2772
			 * Fires when a specific module is activated.
2773
			 *
2774
			 * @since 1.9.0
2775
			 *
2776
			 * @param string $module Module slug.
2777
			 */
2778
			do_action( 'jetpack_activate_module', $module );
2779
			$active[] = $module;
2780
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2781 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2782
				$active_state = explode( ',', $active_state );
2783
			} else {
2784
				$active_state = array();
2785
			}
2786
			$active_state[] = $module;
2787
			Jetpack::state( $state, implode( ',', $active_state ) );
2788
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2789
			ob_end_clean();
2790
		}
2791
		Jetpack::state( 'error', false );
2792
		Jetpack::state( 'module', false );
2793
		Jetpack::catch_errors( false );
2794
		/**
2795
		 * Fires when default modules are activated.
2796
		 *
2797
		 * @since 1.9.0
2798
		 *
2799
		 * @param string $min_version Minimum version number required to use modules.
2800
		 * @param string $max_version Maximum version number required to use modules.
2801
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2802
		 */
2803
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2804
	}
2805
2806
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2807
		/**
2808
		 * Fires before a module is activated.
2809
		 *
2810
		 * @since 2.6.0
2811
		 *
2812
		 * @param string $module Module slug.
2813
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2814
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2815
		 */
2816
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2817
2818
		$jetpack = Jetpack::init();
2819
2820
		if ( ! strlen( $module ) )
2821
			return false;
2822
2823
		if ( ! Jetpack::is_module( $module ) )
2824
			return false;
2825
2826
		// If it's already active, then don't do it again
2827
		$active = Jetpack::get_active_modules();
2828
		foreach ( $active as $act ) {
2829
			if ( $act == $module )
2830
				return true;
2831
		}
2832
2833
		$module_data = Jetpack::get_module( $module );
2834
2835
		if ( ! Jetpack::is_active() ) {
2836
			if ( !Jetpack::is_development_mode() )
2837
				return false;
2838
2839
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2840
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2841
				return false;
2842
		}
2843
2844
		// Check and see if the old plugin is active
2845
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2846
			// Deactivate the old plugin
2847
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2848
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2849
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2850
				Jetpack::state( 'deactivated_plugins', $module );
2851
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2852
				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...
2853
			}
2854
		}
2855
2856
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2857
		Jetpack::state( 'module', $module );
2858
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2859
2860
		Jetpack::catch_errors( true );
2861
		ob_start();
2862
		require Jetpack::get_module_path( $module );
2863
		/** This action is documented in class.jetpack.php */
2864
		do_action( 'jetpack_activate_module', $module );
2865
		$active[] = $module;
2866
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2867
		Jetpack::state( 'error', false ); // the override
2868
		Jetpack::state( 'message', 'module_activated' );
2869
		Jetpack::state( 'module', $module );
2870
		ob_end_clean();
2871
		Jetpack::catch_errors( false );
2872
2873
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2874 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2875
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2876
2877
			//Jump start is being dismissed send data to MC Stats
2878
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2879
2880
			$jetpack->do_stats( 'server_side' );
2881
		}
2882
2883
		if ( $redirect ) {
2884
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2885
		}
2886
		if ( $exit ) {
2887
			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...
2888
		}
2889
		return true;
2890
	}
2891
2892
	function activate_module_actions( $module ) {
2893
		/**
2894
		 * Fires when a module is activated.
2895
		 * The dynamic part of the filter, $module, is the module slug.
2896
		 *
2897
		 * @since 1.9.0
2898
		 *
2899
		 * @param string $module Module slug.
2900
		 */
2901
		do_action( "jetpack_activate_module_$module", $module );
2902
2903
		$this->sync->sync_all_module_options( $module );
2904
	}
2905
2906
	public static function deactivate_module( $module ) {
2907
		/**
2908
		 * Fires when a module is deactivated.
2909
		 *
2910
		 * @since 1.9.0
2911
		 *
2912
		 * @param string $module Module slug.
2913
		 */
2914
		do_action( 'jetpack_pre_deactivate_module', $module );
2915
2916
		$jetpack = Jetpack::init();
2917
2918
		$active = Jetpack::get_active_modules();
2919
		$new    = array_filter( array_diff( $active, (array) $module ) );
2920
2921
		/**
2922
		 * Fires when a module is deactivated.
2923
		 * The dynamic part of the filter, $module, is the module slug.
2924
		 *
2925
		 * @since 1.9.0
2926
		 *
2927
		 * @param string $module Module slug.
2928
		 */
2929
		do_action( "jetpack_deactivate_module_$module", $module );
2930
2931
		// A flag for Jump Start so it's not shown again.
2932 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2933
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2934
2935
			//Jump start is being dismissed send data to MC Stats
2936
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2937
2938
			$jetpack->do_stats( 'server_side' );
2939
		}
2940
2941
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2942
	}
2943
2944
	public static function enable_module_configurable( $module ) {
2945
		$module = Jetpack::get_module_slug( $module );
2946
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2947
	}
2948
2949
	public static function module_configuration_url( $module ) {
2950
		$module = Jetpack::get_module_slug( $module );
2951
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2952
	}
2953
2954
	public static function module_configuration_load( $module, $method ) {
2955
		$module = Jetpack::get_module_slug( $module );
2956
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2957
	}
2958
2959
	public static function module_configuration_head( $module, $method ) {
2960
		$module = Jetpack::get_module_slug( $module );
2961
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2962
	}
2963
2964
	public static function module_configuration_screen( $module, $method ) {
2965
		$module = Jetpack::get_module_slug( $module );
2966
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2967
	}
2968
2969
	public static function module_configuration_activation_screen( $module, $method ) {
2970
		$module = Jetpack::get_module_slug( $module );
2971
		add_action( 'display_activate_module_setting_' . $module, $method );
2972
	}
2973
2974
/* Installation */
2975
2976
	public static function bail_on_activation( $message, $deactivate = true ) {
2977
?>
2978
<!doctype html>
2979
<html>
2980
<head>
2981
<meta charset="<?php bloginfo( 'charset' ); ?>">
2982
<style>
2983
* {
2984
	text-align: center;
2985
	margin: 0;
2986
	padding: 0;
2987
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2988
}
2989
p {
2990
	margin-top: 1em;
2991
	font-size: 18px;
2992
}
2993
</style>
2994
<body>
2995
<p><?php echo esc_html( $message ); ?></p>
2996
</body>
2997
</html>
2998
<?php
2999
		if ( $deactivate ) {
3000
			$plugins = get_option( 'active_plugins' );
3001
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3002
			$update  = false;
3003
			foreach ( $plugins as $i => $plugin ) {
3004
				if ( $plugin === $jetpack ) {
3005
					$plugins[$i] = false;
3006
					$update = true;
3007
				}
3008
			}
3009
3010
			if ( $update ) {
3011
				update_option( 'active_plugins', array_filter( $plugins ) );
3012
			}
3013
		}
3014
		exit;
3015
	}
3016
3017
	/**
3018
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3019
	 * @static
3020
	 */
3021
	public static function plugin_activation( $network_wide ) {
3022
		Jetpack_Options::update_option( 'activated', 1 );
3023
3024
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3025
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3026
		}
3027
3028
		if ( $network_wide )
3029
			Jetpack::state( 'network_nag', true );
3030
3031
		Jetpack::plugin_initialize();
3032
	}
3033
	/**
3034
	 * Runs before bumping version numbers up to a new version
3035
	 * @param  (string) $version    Version:timestamp
3036
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
3037
	 * @return null              [description]
3038
	 */
3039
	public static function do_version_bump( $version, $old_version ) {
3040
3041
		if ( ! $old_version ) { // For new sites
3042
			// Setting up jetpack manage
3043
			Jetpack::activate_manage();
3044
		}
3045
	}
3046
3047
	/**
3048
	 * Sets the internal version number and activation state.
3049
	 * @static
3050
	 */
3051
	public static function plugin_initialize() {
3052
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3053
			Jetpack_Options::update_option( 'activated', 2 );
3054
		}
3055
3056 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3057
			$version = $old_version = JETPACK__VERSION . ':' . time();
3058
			/** This action is documented in class.jetpack.php */
3059
			do_action( 'updating_jetpack_version', $version, false );
3060
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3061
		}
3062
3063
		Jetpack::load_modules();
3064
3065
		Jetpack_Options::delete_option( 'do_activate' );
3066
	}
3067
3068
	/**
3069
	 * Removes all connection options
3070
	 * @static
3071
	 */
3072
	public static function plugin_deactivation( ) {
3073
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3074
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3075
			Jetpack_Network::init()->deactivate();
3076
		} else {
3077
			Jetpack::disconnect( false );
3078
			//Jetpack_Heartbeat::init()->deactivate();
3079
		}
3080
	}
3081
3082
	/**
3083
	 * Disconnects from the Jetpack servers.
3084
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3085
	 * @static
3086
	 */
3087
	public static function disconnect( $update_activated_state = true ) {
3088
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3089
		Jetpack::clean_nonces( true );
3090
3091
		Jetpack::load_xml_rpc_client();
3092
		$xml = new Jetpack_IXR_Client();
3093
		$xml->query( 'jetpack.deregister' );
3094
3095
		Jetpack_Options::delete_option(
3096
			array(
3097
				'register',
3098
				'blog_token',
3099
				'user_token',
3100
				'user_tokens',
3101
				'master_user',
3102
				'time_diff',
3103
				'fallback_no_verify_ssl_certs',
3104
			)
3105
		);
3106
3107
		if ( $update_activated_state ) {
3108
			Jetpack_Options::update_option( 'activated', 4 );
3109
		}
3110
3111
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
3112
		// Check then record unique disconnection if site has never been disconnected previously
3113
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
3114
			$jetpack_unique_connection['disconnected'] = 1;
3115
		}
3116
		else {
3117
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3118
				//track unique disconnect
3119
				$jetpack = Jetpack::init();
3120
3121
				$jetpack->stat( 'connections', 'unique-disconnect' );
3122
				$jetpack->do_stats( 'server_side' );
3123
			}
3124
			// increment number of times disconnected
3125
			$jetpack_unique_connection['disconnected'] += 1;
3126
		}
3127
3128
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3129
3130
		// Disable the Heartbeat cron
3131
		Jetpack_Heartbeat::init()->deactivate();
3132
	}
3133
3134
	/**
3135
	 * Unlinks the current user from the linked WordPress.com user
3136
	 */
3137
	public static function unlink_user( $user_id = null ) {
3138
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3139
			return false;
3140
3141
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3142
3143
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3144
			return false;
3145
3146
		if ( ! isset( $tokens[ $user_id ] ) )
3147
			return false;
3148
3149
		Jetpack::load_xml_rpc_client();
3150
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3151
		$xml->query( 'jetpack.unlink_user', $user_id );
3152
3153
		unset( $tokens[ $user_id ] );
3154
3155
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3156
3157
		return true;
3158
	}
3159
3160
	/**
3161
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3162
	 */
3163
	public static function try_registration() {
3164
		// Let's get some testing in beta versions and such.
3165
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3166
			// Before attempting to connect, let's make sure that the domains are viable.
3167
			$domains_to_check = array_unique( array(
3168
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3169
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3170
			) );
3171
			foreach ( $domains_to_check as $domain ) {
3172
				$result = Jetpack_Data::is_usable_domain( $domain );
3173
				if ( is_wp_error( $result ) ) {
3174
					return $result;
3175
				}
3176
			}
3177
		}
3178
3179
		$result = Jetpack::register();
3180
3181
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3182
		if ( ! $result || is_wp_error( $result ) ) {
3183
			return $result;
3184
		} else {
3185
			return true;
3186
		}
3187
	}
3188
3189
	/**
3190
	 * Tracking an internal event log. Try not to put too much chaff in here.
3191
	 *
3192
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3193
	 */
3194
	public static function log( $code, $data = null ) {
3195
		// only grab the latest 200 entries
3196
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3197
3198
		// Append our event to the log
3199
		$log_entry = array(
3200
			'time'    => time(),
3201
			'user_id' => get_current_user_id(),
3202
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3203
			'code'    => $code,
3204
		);
3205
		// Don't bother storing it unless we've got some.
3206
		if ( ! is_null( $data ) ) {
3207
			$log_entry['data'] = $data;
3208
		}
3209
		$log[] = $log_entry;
3210
3211
		// Try add_option first, to make sure it's not autoloaded.
3212
		// @todo: Add an add_option method to Jetpack_Options
3213
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3214
			Jetpack_Options::update_option( 'log', $log );
3215
		}
3216
3217
		/**
3218
		 * Fires when Jetpack logs an internal event.
3219
		 *
3220
		 * @since 3.0.0
3221
		 *
3222
		 * @param array $log_entry {
3223
		 *	Array of details about the log entry.
3224
		 *
3225
		 *	@param string time Time of the event.
3226
		 *	@param int user_id ID of the user who trigerred the event.
3227
		 *	@param int blog_id Jetpack Blog ID.
3228
		 *	@param string code Unique name for the event.
3229
		 *	@param string data Data about the event.
3230
		 * }
3231
		 */
3232
		do_action( 'jetpack_log_entry', $log_entry );
3233
	}
3234
3235
	/**
3236
	 * Get the internal event log.
3237
	 *
3238
	 * @param $event (string) - only return the specific log events
3239
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3240
	 *
3241
	 * @return array of log events || WP_Error for invalid params
3242
	 */
3243
	public static function get_log( $event = false, $num = false ) {
3244
		if ( $event && ! is_string( $event ) ) {
3245
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3246
		}
3247
3248
		if ( $num && ! is_numeric( $num ) ) {
3249
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3250
		}
3251
3252
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3253
3254
		// If nothing set - act as it did before, otherwise let's start customizing the output
3255
		if ( ! $num && ! $event ) {
3256
			return $entire_log;
3257
		} else {
3258
			$entire_log = array_reverse( $entire_log );
3259
		}
3260
3261
		$custom_log_output = array();
3262
3263
		if ( $event ) {
3264
			foreach ( $entire_log as $log_event ) {
3265
				if ( $event == $log_event[ 'code' ] ) {
3266
					$custom_log_output[] = $log_event;
3267
				}
3268
			}
3269
		} else {
3270
			$custom_log_output = $entire_log;
3271
		}
3272
3273
		if ( $num ) {
3274
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3275
		}
3276
3277
		return $custom_log_output;
3278
	}
3279
3280
	/**
3281
	 * Log modification of important settings.
3282
	 */
3283
	public static function log_settings_change( $option, $old_value, $value ) {
3284
		switch( $option ) {
3285
			case 'jetpack_sync_non_public_post_stati':
3286
				self::log( $option, $value );
3287
				break;
3288
		}
3289
	}
3290
3291
	/**
3292
	 * Return stat data for WPCOM sync
3293
	 */
3294
	function get_stat_data() {
3295
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3296
		$additional_data = $this->get_additional_stat_data();
3297
3298
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3299
	}
3300
3301
	/**
3302
	 * Get additional stat data to sync to WPCOM
3303
	 */
3304
	function get_additional_stat_data( $prefix = '' ) {
3305
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3306
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3307
		$return["{$prefix}users"]          = count_users();
3308
		$return["{$prefix}site-count"]     = 0;
3309
		if ( function_exists( 'get_blog_count' ) ) {
3310
			$return["{$prefix}site-count"] = get_blog_count();
3311
		}
3312
		return $return;
3313
	}
3314
3315
	/* Admin Pages */
3316
3317
	function admin_init() {
3318
		// If the plugin is not connected, display a connect message.
3319
		if (
3320
			// the plugin was auto-activated and needs its candy
3321
			Jetpack_Options::get_option( 'do_activate' )
3322
		||
3323
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3324
			! Jetpack_Options::get_option( 'activated' )
3325
		) {
3326
			Jetpack::plugin_initialize();
3327
		}
3328
3329
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3330
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3331
				// Show connect notice on dashboard and plugins pages
3332
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3333
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3334
			}
3335
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3336
			// Upgrade: 1.1 -> 1.1.1
3337
			// Check and see if host can verify the Jetpack servers' SSL certificate
3338
			$args = array();
3339
			Jetpack_Client::_wp_remote_request(
3340
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3341
				$args,
3342
				true
3343
			);
3344
		} else {
3345
			// Show the notice on the Dashboard only for now
3346
3347
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3348
3349
			// Identity crisis notices
3350
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3351
		}
3352
3353
		// If the plugin has just been disconnected from WP.com, show the survey notice
3354
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3355
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3356
		}
3357
3358
		if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3359
			add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
3360
		}
3361
3362
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3363
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3364
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3365
3366
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3367
			// Artificially throw errors in certain whitelisted cases during plugin activation
3368
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3369
3370
			// Kick off synchronization of user role when it changes
3371
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3372
		}
3373
3374
		// Jetpack Manage Activation Screen from .com
3375
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3376
	}
3377
3378
	function admin_body_class( $admin_body_class = '' ) {
3379
		$classes = explode( ' ', trim( $admin_body_class ) );
3380
3381
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3382
3383
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3384
		return " $admin_body_class ";
3385
	}
3386
3387
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3388
		return $admin_body_class . ' jetpack-pagestyles ';
3389
	}
3390
3391
	function prepare_connect_notice() {
3392
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3393
3394
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3395
3396
		if ( Jetpack::state( 'network_nag' ) )
3397
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3398
	}
3399
	/**
3400
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3401
	 *
3402
	 * @return null
3403
	 */
3404
	function prepare_manage_jetpack_notice() {
3405
3406
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3407
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3408
	}
3409
3410
	function manage_activate_screen() {
3411
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3412
	}
3413
	/**
3414
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3415
	 * This function artificially throws errors for such cases (whitelisted).
3416
	 *
3417
	 * @param string $plugin The activated plugin.
3418
	 */
3419
	function throw_error_on_activate_plugin( $plugin ) {
3420
		$active_modules = Jetpack::get_active_modules();
3421
3422
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3423
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3424
			$throw = false;
3425
3426
			// Try and make sure it really was the stats plugin
3427
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3428
				if ( 'stats.php' == basename( $plugin ) ) {
3429
					$throw = true;
3430
				}
3431
			} else {
3432
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3433
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3434
					$throw = true;
3435
				}
3436
			}
3437
3438
			if ( $throw ) {
3439
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3440
			}
3441
		}
3442
	}
3443
3444
	function intercept_plugin_error_scrape_init() {
3445
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3446
	}
3447
3448
	function intercept_plugin_error_scrape( $action, $result ) {
3449
		if ( ! $result ) {
3450
			return;
3451
		}
3452
3453
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3454
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3455
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3456
			}
3457
		}
3458
	}
3459
3460
	function add_remote_request_handlers() {
3461
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3462
	}
3463
3464
	function remote_request_handlers() {
3465
		switch ( current_filter() ) {
3466
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3467
			$response = $this->upload_handler();
3468
			break;
3469
		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...
3470
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3471
			break;
3472
		}
3473
3474
		if ( ! $response ) {
3475
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3476
		}
3477
3478
		if ( is_wp_error( $response ) ) {
3479
			$status_code       = $response->get_error_data();
3480
			$error             = $response->get_error_code();
3481
			$error_description = $response->get_error_message();
3482
3483
			if ( ! is_int( $status_code ) ) {
3484
				$status_code = 400;
3485
			}
3486
3487
			status_header( $status_code );
3488
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3489
		}
3490
3491
		status_header( 200 );
3492
		if ( true === $response ) {
3493
			exit;
3494
		}
3495
3496
		die( json_encode( (object) $response ) );
3497
	}
3498
3499
	function upload_handler() {
3500
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3501
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3502
		}
3503
3504
		$user = wp_authenticate( '', '' );
3505
		if ( ! $user || is_wp_error( $user ) ) {
3506
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3507
		}
3508
3509
		wp_set_current_user( $user->ID );
3510
3511
		if ( ! current_user_can( 'upload_files' ) ) {
3512
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3513
		}
3514
3515
		if ( empty( $_FILES ) ) {
3516
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3517
		}
3518
3519
		foreach ( array_keys( $_FILES ) as $files_key ) {
3520
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3521
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3522
			}
3523
		}
3524
3525
		$media_keys = array_keys( $_FILES['media'] );
3526
3527
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3528
		if ( ! $token || is_wp_error( $token ) ) {
3529
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3530
		}
3531
3532
		$uploaded_files = array();
3533
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3534
		unset( $GLOBALS['post'] );
3535
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3536
			$file = array();
3537
			foreach ( $media_keys as $media_key ) {
3538
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3539
			}
3540
3541
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3542
3543
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3544
			if ( $hmac_provided !== $hmac_file ) {
3545
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3546
				continue;
3547
			}
3548
3549
			$_FILES['.jetpack.upload.'] = $file;
3550
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3551
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3552
				$post_id = 0;
3553
			}
3554
			$attachment_id = media_handle_upload(
3555
				'.jetpack.upload.',
3556
				$post_id,
3557
				array(),
3558
				array(
3559
					'action' => 'jetpack_upload_file',
3560
				)
3561
			);
3562
3563
			if ( ! $attachment_id ) {
3564
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3565
			} elseif ( is_wp_error( $attachment_id ) ) {
3566
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3567
			} else {
3568
				$attachment = get_post( $attachment_id );
3569
				$uploaded_files[$index] = (object) array(
3570
					'id'   => (string) $attachment_id,
3571
					'file' => $attachment->post_title,
3572
					'url'  => wp_get_attachment_url( $attachment_id ),
3573
					'type' => $attachment->post_mime_type,
3574
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3575
				);
3576
			}
3577
		}
3578
		if ( ! is_null( $global_post ) ) {
3579
			$GLOBALS['post'] = $global_post;
3580
		}
3581
3582
		return $uploaded_files;
3583
	}
3584
3585
	/**
3586
	 * Add help to the Jetpack page
3587
	 *
3588
	 * @since Jetpack (1.2.3)
3589
	 * @return false if not the Jetpack page
3590
	 */
3591
	function admin_help() {
3592
		$current_screen = get_current_screen();
3593
3594
		// Overview
3595
		$current_screen->add_help_tab(
3596
			array(
3597
				'id'		=> 'home',
3598
				'title'		=> __( 'Home', 'jetpack' ),
3599
				'content'	=>
3600
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3601
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3602
					'<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>',
3603
			)
3604
		);
3605
3606
		// Screen Content
3607
		if ( current_user_can( 'manage_options' ) ) {
3608
			$current_screen->add_help_tab(
3609
				array(
3610
					'id'		=> 'settings',
3611
					'title'		=> __( 'Settings', 'jetpack' ),
3612
					'content'	=>
3613
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3614
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3615
						'<ol>' .
3616
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3617
							'<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>' .
3618
						'</ol>' .
3619
						'<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>'
3620
				)
3621
			);
3622
		}
3623
3624
		// Help Sidebar
3625
		$current_screen->set_help_sidebar(
3626
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3627
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3628
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3629
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3630
		);
3631
	}
3632
3633
	function admin_menu_css() {
3634
		wp_enqueue_style( 'jetpack-icons' );
3635
	}
3636
3637
	function admin_menu_order() {
3638
		return true;
3639
	}
3640
3641 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3642
		$jp_menu_order = array();
3643
3644
		foreach ( $menu_order as $index => $item ) {
3645
			if ( $item != 'jetpack' ) {
3646
				$jp_menu_order[] = $item;
3647
			}
3648
3649
			if ( $index == 0 ) {
3650
				$jp_menu_order[] = 'jetpack';
3651
			}
3652
		}
3653
3654
		return $jp_menu_order;
3655
	}
3656
3657
	function admin_head() {
3658 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3659
			/** This action is documented in class.jetpack-admin-page.php */
3660
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3661
	}
3662
3663
	function admin_banner_styles() {
3664
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3665
3666
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3667
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3668
		wp_style_add_data( 'jetpack', 'suffix', $min );
3669
	}
3670
3671
	function admin_scripts() {
3672
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3673
		wp_localize_script(
3674
			'jetpack-js',
3675
			'jetpackL10n',
3676
			array(
3677
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3678
				'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?",
3679
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3680
			)
3681
		);
3682
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3683
	}
3684
3685
	function plugin_action_links( $actions ) {
3686
3687
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3688
3689
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3690
			return array_merge(
3691
				$jetpack_home,
3692
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3693
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3694
				$actions
3695
				);
3696
			}
3697
3698
		return array_merge( $jetpack_home, $actions );
3699
	}
3700
3701
	function admin_connect_notice() {
3702
		// Don't show the connect notice anywhere but the plugins.php after activating
3703
		$current = get_current_screen();
3704
		if ( 'plugins' !== $current->parent_base )
3705
			return;
3706
3707
		if ( ! current_user_can( 'jetpack_connect' ) )
3708
			return;
3709
3710
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3711
		?>
3712
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3713
			<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>
3714
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3715
				<div class="jp-banner__content is-connection">
3716
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3717
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3718
				</div>
3719
				<div class="jp-banner__action-container is-connection">
3720
						<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>
3721
				</div>
3722 View Code Duplication
			<?php else : ?>
3723
				<div class="jp-banner__content">
3724
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3725
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3726
				</div>
3727
				<div class="jp-banner__action-container">
3728
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3729
				</div>
3730
			<?php endif; ?>
3731
		</div>
3732
3733
		<?php
3734
	}
3735
3736
	/**
3737
	 * This is the first banner
3738
	 * It should be visible only to user that can update the option
3739
	 * Are not connected
3740
	 *
3741
	 * @return null
3742
	 */
3743
	function admin_jetpack_manage_notice() {
3744
		$screen = get_current_screen();
3745
3746
		// Don't show the connect notice on the jetpack settings page.
3747
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3748
			return;
3749
3750
		// Only show it if don't have the managment option set.
3751
		// And not dismissed it already.
3752
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3753
			return;
3754
		}
3755
3756
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3757
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3758
		/**
3759
		 * I think it would be great to have different wordsing depending on where you are
3760
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3761
		 * etc..
3762
		 */
3763
3764
		?>
3765
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3766
			<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>
3767
			<div class="jp-banner__content">
3768
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3769
				<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>
3770
			</div>
3771
			<div class="jp-banner__action-container is-opt-in">
3772
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3773
			</div>
3774
		</div>
3775
		<?php
3776
	}
3777
3778
	/**
3779
	 * Returns the url that the user clicks to remove the notice for the big banner
3780
	 * @return (string)
3781
	 */
3782
	function opt_out_jetpack_manage_url() {
3783
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3784
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3785
	}
3786
	/**
3787
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3788
	 * @return (string)
3789
	 */
3790
	function opt_in_jetpack_manage_url() {
3791
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3792
	}
3793
3794
	function opt_in_jetpack_manage_notice() {
3795
		?>
3796
		<div class="wrap">
3797
			<div id="message" class="jetpack-message is-opt-in">
3798
				<?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' ); ?>
3799
			</div>
3800
		</div>
3801
		<?php
3802
3803
	}
3804
	/**
3805
	 * Determines whether to show the notice of not true = display notice
3806
	 * @return (bool)
3807
	 */
3808
	function can_display_jetpack_manage_notice() {
3809
		// never display the notice to users that can't do anything about it anyways
3810
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3811
			return false;
3812
3813
		// don't display if we are in development more
3814
		if( Jetpack::is_development_mode() ) {
3815
			return false;
3816
		}
3817
		// don't display if the site is private
3818
		if(  ! Jetpack_Options::get_option( 'public' ) )
3819
			return false;
3820
3821
		/**
3822
		 * Should the Jetpack Remote Site Management notice be displayed.
3823
		 *
3824
		 * @since 3.3.0
3825
		 *
3826
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3827
		 */
3828
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3829
	}
3830
3831
	function network_connect_notice() {
3832
		?>
3833
		<div id="message" class="updated jetpack-message">
3834
			<div class="squeezer">
3835
				<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>
3836
			</div>
3837
		</div>
3838
		<?php
3839
	}
3840
3841
	public static function jetpack_comment_notice() {
3842
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3843
			return '';
3844
		}
3845
3846
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3847
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3848
3849
		if ( $jetpack_old_version ) {
3850
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3851
				return '';
3852
			}
3853
		}
3854
3855
		if ( $jetpack_new_version ) {
3856
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3857
				return '';
3858
			}
3859
		}
3860
3861
		return '<br /><br />' . sprintf(
3862
			__( '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' ),
3863
			wp_nonce_url(
3864
				Jetpack::admin_url(
3865
					array(
3866
						'page'   => 'jetpack',
3867
						'action' => 'activate',
3868
						'module' => 'comments',
3869
					)
3870
				),
3871
				'jetpack_activate-comments'
3872
			),
3873
			__( 'click here', 'jetpack' )
3874
		);
3875
	}
3876
3877
	/**
3878
	 * Show the survey link when the user has just disconnected Jetpack.
3879
	 */
3880
	function disconnect_survey_notice() {
3881
		?>
3882
		<div class="wrap">
3883
			<div id="message" class="jetpack-message stay-visible">
3884
				<div class="squeezer">
3885
					<h2>
3886
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3887
						<br />
3888
						<?php echo sprintf(
3889
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3890
							'https://jetpack.com/survey-disconnected/',
3891
							'_blank'
3892
						); ?>
3893
					</h2>
3894
				</div>
3895
			</div>
3896
		</div>
3897
		<?php
3898
	}
3899
3900
	/*
3901
	 * Registration flow:
3902
	 * 1 - ::admin_page_load() action=register
3903
	 * 2 - ::try_registration()
3904
	 * 3 - ::register()
3905
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3906
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3907
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3908
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3909
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3910
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3911
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3912
	 *       jetpack_id, jetpack_secret, jetpack_public
3913
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3914
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3915
	 * 5 - user logs in with WP.com account
3916
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3917
	 *		- Jetpack_Client_Server::authorize()
3918
	 *		- Jetpack_Client_Server::get_token()
3919
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3920
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3921
	 *			- which responds with access_token, token_type, scope
3922
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3923
	 *		- Jetpack::activate_default_modules()
3924
	 *     		- Deactivates deprecated plugins
3925
	 *     		- Activates all default modules
3926
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3927
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3928
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3929
	 *     Done!
3930
	 */
3931
3932
	/**
3933
	 * Handles the page load events for the Jetpack admin page
3934
	 */
3935
	function admin_page_load() {
3936
		$error = false;
3937
3938
		// Make sure we have the right body class to hook stylings for subpages off of.
3939
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3940
3941
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3942
			// Should only be used in intermediate redirects to preserve state across redirects
3943
			Jetpack::restate();
3944
		}
3945
3946
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3947
			// User clicked in the iframe to link their accounts
3948
			if ( ! Jetpack::is_user_connected() ) {
3949
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3950
				if ( isset( $_GET['notes_iframe'] ) )
3951
					$connect_url .= '&notes_iframe';
3952
				wp_redirect( $connect_url );
3953
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3954
			} else {
3955
				Jetpack::state( 'message', 'already_authorized' );
3956
				wp_safe_redirect( Jetpack::admin_url() );
3957
				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...
3958
			}
3959
		}
3960
3961
3962
		if ( isset( $_GET['action'] ) ) {
3963
			switch ( $_GET['action'] ) {
3964
			case 'authorize':
3965
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3966
					Jetpack::state( 'message', 'already_authorized' );
3967
					wp_safe_redirect( Jetpack::admin_url() );
3968
					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...
3969
				}
3970
				Jetpack::log( 'authorize' );
3971
				$client_server = new Jetpack_Client_Server;
3972
				$client_server->client_authorize();
3973
				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...
3974
			case 'register' :
3975
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3976
					$error = 'cheatin';
3977
					break;
3978
				}
3979
				check_admin_referer( 'jetpack-register' );
3980
				Jetpack::log( 'register' );
3981
				Jetpack::maybe_set_version_option();
3982
				$registered = Jetpack::try_registration();
3983
				if ( is_wp_error( $registered ) ) {
3984
					$error = $registered->get_error_code();
3985
					Jetpack::state( 'error_description', $registered->get_error_message() );
3986
					break;
3987
				}
3988
				
3989
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3990
3991
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3992
				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...
3993
			case 'activate' :
3994
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3995
					$error = 'cheatin';
3996
					break;
3997
				}
3998
3999
				$module = stripslashes( $_GET['module'] );
4000
				check_admin_referer( "jetpack_activate-$module" );
4001
				Jetpack::log( 'activate', $module );
4002
				Jetpack::activate_module( $module );
4003
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4004
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4005
				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...
4006
			case 'activate_default_modules' :
4007
				check_admin_referer( 'activate_default_modules' );
4008
				Jetpack::log( 'activate_default_modules' );
4009
				Jetpack::restate();
4010
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4011
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4012
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4013
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4014
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4015
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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