Completed
Push — add/default-xmlrpc-method ( 13c4e0...3e83fe )
by
unknown
09:18
created

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

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

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

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

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

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

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

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