Completed
Push — remove/deprecated-upgrade-code ( 30dd2a )
by
unknown
26:39 queued 15:57
created

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

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

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

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