Completed
Push — fix/wpcontainer-styles ( f4d011 )
by
unknown
349:25 queued 339:33
created

class.jetpack.php (14 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
			self::$instance = new Jetpack;
311
312
			self::$instance->plugin_upgrade();
313
314
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
315
316
		}
317
318
		return self::$instance;
319
	}
320
321
	/**
322
	 * Must never be called statically
323
	 */
324
	function plugin_upgrade() {
325
		if ( Jetpack::is_active() ) {
326
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
327
			if ( JETPACK__VERSION != $version ) {
328
329
				// Check which active modules actually exist and remove others from active_modules list
330
				$unfiltered_modules = Jetpack::get_active_modules();
331
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
332
				if ( array_diff( $unfiltered_modules, $modules ) ) {
333
					Jetpack_Options::update_option( 'active_modules', $modules );
334
				}
335
336
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
337
				/**
338
				 * Fires when synchronizing all registered options and constants.
339
				 *
340
				 * @since 3.3.0
341
				 */
342
				do_action( 'jetpack_sync_all_registered_options' );
343
			}
344
		}
345
	}
346
347
	static function activate_manage( ) {
348
349
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
350
			self::activate_module( 'manage', false, false );
351
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
352
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
353
		}
354
355
	}
356
357
	/**
358
	 * Constructor.  Initializes WordPress hooks
359
	 */
360
	private function __construct() {
361
		/*
362
		 * Check for and alert any deprecated hooks
363
		 */
364
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
365
366
		/**
367
		 * We need sync object even in Multisite mode
368
		 */
369
		$this->sync = new Jetpack_Sync;
370
371
		/**
372
		 * Trigger a wp_version sync when updating WP versions
373
		 **/
374
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
375
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
376
377
		add_action( 'init', array( $this, 'sync_update_data') );
378
		add_action( 'init', array( $this, 'sync_theme_data' ) );
379
380
		/*
381
		 * Load things that should only be in Network Admin.
382
		 *
383
		 * For now blow away everything else until a more full
384
		 * understanding of what is needed at the network level is
385
		 * available
386
		 */
387
		if( is_multisite() ) {
388
			Jetpack_Network::init();
389
390
			// Only sync this info if we are on a multi site
391
			// @since  3.7
392
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
393
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
394
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
395
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
396
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
397
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
398
399
			if( is_network_admin() ) {
400
				// Sync network site data if it is updated or not.
401
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
402
				return; // End here to prevent single site actions from firing
403
			}
404
		}
405
406
407
		$theme_slug = get_option( 'stylesheet' );
408
409
410
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
411
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
412
		$this->sync->options(
413
			JETPACK__PLUGIN_DIR . 'jetpack.php',
414
			'home',
415
			'siteurl',
416
			'blogname',
417
			'gmt_offset',
418
			'timezone_string',
419
			'security_report',
420
			'stylesheet',
421
			"theme_mods_{$theme_slug}",
422
			'jetpack_sync_non_public_post_stati',
423
			'jetpack_options',
424
			'site_icon', // (int) - ID of core's Site Icon attachment ID
425
			'default_post_format',
426
			'default_category',
427
			'large_size_w',
428
			'large_size_h',
429
			'thumbnail_size_w',
430
			'thumbnail_size_h',
431
			'medium_size_w',
432
			'medium_size_h',
433
			'thumbnail_crop',
434
			'image_default_link_type'
435
		);
436
437
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
438
			$this->sync->options( __FILE__, 'jetpack_' . $option );
439
		}
440
441
		/**
442
		 * Sometimes you want to sync data to .com without adding options to .org sites.
443
		 * The mock option allows you to do just that.
444
		 */
445
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
446
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
447
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
448
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
449
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
450
451
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
452
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
453
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
454
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
455
456
		/**
457
		 * Trigger an update to the main_network_site when we update the blogname of a site.
458
		 *
459
		 */
460
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
461
462
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
463
464
		// Update the settings everytime the we register a new user to the site or we delete a user.
465
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
466
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
467
468
		// Unlink user before deleting the user from .com
469
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
470
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
471
472
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
473
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
474
475
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
476
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
477
478
			$this->require_jetpack_authentication();
479
480
			if ( Jetpack::is_active() ) {
481
				// Hack to preserve $HTTP_RAW_POST_DATA
482
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
483
484
				$signed = $this->verify_xml_rpc_signature();
485
				if ( $signed && ! is_wp_error( $signed ) ) {
486
					// The actual API methods.
487
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
488
				} else {
489
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
490
					// active Jetpack connection, so that additional users can link their account.
491
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
492
				}
493
			} else {
494
				// The bootstrap API methods.
495
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
496
			}
497
498
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
499
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
500
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
501
			$this->require_jetpack_authentication();
502
			$this->add_remote_request_handlers();
503
		} else {
504
			if ( Jetpack::is_active() ) {
505
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
506
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
507
			}
508
		}
509
510
		if ( Jetpack::is_active() ) {
511
			Jetpack_Heartbeat::init();
512
		}
513
514
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
515
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
516
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
517
		}
518
519
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
520
521
		add_action( 'admin_init', array( $this, 'admin_init' ) );
522
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
523
524
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
525
526
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
527
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
528
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
529
530
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
531
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
532
533
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
534
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
535
536
		// Identity Crisis AJAX callback function
537
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
538
539
		// JITM AJAX callback function
540
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
541
542
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
543
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
544
545
		// Universal ajax callback for all tracking events triggered via js
546
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
547
548
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
549
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
550
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
551
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
552
553
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
554
555
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
556
557
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
558
559
		/**
560
		 * These actions run checks to load additional files.
561
		 * They check for external files or plugins, so they need to run as late as possible.
562
		 */
563
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
564
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
565
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
566
567
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
568
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
569
570
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
571
572
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
573
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
574
575
		// A filter to control all just in time messages
576
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
577
578
		/**
579
		 * This is the hack to concatinate all css files into one.
580
		 * For description and reasoning see the implode_frontend_css method
581
		 *
582
		 * Super late priority so we catch all the registered styles
583
		 */
584
		if( !is_admin() ) {
585
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
586
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
587
		}
588
589
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
590
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
591
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
592
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
593
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
594
595
	}
596
597
	/*
598
	 * Make sure any site icon added to core can get
599
	 * synced back to dotcom, so we can display it there.
600
	 */
601
	function jetpack_sync_core_icon() {
602
		if ( function_exists( 'get_site_icon_url' ) ) {
603
			$url = get_site_icon_url();
604
		} else {
605
			return;
606
		}
607
608
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
609
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
610
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
611
			// This is the option that is synced with dotcom
612
			Jetpack_Options::update_option( 'site_icon_url', $url );
613
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
614
			Jetpack_Options::delete_option( 'site_icon_url' );
615
		}
616
	}
617
618
	function jetpack_admin_ajax_tracks_callback() {
619
		// Check for nonce
620
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
621
			wp_die( 'Permissions check failed.' );
622
		}
623
624
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
625
			wp_die( 'No valid event name or type.' );
626
		}
627
628
		$tracks_data = array();
629
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
630
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
631
		}
632
633
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
634
		wp_send_json_success();
635
		wp_die();
636
	}
637
638
	function jetpack_admin_ajax_callback() {
639
		// Check for nonce
640 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
641
			wp_die( 'permissions check failed' );
642
		}
643
644
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
645
			$slug = $_REQUEST['thisModuleSlug'];
646
647
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
648
				wp_die( 'That is not a Jetpack module slug' );
649
			}
650
651
			if ( Jetpack::is_module_active( $slug ) ) {
652
				Jetpack::deactivate_module( $slug );
653
			} else {
654
				Jetpack::activate_module( $slug, false, false );
655
			}
656
657
			$modules = Jetpack_Admin::init()->get_modules();
658
			echo json_encode( $modules[ $slug ] );
659
660
			exit;
661
		}
662
663
		wp_die();
664
	}
665
666
	/*
667
	 * Sometimes we need to refresh the data,
668
	 * especially if the page is visited via a 'history'
669
	 * event like back/forward
670
	 */
671
	function jetpack_admin_ajax_refresh_data() {
672
		// Check for nonce
673 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
674
			wp_die( 'permissions check failed' );
675
		}
676
677
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
678
			$modules = Jetpack_Admin::init()->get_modules();
679
			echo json_encode( $modules );
680
			exit;
681
		}
682
683
		wp_die();
684
	}
685
686
	/**
687
	 * The callback for the JITM ajax requests.
688
	 */
689
	function jetpack_jitm_ajax_callback() {
690
		// Check for nonce
691
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
692
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
693
		}
694
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
695
			$module_slug = $_REQUEST['jitmModule'];
696
			Jetpack::log( 'activate', $module_slug );
697
			Jetpack::activate_module( $module_slug, false, false );
698
			Jetpack::state( 'message', 'no_message' );
699
700
			//A Jetpack module is being activated through a JITM, track it
701
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
702
			$this->do_stats( 'server_side' );
703
704
			wp_send_json_success();
705
		}
706
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
707
			// get the hide_jitm options array
708
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
709
			$module_slug = $_REQUEST['jitmModule'];
710
711
			if( ! $jetpack_hide_jitm ) {
712
				$jetpack_hide_jitm = array(
713
					$module_slug => 'hide'
714
				);
715
			} else {
716
				$jetpack_hide_jitm[$module_slug] = 'hide';
717
			}
718
719
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
720
721
			//jitm is being dismissed forever, track it
722
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
723
			$this->do_stats( 'server_side' );
724
725
			wp_send_json_success();
726
		}
727 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
728
			$module_slug = $_REQUEST['jitmModule'];
729
730
			// User went to WordPress.com, track this
731
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
732
			$this->do_stats( 'server_side' );
733
734
			wp_send_json_success();
735
		}
736 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
737
			$track = $_REQUEST['jitmModule'];
738
739
			// User is viewing JITM, track it.
740
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
741
			$this->do_stats( 'server_side' );
742
743
			wp_send_json_success();
744
		}
745
	}
746
747
	/**
748
	 * If there are any stats that need to be pushed, but haven't been, push them now.
749
	 */
750
	function __destruct() {
751
		if ( ! empty( $this->stats ) ) {
752
			$this->do_stats( 'server_side' );
753
		}
754
	}
755
756
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
757
		switch( $cap ) {
758
			case 'jetpack_connect' :
759
			case 'jetpack_reconnect' :
760
				if ( Jetpack::is_development_mode() ) {
761
					$caps = array( 'do_not_allow' );
762
					break;
763
				}
764
				/**
765
				 * Pass through. If it's not development mode, these should match disconnect.
766
				 * Let users disconnect if it's development mode, just in case things glitch.
767
				 */
768
			case 'jetpack_disconnect' :
769
				/**
770
				 * In multisite, can individual site admins manage their own connection?
771
				 *
772
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
773
				 */
774
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
775
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
776
						/**
777
						 * We need to update the option name -- it's terribly unclear which
778
						 * direction the override goes.
779
						 *
780
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
781
						 */
782
						$caps = array( 'do_not_allow' );
783
						break;
784
					}
785
				}
786
787
				$caps = array( 'manage_options' );
788
				break;
789
			case 'jetpack_manage_modules' :
790
			case 'jetpack_activate_modules' :
791
			case 'jetpack_deactivate_modules' :
792
				$caps = array( 'manage_options' );
793
				break;
794
			case 'jetpack_configure_modules' :
795
				$caps = array( 'manage_options' );
796
				break;
797
			case 'jetpack_network_admin_page':
798
			case 'jetpack_network_settings_page':
799
				$caps = array( 'manage_network_plugins' );
800
				break;
801
			case 'jetpack_network_sites_page':
802
				$caps = array( 'manage_sites' );
803
				break;
804
			case 'jetpack_admin_page' :
805
				if ( Jetpack::is_development_mode() ) {
806
					$caps = array( 'manage_options' );
807
					break;
808
				} else {
809
					$caps = array( 'read' );
810
				}
811
				break;
812
			case 'jetpack_connect_user' :
813
				if ( Jetpack::is_development_mode() ) {
814
					$caps = array( 'do_not_allow' );
815
					break;
816
				}
817
				$caps = array( 'read' );
818
				break;
819
		}
820
		return $caps;
821
	}
822
823
	function require_jetpack_authentication() {
824
		// Don't let anyone authenticate
825
		$_COOKIE = array();
826
		remove_all_filters( 'authenticate' );
827
828
		/**
829
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
830
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
831
		 * generate false-positives.
832
		 */
833
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
834
835
		if ( Jetpack::is_active() ) {
836
			// Allow Jetpack authentication
837
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
838
		}
839
	}
840
841
	/**
842
	 * Load language files
843
	 * @action plugins_loaded
844
	 */
845
	public static function plugin_textdomain() {
846
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
847
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
848
	}
849
850
	/**
851
	 * Register assets for use in various modules and the Jetpack admin page.
852
	 *
853
	 * @uses wp_script_is, wp_register_script, plugins_url
854
	 * @action wp_loaded
855
	 * @return null
856
	 */
857
	public function register_assets() {
858
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
859
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
860
		}
861
862 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
863
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
864
		}
865
866 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
867
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
868
		}
869
870 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
871
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
872
		}
873
874
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
875
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
876
877
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
878
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
879
			if ( ! is_numeric( $fb_app_id ) ) {
880
				$fb_app_id = '';
881
			}
882
			wp_localize_script(
883
				'jetpack-facebook-embed',
884
				'jpfbembed',
885
				array(
886
					'appid' => $fb_app_id,
887
					'locale' => $this->get_locale(),
888
				)
889
			);
890
		}
891
892
		/**
893
		 * As jetpack_register_genericons is by default fired off a hook,
894
		 * the hook may have already fired by this point.
895
		 * So, let's just trigger it manually.
896
		 */
897
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
898
		jetpack_register_genericons();
899
900 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
901
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
902
	}
903
904
	/**
905
	 * Guess locale from language code.
906
	 *
907
	 * @param string $lang Language code.
908
	 * @return string|bool
909
	 */
910 View Code Duplication
	function guess_locale_from_lang( $lang ) {
911
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
912
			return 'en_US';
913
		}
914
915
		if ( ! class_exists( 'GP_Locales' ) ) {
916
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
917
				return false;
918
			}
919
920
			require JETPACK__GLOTPRESS_LOCALES_PATH;
921
		}
922
923
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
924
			// WP.com: get_locale() returns 'it'
925
			$locale = GP_Locales::by_slug( $lang );
926
		} else {
927
			// Jetpack: get_locale() returns 'it_IT';
928
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
929
		}
930
931
		if ( ! $locale ) {
932
			return false;
933
		}
934
935
		if ( empty( $locale->facebook_locale ) ) {
936
			if ( empty( $locale->wp_locale ) ) {
937
				return false;
938
			} else {
939
				// Facebook SDK is smart enough to fall back to en_US if a
940
				// locale isn't supported. Since supported Facebook locales
941
				// can fall out of sync, we'll attempt to use the known
942
				// wp_locale value and rely on said fallback.
943
				return $locale->wp_locale;
944
			}
945
		}
946
947
		return $locale->facebook_locale;
948
	}
949
950
	/**
951
	 * Get the locale.
952
	 *
953
	 * @return string|bool
954
	 */
955
	function get_locale() {
956
		$locale = $this->guess_locale_from_lang( get_locale() );
957
958
		if ( ! $locale ) {
959
			$locale = 'en_US';
960
		}
961
962
		return $locale;
963
	}
964
965
	/**
966
	 * Device Pixels support
967
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
968
	 */
969
	function devicepx() {
970
		if ( Jetpack::is_active() ) {
971
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
972
		}
973
	}
974
975
	/**
976
	 * Return the network_site_url so that .com knows what network this site is a part of.
977
	 * @param  bool $option
978
	 * @return string
979
	 */
980
	public function jetpack_main_network_site_option( $option ) {
981
		return network_site_url();
982
	}
983
	/**
984
	 * Network Name.
985
	 */
986
	static function network_name( $option = null ) {
987
		global $current_site;
988
		return $current_site->site_name;
989
	}
990
	/**
991
	 * Does the network allow new user and site registrations.
992
	 * @return string
993
	 */
994
	static function network_allow_new_registrations( $option = null ) {
995
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
996
	}
997
	/**
998
	 * Does the network allow admins to add new users.
999
	 * @return boolian
1000
	 */
1001
	static function network_add_new_users( $option = null ) {
1002
		return (bool) get_site_option( 'add_new_users' );
1003
	}
1004
	/**
1005
	 * File upload psace left per site in MB.
1006
	 *  -1 means NO LIMIT.
1007
	 * @return number
1008
	 */
1009
	static function network_site_upload_space( $option = null ) {
1010
		// value in MB
1011
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1012
	}
1013
1014
	/**
1015
	 * Network allowed file types.
1016
	 * @return string
1017
	 */
1018
	static function network_upload_file_types( $option = null ) {
1019
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1020
	}
1021
1022
	/**
1023
	 * Maximum file upload size set by the network.
1024
	 * @return number
1025
	 */
1026
	static function network_max_upload_file_size( $option = null ) {
1027
		// value in KB
1028
		return get_site_option( 'fileupload_maxk', 300 );
1029
	}
1030
1031
	/**
1032
	 * Lets us know if a site allows admins to manage the network.
1033
	 * @return array
1034
	 */
1035
	static function network_enable_administration_menus( $option = null ) {
1036
		return get_site_option( 'menu_items' );
1037
	}
1038
1039
	/**
1040
	 * Return whether we are dealing with a multi network setup or not.
1041
	 * The reason we are type casting this is because we want to avoid the situation where
1042
	 * the result is false since when is_main_network_option return false it cases
1043
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1044
	 * database which could be set to anything as opposed to what this function returns.
1045
	 * @param  bool  $option
1046
	 *
1047
	 * @return boolean
1048
	 */
1049
	public function is_main_network_option( $option ) {
1050
		// return '1' or ''
1051
		return (string) (bool) Jetpack::is_multi_network();
1052
	}
1053
1054
	/**
1055
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1056
	 *
1057
	 * @param  string  $option
1058
	 * @return boolean
1059
	 */
1060
	public function is_multisite( $option ) {
1061
		return (string) (bool) is_multisite();
1062
	}
1063
1064
	/**
1065
	 * Implemented since there is no core is multi network function
1066
	 * Right now there is no way to tell if we which network is the dominant network on the system
1067
	 *
1068
	 * @since  3.3
1069
	 * @return boolean
1070
	 */
1071
	public static function is_multi_network() {
1072
		global  $wpdb;
1073
1074
		// if we don't have a multi site setup no need to do any more
1075
		if ( ! is_multisite() ) {
1076
			return false;
1077
		}
1078
1079
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1080
		if ( $num_sites > 1 ) {
1081
			return true;
1082
		} else {
1083
			return false;
1084
		}
1085
	}
1086
1087
	/**
1088
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1089
	 * @return null
1090
	 */
1091
	function update_jetpack_main_network_site_option() {
1092
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1093
		/**
1094
		 * Fires when the site URL is updated.
1095
		 * Determines if the site is the main site of a Mulitiste network.
1096
		 *
1097
		 * @since 3.3.0
1098
		 *
1099
		 * @param string jetpack_main_network_site.
1100
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1101
		 */
1102
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1103
		/**
1104
		 * Fires when the site URL is updated.
1105
		 * Determines if the is part of a multi network.
1106
		 *
1107
		 * @since 3.3.0
1108
		 *
1109
		 * @param string jetpack_is_main_network.
1110
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1111
		 */
1112
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1113
		/**
1114
		 * Fires when the site URL is updated.
1115
		 * Determines if the site is part of a multisite network.
1116
		 *
1117
		 * @since 3.4.0
1118
		 *
1119
		 * @param string jetpack_is_multi_site.
1120
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1121
		 */
1122
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1123
	}
1124
	/**
1125
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1126
	 *
1127
	 */
1128
	function update_jetpack_network_settings() {
1129
		// Only sync this info for the main network site.
1130
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1131
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1132
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1133
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1134
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1135
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1136
1137
	}
1138
1139
	/**
1140
	 * Get back if the current site is single user site.
1141
	 *
1142
	 * @return bool
1143
	 */
1144
	public static function is_single_user_site() {
1145
1146
		$user_query = new WP_User_Query( array(
1147
			'blog_id' => get_current_blog_id(),
1148
			'fields'  => 'ID',
1149
			'number' => 2
1150
		) );
1151
		return 1 === (int) $user_query->get_total();
1152
	}
1153
1154
	/**
1155
	 * Returns true if the site has file write access false otherwise.
1156
	 * @return string ( '1' | '0' )
1157
	 **/
1158
	public static function file_system_write_access() {
1159
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1160
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1161
		}
1162
1163
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1164
1165
		$filesystem_method = get_filesystem_method();
1166
		if ( $filesystem_method === 'direct' ) {
1167
			return 1;
1168
		}
1169
1170
		ob_start();
1171
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1172
		ob_end_clean();
1173
		if ( $filesystem_credentials_are_stored ) {
1174
			return 1;
1175
		}
1176
		return 0;
1177
	}
1178
1179
	/**
1180
	 * Finds out if a site is using a version control system.
1181
	 * @return string ( '1' | '0' )
1182
	 **/
1183
	public static function is_version_controlled() {
1184
1185
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1186
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1187
		}
1188
		$updater = new WP_Automatic_Updater();
1189
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1190
		// transients should not be empty
1191
		if ( empty( $is_version_controlled ) ) {
1192
			$is_version_controlled = '0';
1193
		}
1194
		return $is_version_controlled;
1195
	}
1196
1197
	/**
1198
	 * Determines whether the current theme supports featured images or not.
1199
	 * @return string ( '1' | '0' )
1200
	 */
1201
	public static function featured_images_enabled() {
1202
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1203
	}
1204
1205
	/*
1206
	 * Sync back wp_version
1207
	 */
1208
	public static function get_wp_version() {
1209
		global $wp_version;
1210
		return $wp_version;
1211
	}
1212
1213
	/**
1214
	 * Keeps wp_version in sync with .com when WordPress core updates
1215
	 **/
1216
	public static function update_get_wp_version( $update, $meta_data ) {
1217
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1218
			/** This action is documented in wp-includes/option.php */
1219
			/**
1220
			 * This triggers the sync for the jetpack version
1221
			 * See Jetpack_Sync options method for more info.
1222
			 */
1223
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1224
		}
1225
	}
1226
1227
	/**
1228
	 * Triggers a sync of update counts and update details
1229
	 */
1230
	function sync_update_data() {
1231
		// Anytime WordPress saves update data, we'll want to sync update data
1232
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1233
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1234
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1235
		// Anytime a connection to jetpack is made, sync the update data
1236
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1237
		// Anytime the Jetpack Version changes, sync the the update data
1238
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1239
1240
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1241
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1242
		}
1243
1244
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1245
	}
1246
1247
	/**
1248
	 * Triggers a sync of information specific to the current theme.
1249
	 */
1250
	function sync_theme_data() {
1251
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1252
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1253
	}
1254
1255
	/**
1256
	 * jetpack_updates is saved in the following schema:
1257
	 *
1258
	 * array (
1259
	 *      'plugins'                       => (int) Number of plugin updates available.
1260
	 *      'themes'                        => (int) Number of theme updates available.
1261
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1262
	 *      'translations'                  => (int) Number of translation updates available.
1263
	 *      'total'                         => (int) Total of all available updates.
1264
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1265
	 * )
1266
	 * @return array
1267
	 */
1268
	public static function get_updates() {
1269
		$update_data = wp_get_update_data();
1270
1271
		// Stores the individual update counts as well as the total count.
1272
		if ( isset( $update_data['counts'] ) ) {
1273
			$updates = $update_data['counts'];
1274
		}
1275
1276
		// If we need to update WordPress core, let's find the latest version number.
1277 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1278
			$cur = get_preferred_from_update_core();
1279
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1280
				$updates['wp_update_version'] = $cur->current;
1281
			}
1282
		}
1283
		return isset( $updates ) ? $updates : array();
1284
	}
1285
1286
	public static function get_update_details() {
1287
		$update_details = array(
1288
			'update_core' => get_site_transient( 'update_core' ),
1289
			'update_plugins' => get_site_transient( 'update_plugins' ),
1290
			'update_themes' => get_site_transient( 'update_themes' ),
1291
		);
1292
		return $update_details;
1293
	}
1294
1295
	public static function refresh_update_data() {
1296
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1297
			/**
1298
			 * Fires whenever the amount of updates needed for a site changes.
1299
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1300
			 *
1301
			 * @since 3.7.0
1302
			 *
1303
			 * @param string jetpack_updates
1304
			 * @param array Update counts calculated by Jetpack::get_updates
1305
			 */
1306
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1307
		}
1308
		/**
1309
		 * Fires whenever the amount of updates needed for a site changes.
1310
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1311
		 *
1312
		 * @since 3.7.0
1313
		 *
1314
		 * @param string jetpack_update_details
1315
		 * @param array Update details calculated by Jetpack::get_update_details
1316
		 */
1317
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1318
	}
1319
1320
	public static function refresh_theme_data() {
1321
		/**
1322
		 * Fires whenever a theme change is made.
1323
		 *
1324
		 * @since 3.8.1
1325
		 *
1326
		 * @param string featured_images_enabled
1327
		 * @param boolean Whether featured images are enabled or not
1328
		 */
1329
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1330
	}
1331
1332
	/**
1333
	 * Invalides the transient as well as triggers the update of the mock option.
1334
	 *
1335
	 * @return null
1336
	 */
1337
	function is_single_user_site_invalidate() {
1338
		/**
1339
		 * Fires when a user is added or removed from a site.
1340
		 * Determines if the site is a single user site.
1341
		 *
1342
		 * @since 3.4.0
1343
		 *
1344
		 * @param string jetpack_single_user_site.
1345
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1346
		 */
1347
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1348
	}
1349
1350
	/**
1351
	 * Is Jetpack active?
1352
	 */
1353
	public static function is_active() {
1354
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1355
	}
1356
1357
	/**
1358
	 * Is Jetpack in development (offline) mode?
1359
	 */
1360
	public static function is_development_mode() {
1361
		$development_mode = false;
1362
1363
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1364
			$development_mode = JETPACK_DEV_DEBUG;
1365
		}
1366
1367
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1368
			$development_mode = true;
1369
		}
1370
		/**
1371
		 * Filters Jetpack's development mode.
1372
		 *
1373
		 * @see http://jetpack.com/support/development-mode/
1374
		 *
1375
		 * @since 2.2.1
1376
		 *
1377
		 * @param bool $development_mode Is Jetpack's development mode active.
1378
		 */
1379
		return apply_filters( 'jetpack_development_mode', $development_mode );
1380
	}
1381
1382
	/**
1383
	* Get Jetpack development mode notice text and notice class.
1384
	*
1385
	* Mirrors the checks made in Jetpack::is_development_mode
1386
	*
1387
	*/
1388
	public static function show_development_mode_notice() {
1389
		if ( Jetpack::is_development_mode() ) {
1390
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1391
				$notice = sprintf(
1392
					/* translators: %s is a URL */
1393
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1394
					'http://jetpack.com/support/development-mode/'
1395
				);
1396
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1397
				$notice = sprintf(
1398
					/* translators: %s is a URL */
1399
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1400
					'http://jetpack.com/support/development-mode/'
1401
				);
1402
			} else {
1403
				$notice = sprintf(
1404
					/* translators: %s is a URL */
1405
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1406
					'http://jetpack.com/support/development-mode/'
1407
				);
1408
			}
1409
1410
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1411
		}
1412
1413
		// Throw up a notice if using a development version and as for feedback.
1414
		if ( Jetpack::is_development_version() ) {
1415
			/* translators: %s is a URL */
1416
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1417
1418
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1419
		}
1420
		// Throw up a notice if using staging mode
1421
		if ( Jetpack::is_staging_site() ) {
1422
			/* translators: %s is a URL */
1423
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1424
1425
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1426
		}
1427
	}
1428
1429
	/**
1430
	 * Whether Jetpack's version maps to a public release, or a development version.
1431
	 */
1432
	public static function is_development_version() {
1433
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1434
	}
1435
1436
	/**
1437
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1438
	 */
1439
	public static function is_user_connected( $user_id = false ) {
1440
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1441
		if ( ! $user_id ) {
1442
			return false;
1443
		}
1444
		return (bool) Jetpack_Data::get_access_token( $user_id );
1445
	}
1446
1447
	/**
1448
	 * Get the wpcom user data of the current|specified connected user.
1449
	 */
1450 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1451
		if ( ! $user_id ) {
1452
			$user_id = get_current_user_id();
1453
		}
1454
		Jetpack::load_xml_rpc_client();
1455
		$xml = new Jetpack_IXR_Client( array(
1456
			'user_id' => $user_id,
1457
		) );
1458
		$xml->query( 'wpcom.getUser' );
1459
		if ( ! $xml->isError() ) {
1460
			return $xml->getResponse();
1461
		}
1462
		return false;
1463
	}
1464
1465
	/**
1466
	 * Get the wpcom email of the current|specified connected user.
1467
	 */
1468 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1469
		if ( ! $user_id ) {
1470
			$user_id = get_current_user_id();
1471
		}
1472
		Jetpack::load_xml_rpc_client();
1473
		$xml = new Jetpack_IXR_Client( array(
1474
			'user_id' => $user_id,
1475
		) );
1476
		$xml->query( 'wpcom.getUserEmail' );
1477
		if ( ! $xml->isError() ) {
1478
			return $xml->getResponse();
1479
		}
1480
		return false;
1481
	}
1482
1483
	/**
1484
	 * Get the wpcom email of the master user.
1485
	 */
1486
	public static function get_master_user_email() {
1487
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1488
		if ( $master_user_id ) {
1489
			return self::get_connected_user_email( $master_user_id );
1490
		}
1491
		return '';
1492
	}
1493
1494
	function current_user_is_connection_owner() {
1495
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1496
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1497
	}
1498
1499
	/**
1500
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1501
	 */
1502
	function extra_oembed_providers() {
1503
		// Cloudup: https://dev.cloudup.com/#oembed
1504
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1505
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1506
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1507
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1508
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1509
	}
1510
1511
	/**
1512
	 * Synchronize connected user role changes
1513
	 */
1514
	function user_role_change( $user_id ) {
1515
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1516
			$current_user_id = get_current_user_id();
1517
			wp_set_current_user( $user_id );
1518
			$role = $this->translate_current_user_to_role();
1519
			$signed_role = $this->sign_role( $role );
1520
			wp_set_current_user( $current_user_id );
1521
1522
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1523
			$master_user_id = absint( $master_token->external_user_id );
1524
1525
			if ( ! $master_user_id )
1526
				return; // this shouldn't happen
1527
1528
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1529
			//@todo retry on failure
1530
1531
			//try to choose a new master if we're demoting the current one
1532
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1533
				$query = new WP_User_Query(
1534
					array(
1535
						'fields'  => array( 'id' ),
1536
						'role'    => 'administrator',
1537
						'orderby' => 'id',
1538
						'exclude' => array( $master_user_id ),
1539
					)
1540
				);
1541
				$new_master = false;
1542
				foreach ( $query->results as $result ) {
1543
					$uid = absint( $result->id );
1544
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1545
						$new_master = $uid;
1546
						break;
1547
					}
1548
				}
1549
1550
				if ( $new_master ) {
1551
					Jetpack_Options::update_option( 'master_user', $new_master );
1552
				}
1553
				// else disconnect..?
1554
			}
1555
		}
1556
	}
1557
1558
	/**
1559
	 * Loads the currently active modules.
1560
	 */
1561
	public static function load_modules() {
1562
		if ( ! self::is_active() && !self::is_development_mode() ) {
1563
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1564
				return;
1565
			}
1566
		}
1567
1568
		$version = Jetpack_Options::get_option( 'version' );
1569 View Code Duplication
		if ( ! $version ) {
1570
			$version = $old_version = JETPACK__VERSION . ':' . time();
1571
			/** This action is documented in class.jetpack.php */
1572
			do_action( 'updating_jetpack_version', $version, false );
1573
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1574
		}
1575
		list( $version ) = explode( ':', $version );
1576
1577
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1578
1579
		$modules_data = array();
1580
1581
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1582
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1583
			$updated_modules = array();
1584
			foreach ( $modules as $module ) {
1585
				$modules_data[ $module ] = Jetpack::get_module( $module );
1586
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1587
					continue;
1588
				}
1589
1590
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1591
					continue;
1592
				}
1593
1594
				$updated_modules[] = $module;
1595
			}
1596
1597
			$modules = array_diff( $modules, $updated_modules );
1598
		}
1599
1600
		$is_development_mode = Jetpack::is_development_mode();
1601
1602
		foreach ( $modules as $index => $module ) {
1603
			// If we're in dev mode, disable modules requiring a connection
1604
			if ( $is_development_mode ) {
1605
				// Prime the pump if we need to
1606
				if ( empty( $modules_data[ $module ] ) ) {
1607
					$modules_data[ $module ] = Jetpack::get_module( $module );
1608
				}
1609
				// If the module requires a connection, but we're in local mode, don't include it.
1610
				if ( $modules_data[ $module ]['requires_connection'] ) {
1611
					continue;
1612
				}
1613
			}
1614
1615
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1616
				continue;
1617
			}
1618
1619
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1620
				unset( $modules[ $index ] );
1621
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1622
				continue;
1623
			}
1624
1625
			/**
1626
			 * Fires when a specific module is loaded.
1627
			 * The dynamic part of the hook, $module, is the module slug.
1628
			 *
1629
			 * @since 1.1.0
1630
			 */
1631
			do_action( 'jetpack_module_loaded_' . $module );
1632
		}
1633
1634
		/**
1635
		 * Fires when all the modules are loaded.
1636
		 *
1637
		 * @since 1.1.0
1638
		 */
1639
		do_action( 'jetpack_modules_loaded' );
1640
1641
		// 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.
1642
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1643
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1644
	}
1645
1646
	/**
1647
	 * Check if Jetpack's REST API compat file should be included
1648
	 * @action plugins_loaded
1649
	 * @return null
1650
	 */
1651
	public function check_rest_api_compat() {
1652
		/**
1653
		 * Filters the list of REST API compat files to be included.
1654
		 *
1655
		 * @since 2.2.5
1656
		 *
1657
		 * @param array $args Array of REST API compat files to include.
1658
		 */
1659
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1660
1661
		if ( function_exists( 'bbpress' ) )
1662
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1663
1664
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1665
			require_once $_jetpack_rest_api_compat_include;
1666
	}
1667
1668
	/**
1669
	 * Gets all plugins currently active in values, regardless of whether they're
1670
	 * traditionally activated or network activated.
1671
	 *
1672
	 * @todo Store the result in core's object cache maybe?
1673
	 */
1674
	public static function get_active_plugins() {
1675
		$active_plugins = (array) get_option( 'active_plugins', array() );
1676
1677
		if ( is_multisite() ) {
1678
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1679
			// whereas active_plugins stores them in the values.
1680
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1681
			if ( $network_plugins ) {
1682
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1683
			}
1684
		}
1685
1686
		sort( $active_plugins );
1687
1688
		return array_unique( $active_plugins );
1689
	}
1690
1691
	/**
1692
	 * Gets and parses additional plugin data to send with the heartbeat data
1693
	 *
1694
	 * @since 3.8.1
1695
	 *
1696
	 * @return array Array of plugin data
1697
	 */
1698
	public static function get_parsed_plugin_data() {
1699
		if ( ! function_exists( 'get_plugins' ) ) {
1700
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1701
		}
1702
		$all_plugins    = get_plugins();
1703
		$active_plugins = Jetpack::get_active_plugins();
1704
1705
		$plugins = array();
1706
		foreach ( $all_plugins as $path => $plugin_data ) {
1707
			$plugins[ $path ] = array(
1708
					'is_active' => in_array( $path, $active_plugins ),
1709
					'file'      => $path,
1710
					'name'      => $plugin_data['Name'],
1711
					'version'   => $plugin_data['Version'],
1712
					'author'    => $plugin_data['Author'],
1713
			);
1714
		}
1715
1716
		return $plugins;
1717
	}
1718
1719
	/**
1720
	 * Gets and parses theme data to send with the heartbeat data
1721
	 *
1722
	 * @since 3.8.1
1723
	 *
1724
	 * @return array Array of theme data
1725
	 */
1726
	public static function get_parsed_theme_data() {
1727
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1728
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1729
1730
		$themes = array();
1731
		foreach ( $all_themes as $slug => $theme_data ) {
1732
			$theme_headers = array();
1733
			foreach ( $header_keys as $header_key ) {
1734
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1735
			}
1736
1737
			$themes[ $slug ] = array(
1738
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1739
					'slug' => $slug,
1740
					'theme_root' => $theme_data->get_theme_root_uri(),
1741
					'parent' => $theme_data->parent(),
1742
					'headers' => $theme_headers
1743
			);
1744
		}
1745
1746
		return $themes;
1747
	}
1748
1749
	/**
1750
	 * Checks whether a specific plugin is active.
1751
	 *
1752
	 * We don't want to store these in a static variable, in case
1753
	 * there are switch_to_blog() calls involved.
1754
	 */
1755
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1756
		return in_array( $plugin, self::get_active_plugins() );
1757
	}
1758
1759
	/**
1760
	 * Check if Jetpack's Open Graph tags should be used.
1761
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1762
	 *
1763
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1764
	 * @action plugins_loaded
1765
	 * @return null
1766
	 */
1767
	public function check_open_graph() {
1768
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1769
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1770
		}
1771
1772
		$active_plugins = self::get_active_plugins();
1773
1774
		if ( ! empty( $active_plugins ) ) {
1775
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1776
				if ( in_array( $plugin, $active_plugins ) ) {
1777
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1778
					break;
1779
				}
1780
			}
1781
		}
1782
1783
		/**
1784
		 * Allow the addition of Open Graph Meta Tags to all pages.
1785
		 *
1786
		 * @since 2.0.3
1787
		 *
1788
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1789
		 */
1790
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1791
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1792
		}
1793
	}
1794
1795
	/**
1796
	 * Check if Jetpack's Twitter tags should be used.
1797
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1798
	 *
1799
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1800
	 * @action plugins_loaded
1801
	 * @return null
1802
	 */
1803
	public function check_twitter_tags() {
1804
1805
		$active_plugins = self::get_active_plugins();
1806
1807
		if ( ! empty( $active_plugins ) ) {
1808
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1809
				if ( in_array( $plugin, $active_plugins ) ) {
1810
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1811
					break;
1812
				}
1813
			}
1814
		}
1815
1816
		/**
1817
		 * Allow Twitter Card Meta tags to be disabled.
1818
		 *
1819
		 * @since 2.6.0
1820
		 *
1821
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1822
		 */
1823
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1824
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1825
		}
1826
	}
1827
1828
1829
1830
1831
	/*
1832
	 *
1833
	 * Jetpack Security Reports
1834
	 *
1835
	 * Allowed types: login_form, backup, file_scanning, spam
1836
	 *
1837
	 * 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)
1838
	 *
1839
	 * 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)
1840
	 *
1841
	 *
1842
	 * Example code to submit a security report:
1843
	 *
1844
	 *  function akismet_submit_jetpack_security_report() {
1845
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1846
	 *  }
1847
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1848
	 *
1849
	 */
1850
1851
1852
	/**
1853
	 * Calls for security report submissions.
1854
	 *
1855
	 * @return null
1856
	 */
1857
	public static function perform_security_reporting() {
1858
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1859
1860
		if ( $no_check_needed ) {
1861
			return;
1862
		}
1863
1864
		/**
1865
		 * Fires before a security report is created.
1866
		 *
1867
		 * @since 3.4.0
1868
		 */
1869
		do_action( 'jetpack_security_report' );
1870
1871
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1872
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1873
	}
1874
1875
	/**
1876
	 * Allows plugins to submit security reports.
1877
 	 *
1878
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1879
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1880
	 * @param array   $args         See definitions above
1881
	 */
1882
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1883
1884
		if( !doing_action( 'jetpack_security_report' ) ) {
1885
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1886
		}
1887
1888
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1889
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1890
		}
1891
1892
		if( !function_exists( 'get_plugin_data' ) ) {
1893
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1894
		}
1895
1896
		//Get rid of any non-allowed args
1897
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1898
1899
		$plugin = get_plugin_data( $plugin_file );
1900
1901
		if ( !$plugin['Name'] ) {
1902
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1903
		}
1904
1905
		// Sanitize everything to make sure we're not syncing something wonky
1906
		$type = sanitize_key( $type );
1907
1908
		$args['plugin'] = $plugin;
1909
1910
		// Cast blocked, last and next as integers.
1911
		// Last and next should be in unix timestamp format
1912
		if ( isset( $args['blocked'] ) ) {
1913
			$args['blocked'] = (int) $args['blocked'];
1914
		}
1915
		if ( isset( $args['last'] ) ) {
1916
			$args['last'] = (int) $args['last'];
1917
		}
1918
		if ( isset( $args['next'] ) ) {
1919
			$args['next'] = (int) $args['next'];
1920
		}
1921
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1922
			$args['status'] = 'ok';
1923
		}
1924
		if ( isset( $args['message'] ) ) {
1925
1926
			if( $args['status'] == 'ok' ) {
1927
				unset( $args['message'] );
1928
			}
1929
1930
			$allowed_html = array(
1931
			    'a' => array(
1932
			        'href' => array(),
1933
			        'title' => array()
1934
			    ),
1935
			    'em' => array(),
1936
			    'strong' => array(),
1937
			);
1938
1939
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1940
		}
1941
1942
		$plugin_name = $plugin[ 'Name' ];
1943
1944
		self::$security_report[ $type ][ $plugin_name ] = $args;
1945
	}
1946
1947
	/**
1948
	 * Collects a new report if needed, then returns it.
1949
	 */
1950
	public function get_security_report() {
1951
		self::perform_security_reporting();
1952
		return Jetpack_Options::get_option( 'security_report' );
1953
	}
1954
1955
1956
/* Jetpack Options API */
1957
1958
	public static function get_option_names( $type = 'compact' ) {
1959
		return Jetpack_Options::get_option_names( $type );
1960
	}
1961
1962
	/**
1963
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1964
 	 *
1965
	 * @param string $name    Option name
1966
	 * @param mixed  $default (optional)
1967
	 */
1968
	public static function get_option( $name, $default = false ) {
1969
		return Jetpack_Options::get_option( $name, $default );
1970
	}
1971
1972
	/**
1973
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1974
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1975
	* $name must be a registered option name.
1976
	*/
1977
	public static function create_nonce( $name ) {
1978
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1979
1980
		Jetpack_Options::update_option( $name, $secret );
1981
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1982
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1983
			return new Jetpack_Error( 'missing_secrets' );
1984
1985
		return array(
1986
			'secret_1' => $secret_1,
1987
			'secret_2' => $secret_2,
1988
			'eol'      => $eol,
1989
		);
1990
	}
1991
1992
	/**
1993
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1994
 	 *
1995
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1996
	 * @param string $name  Option name
1997
	 * @param mixed  $value Option value
1998
	 */
1999
	public static function update_option( $name, $value ) {
2000
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2001
		return Jetpack_Options::update_option( $name, $value );
2002
	}
2003
2004
	/**
2005
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2006
 	 *
2007
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2008
	 * @param array $array array( option name => option value, ... )
2009
	 */
2010
	public static function update_options( $array ) {
2011
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2012
		return Jetpack_Options::update_options( $array );
2013
	}
2014
2015
	/**
2016
	 * Deletes the given option.  May be passed multiple option names as an array.
2017
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2018
	 *
2019
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2020
	 * @param string|array $names
2021
	 */
2022
	public static function delete_option( $names ) {
2023
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2024
		return Jetpack_Options::delete_option( $names );
2025
	}
2026
2027
	/**
2028
	 * Enters a user token into the user_tokens option
2029
	 *
2030
	 * @param int $user_id
2031
	 * @param string $token
2032
	 * return bool
2033
	 */
2034
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2035
		// not designed for concurrent updates
2036
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2037
		if ( ! is_array( $user_tokens ) )
2038
			$user_tokens = array();
2039
		$user_tokens[$user_id] = $token;
2040
		if ( $is_master_user ) {
2041
			$master_user = $user_id;
2042
			$options     = compact( 'user_tokens', 'master_user' );
2043
		} else {
2044
			$options = compact( 'user_tokens' );
2045
		}
2046
		return Jetpack_Options::update_options( $options );
2047
	}
2048
2049
	/**
2050
	 * Returns an array of all PHP files in the specified absolute path.
2051
	 * Equivalent to glob( "$absolute_path/*.php" ).
2052
	 *
2053
	 * @param string $absolute_path The absolute path of the directory to search.
2054
	 * @return array Array of absolute paths to the PHP files.
2055
	 */
2056
	public static function glob_php( $absolute_path ) {
2057
		if ( function_exists( 'glob' ) ) {
2058
			return glob( "$absolute_path/*.php" );
2059
		}
2060
2061
		$absolute_path = untrailingslashit( $absolute_path );
2062
		$files = array();
2063
		if ( ! $dir = @opendir( $absolute_path ) ) {
2064
			return $files;
2065
		}
2066
2067
		while ( false !== $file = readdir( $dir ) ) {
2068
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2069
				continue;
2070
			}
2071
2072
			$file = "$absolute_path/$file";
2073
2074
			if ( ! is_file( $file ) ) {
2075
				continue;
2076
			}
2077
2078
			$files[] = $file;
2079
		}
2080
2081
		closedir( $dir );
2082
2083
		return $files;
2084
	}
2085
2086
	public static function activate_new_modules( $redirect = false ) {
2087
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2088
			return;
2089
		}
2090
2091
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2092 View Code Duplication
		if ( ! $jetpack_old_version ) {
2093
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2094
			/** This action is documented in class.jetpack.php */
2095
			do_action( 'updating_jetpack_version', $version, false );
2096
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2097
		}
2098
2099
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2100
2101
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2102
			return;
2103
		}
2104
2105
		$active_modules     = Jetpack::get_active_modules();
2106
		$reactivate_modules = array();
2107
		foreach ( $active_modules as $active_module ) {
2108
			$module = Jetpack::get_module( $active_module );
2109
			if ( ! isset( $module['changed'] ) ) {
2110
				continue;
2111
			}
2112
2113
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2114
				continue;
2115
			}
2116
2117
			$reactivate_modules[] = $active_module;
2118
			Jetpack::deactivate_module( $active_module );
2119
		}
2120
2121
		$new_version = JETPACK__VERSION . ':' . time();
2122
		/** This action is documented in class.jetpack.php */
2123
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2124
		Jetpack_Options::update_options(
2125
			array(
2126
				'version'     => $new_version,
2127
				'old_version' => $jetpack_old_version,
2128
			)
2129
		);
2130
2131
		Jetpack::state( 'message', 'modules_activated' );
2132
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2133
2134
		if ( $redirect ) {
2135
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2136
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2137
				$page = $_GET['page'];
2138
			}
2139
2140
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2141
			exit;
2142
		}
2143
	}
2144
2145
	/**
2146
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2147
	 * Make sure to tuck away module "library" files in a sub-directory.
2148
	 */
2149
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2150
		static $modules = null;
2151
2152
		if ( ! isset( $modules ) ) {
2153
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2154
			// Use the cache if we're on the front-end and it's available...
2155
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2156
				$modules = $available_modules_option[ JETPACK__VERSION ];
2157
			} else {
2158
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2159
2160
				$modules = array();
2161
2162
				foreach ( $files as $file ) {
2163
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2164
						continue;
2165
					}
2166
2167
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2168
				}
2169
2170
				Jetpack_Options::update_option( 'available_modules', array(
2171
					JETPACK__VERSION => $modules,
2172
				) );
2173
			}
2174
		}
2175
2176
		/**
2177
		 * Filters the array of modules available to be activated.
2178
		 *
2179
		 * @since 2.4.0
2180
		 *
2181
		 * @param array $modules Array of available modules.
2182
		 * @param string $min_version Minimum version number required to use modules.
2183
		 * @param string $max_version Maximum version number required to use modules.
2184
		 */
2185
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2186
2187
		if ( ! $min_version && ! $max_version ) {
2188
			return array_keys( $mods );
2189
		}
2190
2191
		$r = array();
2192
		foreach ( $mods as $slug => $introduced ) {
2193
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2194
				continue;
2195
			}
2196
2197
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2198
				continue;
2199
			}
2200
2201
			$r[] = $slug;
2202
		}
2203
2204
		return $r;
2205
	}
2206
2207
	/**
2208
	 * Default modules loaded on activation.
2209
	 */
2210
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2211
		$return = array();
2212
2213
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2214
			$module_data = Jetpack::get_module( $module );
2215
2216
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2217
				case 'yes' :
2218
					$return[] = $module;
2219
					break;
2220
				case 'public' :
2221
					if ( Jetpack_Options::get_option( 'public' ) ) {
2222
						$return[] = $module;
2223
					}
2224
					break;
2225
				case 'no' :
2226
				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...
2227
					break;
2228
			}
2229
		}
2230
		/**
2231
		 * Filters the array of default modules.
2232
		 *
2233
		 * @since 2.5.0
2234
		 *
2235
		 * @param array $return Array of default modules.
2236
		 * @param string $min_version Minimum version number required to use modules.
2237
		 * @param string $max_version Maximum version number required to use modules.
2238
		 */
2239
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2240
	}
2241
2242
	/**
2243
	 * Checks activated modules during auto-activation to determine
2244
	 * if any of those modules are being deprecated.  If so, close
2245
	 * them out, and add any replacement modules.
2246
	 *
2247
	 * Runs at priority 99 by default.
2248
	 *
2249
	 * This is run late, so that it can still activate a module if
2250
	 * the new module is a replacement for another that the user
2251
	 * currently has active, even if something at the normal priority
2252
	 * would kibosh everything.
2253
	 *
2254
	 * @since 2.6
2255
	 * @uses jetpack_get_default_modules filter
2256
	 * @param array $modules
2257
	 * @return array
2258
	 */
2259
	function handle_deprecated_modules( $modules ) {
2260
		$deprecated_modules = array(
2261
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2262
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2263
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2264
		);
2265
2266
		// Don't activate SSO if they never completed activating WPCC.
2267
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2268
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2269
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2270
				$deprecated_modules['wpcc'] = null;
2271
			}
2272
		}
2273
2274
		foreach ( $deprecated_modules as $module => $replacement ) {
2275
			if ( Jetpack::is_module_active( $module ) ) {
2276
				self::deactivate_module( $module );
2277
				if ( $replacement ) {
2278
					$modules[] = $replacement;
2279
				}
2280
			}
2281
		}
2282
2283
		return array_unique( $modules );
2284
	}
2285
2286
	/**
2287
	 * Checks activated plugins during auto-activation to determine
2288
	 * if any of those plugins are in the list with a corresponding module
2289
	 * that is not compatible with the plugin. The module will not be allowed
2290
	 * to auto-activate.
2291
	 *
2292
	 * @since 2.6
2293
	 * @uses jetpack_get_default_modules filter
2294
	 * @param array $modules
2295
	 * @return array
2296
	 */
2297
	function filter_default_modules( $modules ) {
2298
2299
		$active_plugins = self::get_active_plugins();
2300
2301
		if ( ! empty( $active_plugins ) ) {
2302
2303
			// For each module we'd like to auto-activate...
2304
			foreach ( $modules as $key => $module ) {
2305
				// If there are potential conflicts for it...
2306
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2307
					// For each potential conflict...
2308
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2309
						// If that conflicting plugin is active...
2310
						if ( in_array( $plugin, $active_plugins ) ) {
2311
							// Remove that item from being auto-activated.
2312
							unset( $modules[ $key ] );
2313
						}
2314
					}
2315
				}
2316
			}
2317
		}
2318
2319
		return $modules;
2320
	}
2321
2322
	/**
2323
	 * Extract a module's slug from its full path.
2324
	 */
2325
	public static function get_module_slug( $file ) {
2326
		return str_replace( '.php', '', basename( $file ) );
2327
	}
2328
2329
	/**
2330
	 * Generate a module's path from its slug.
2331
	 */
2332
	public static function get_module_path( $slug ) {
2333
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2334
	}
2335
2336
	/**
2337
	 * Load module data from module file. Headers differ from WordPress
2338
	 * plugin headers to avoid them being identified as standalone
2339
	 * plugins on the WordPress plugins page.
2340
	 */
2341
	public static function get_module( $module ) {
2342
		$headers = array(
2343
			'name'                      => 'Module Name',
2344
			'description'               => 'Module Description',
2345
			'jumpstart_desc'            => 'Jumpstart Description',
2346
			'sort'                      => 'Sort Order',
2347
			'recommendation_order'      => 'Recommendation Order',
2348
			'introduced'                => 'First Introduced',
2349
			'changed'                   => 'Major Changes In',
2350
			'deactivate'                => 'Deactivate',
2351
			'free'                      => 'Free',
2352
			'requires_connection'       => 'Requires Connection',
2353
			'auto_activate'             => 'Auto Activate',
2354
			'module_tags'               => 'Module Tags',
2355
			'feature'                   => 'Feature',
2356
			'additional_search_queries' => 'Additional Search Queries',
2357
		);
2358
2359
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2360
2361
		$mod = Jetpack::get_file_data( $file, $headers );
2362
		if ( empty( $mod['name'] ) ) {
2363
			return false;
2364
		}
2365
2366
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2367
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2368
		$mod['deactivate']              = empty( $mod['deactivate'] );
2369
		$mod['free']                    = empty( $mod['free'] );
2370
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2371
2372
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2373
			$mod['auto_activate'] = 'No';
2374
		} else {
2375
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2376
		}
2377
2378
		if ( $mod['module_tags'] ) {
2379
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2380
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2381
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2382
		} else {
2383
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2384
		}
2385
2386
		if ( $mod['feature'] ) {
2387
			$mod['feature'] = explode( ',', $mod['feature'] );
2388
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2389
		} else {
2390
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2391
		}
2392
2393
		/**
2394
		 * Filters the feature array on a module.
2395
		 *
2396
		 * This filter allows you to control where each module is filtered: Recommended,
2397
		 * Jumpstart, and the default "Other" listing.
2398
		 *
2399
		 * @since 3.5.0
2400
		 *
2401
		 * @param array   $mod['feature'] The areas to feature this module:
2402
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2403
		 *     'Recommended' shows on the main Jetpack admin screen.
2404
		 *     'Other' should be the default if no other value is in the array.
2405
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2406
		 * @param array   $mod All the currently assembled module data.
2407
		 */
2408
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2409
2410
		/**
2411
		 * Filter the returned data about a module.
2412
		 *
2413
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2414
		 * so please be careful.
2415
		 *
2416
		 * @since 3.6.0
2417
		 *
2418
		 * @param array   $mod    The details of the requested module.
2419
		 * @param string  $module The slug of the module, e.g. sharedaddy
2420
		 * @param string  $file   The path to the module source file.
2421
		 */
2422
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2423
	}
2424
2425
	/**
2426
	 * Like core's get_file_data implementation, but caches the result.
2427
	 */
2428
	public static function get_file_data( $file, $headers ) {
2429
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2430
		$file_name = basename( $file );
2431
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2432
		$key              = md5( $file_name . serialize( $headers ) );
2433
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2434
2435
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2436
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2437
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2438
		}
2439
2440
		$data = get_file_data( $file, $headers );
2441
2442
		// Strip out any old Jetpack versions that are cluttering the option.
2443
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2444
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2445
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2446
2447
		return $data;
2448
	}
2449
2450
	/**
2451
	 * Return translated module tag.
2452
	 *
2453
	 * @param string $tag Tag as it appears in each module heading.
2454
	 *
2455
	 * @return mixed
2456
	 */
2457
	public static function translate_module_tag( $tag ) {
2458
		return jetpack_get_module_i18n_tag( $tag );
2459
	}
2460
2461
	/**
2462
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2463
	 *
2464
	 * @since 3.9.2
2465
	 *
2466
	 * @param array $modules
2467
	 *
2468
	 * @return string|void
2469
	 */
2470
	public static function get_translated_modules( $modules ) {
2471
		foreach ( $modules as $index => $module ) {
2472
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2473
			if ( isset( $module['name'] ) ) {
2474
				$modules[ $index ]['name'] = $i18n_module['name'];
2475
			}
2476
			if ( isset( $module['description'] ) ) {
2477
				$modules[ $index ]['description'] = $i18n_module['description'];
2478
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2479
			}
2480
		}
2481
		return $modules;
2482
	}
2483
2484
	/**
2485
	 * Get a list of activated modules as an array of module slugs.
2486
	 */
2487
	public static function get_active_modules() {
2488
		$active = Jetpack_Options::get_option( 'active_modules' );
2489
		if ( ! is_array( $active ) )
2490
			$active = array();
2491
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2492
			$active[] = 'vaultpress';
2493
		} else {
2494
			$active = array_diff( $active, array( 'vaultpress' ) );
2495
		}
2496
2497
		//If protect is active on the main site of a multisite, it should be active on all sites.
2498
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2499
			$active[] = 'protect';
2500
		}
2501
2502
		return array_unique( $active );
2503
	}
2504
2505
	/**
2506
	 * Check whether or not a Jetpack module is active.
2507
	 *
2508
	 * @param string $module The slug of a Jetpack module.
2509
	 * @return bool
2510
	 *
2511
	 * @static
2512
	 */
2513
	public static function is_module_active( $module ) {
2514
		return in_array( $module, self::get_active_modules() );
2515
	}
2516
2517
	public static function is_module( $module ) {
2518
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2519
	}
2520
2521
	/**
2522
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2523
	 *
2524
	 * @param bool $catch True to start catching, False to stop.
2525
	 *
2526
	 * @static
2527
	 */
2528
	public static function catch_errors( $catch ) {
2529
		static $display_errors, $error_reporting;
2530
2531
		if ( $catch ) {
2532
			$display_errors  = @ini_set( 'display_errors', 1 );
2533
			$error_reporting = @error_reporting( E_ALL );
2534
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2535
		} else {
2536
			@ini_set( 'display_errors', $display_errors );
2537
			@error_reporting( $error_reporting );
2538
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2539
		}
2540
	}
2541
2542
	/**
2543
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2544
	 */
2545
	public static function catch_errors_on_shutdown() {
2546
		Jetpack::state( 'php_errors', ob_get_clean() );
2547
	}
2548
2549
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2550
		$jetpack = Jetpack::init();
2551
2552
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2553
		$modules = array_merge( $other_modules, $modules );
2554
2555
		// Look for standalone plugins and disable if active.
2556
2557
		$to_deactivate = array();
2558
		foreach ( $modules as $module ) {
2559
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2560
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2561
			}
2562
		}
2563
2564
		$deactivated = array();
2565
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2566
			list( $probable_file, $probable_title ) = $deactivate_me;
2567
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2568
				$deactivated[] = $module;
2569
			}
2570
		}
2571
2572
		if ( $deactivated && $redirect ) {
2573
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2574
2575
			$url = add_query_arg(
2576
				array(
2577
					'action'   => 'activate_default_modules',
2578
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2579
				),
2580
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2581
			);
2582
			wp_safe_redirect( $url );
2583
			exit;
2584
		}
2585
2586
		/**
2587
		 * Fires before default modules are activated.
2588
		 *
2589
		 * @since 1.9.0
2590
		 *
2591
		 * @param string $min_version Minimum version number required to use modules.
2592
		 * @param string $max_version Maximum version number required to use modules.
2593
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2594
		 */
2595
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2596
2597
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2598
		Jetpack::restate();
2599
		Jetpack::catch_errors( true );
2600
2601
		$active = Jetpack::get_active_modules();
2602
2603
		foreach ( $modules as $module ) {
2604
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2605
				$active[] = $module;
2606
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2607
				continue;
2608
			}
2609
2610
			if ( in_array( $module, $active ) ) {
2611
				$module_info = Jetpack::get_module( $module );
2612
				if ( ! $module_info['deactivate'] ) {
2613
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2614 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2615
						$active_state = explode( ',', $active_state );
2616
					} else {
2617
						$active_state = array();
2618
					}
2619
					$active_state[] = $module;
2620
					Jetpack::state( $state, implode( ',', $active_state ) );
2621
				}
2622
				continue;
2623
			}
2624
2625
			$file = Jetpack::get_module_path( $module );
2626
			if ( ! file_exists( $file ) ) {
2627
				continue;
2628
			}
2629
2630
			// we'll override this later if the plugin can be included without fatal error
2631
			if ( $redirect ) {
2632
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2633
			}
2634
			Jetpack::state( 'error', 'module_activation_failed' );
2635
			Jetpack::state( 'module', $module );
2636
			ob_start();
2637
			require $file;
2638
			/**
2639
			 * Fires when a specific module is activated.
2640
			 *
2641
			 * @since 1.9.0
2642
			 *
2643
			 * @param string $module Module slug.
2644
			 */
2645
			do_action( 'jetpack_activate_module', $module );
2646
			$active[] = $module;
2647
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2648 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2649
				$active_state = explode( ',', $active_state );
2650
			} else {
2651
				$active_state = array();
2652
			}
2653
			$active_state[] = $module;
2654
			Jetpack::state( $state, implode( ',', $active_state ) );
2655
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2656
			ob_end_clean();
2657
		}
2658
		Jetpack::state( 'error', false );
2659
		Jetpack::state( 'module', false );
2660
		Jetpack::catch_errors( false );
2661
		/**
2662
		 * Fires when default modules are activated.
2663
		 *
2664
		 * @since 1.9.0
2665
		 *
2666
		 * @param string $min_version Minimum version number required to use modules.
2667
		 * @param string $max_version Maximum version number required to use modules.
2668
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2669
		 */
2670
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2671
	}
2672
2673
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2674
		/**
2675
		 * Fires before a module is activated.
2676
		 *
2677
		 * @since 2.6.0
2678
		 *
2679
		 * @param string $module Module slug.
2680
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2681
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2682
		 */
2683
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2684
2685
		$jetpack = Jetpack::init();
2686
2687
		if ( ! strlen( $module ) )
2688
			return false;
2689
2690
		if ( ! Jetpack::is_module( $module ) )
2691
			return false;
2692
2693
		// If it's already active, then don't do it again
2694
		$active = Jetpack::get_active_modules();
2695
		foreach ( $active as $act ) {
2696
			if ( $act == $module )
2697
				return true;
2698
		}
2699
2700
		$module_data = Jetpack::get_module( $module );
2701
2702
		if ( ! Jetpack::is_active() ) {
2703
			if ( !Jetpack::is_development_mode() )
2704
				return false;
2705
2706
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2707
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2708
				return false;
2709
		}
2710
2711
		// Check and see if the old plugin is active
2712
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2713
			// Deactivate the old plugin
2714
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2715
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2716
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2717
				Jetpack::state( 'deactivated_plugins', $module );
2718
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2719
				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...
2720
			}
2721
		}
2722
2723
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2724
		Jetpack::state( 'module', $module );
2725
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2726
2727
		Jetpack::catch_errors( true );
2728
		ob_start();
2729
		require Jetpack::get_module_path( $module );
2730
		/** This action is documented in class.jetpack.php */
2731
		do_action( 'jetpack_activate_module', $module );
2732
		$active[] = $module;
2733
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2734
		Jetpack::state( 'error', false ); // the override
2735
		Jetpack::state( 'message', 'module_activated' );
2736
		Jetpack::state( 'module', $module );
2737
		ob_end_clean();
2738
		Jetpack::catch_errors( false );
2739
2740
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2741 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2742
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2743
2744
			//Jump start is being dismissed send data to MC Stats
2745
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2746
2747
			$jetpack->do_stats( 'server_side' );
2748
		}
2749
2750
		if ( $redirect ) {
2751
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2752
		}
2753
		if ( $exit ) {
2754
			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...
2755
		}
2756
		return true;
2757
	}
2758
2759
	function activate_module_actions( $module ) {
2760
		/**
2761
		 * Fires when a module is activated.
2762
		 * The dynamic part of the filter, $module, is the module slug.
2763
		 *
2764
		 * @since 1.9.0
2765
		 *
2766
		 * @param string $module Module slug.
2767
		 */
2768
		do_action( "jetpack_activate_module_$module", $module );
2769
2770
		$this->sync->sync_all_module_options( $module );
2771
	}
2772
2773
	public static function deactivate_module( $module ) {
2774
		/**
2775
		 * Fires when a module is deactivated.
2776
		 *
2777
		 * @since 1.9.0
2778
		 *
2779
		 * @param string $module Module slug.
2780
		 */
2781
		do_action( 'jetpack_pre_deactivate_module', $module );
2782
2783
		$jetpack = Jetpack::init();
2784
2785
		$active = Jetpack::get_active_modules();
2786
		$new    = array_filter( array_diff( $active, (array) $module ) );
2787
2788
		/**
2789
		 * Fires when a module is deactivated.
2790
		 * The dynamic part of the filter, $module, is the module slug.
2791
		 *
2792
		 * @since 1.9.0
2793
		 *
2794
		 * @param string $module Module slug.
2795
		 */
2796
		do_action( "jetpack_deactivate_module_$module", $module );
2797
2798
		// A flag for Jump Start so it's not shown again.
2799 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2800
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2801
2802
			//Jump start is being dismissed send data to MC Stats
2803
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2804
2805
			$jetpack->do_stats( 'server_side' );
2806
		}
2807
2808
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2809
	}
2810
2811
	public static function enable_module_configurable( $module ) {
2812
		$module = Jetpack::get_module_slug( $module );
2813
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2814
	}
2815
2816
	public static function module_configuration_url( $module ) {
2817
		$module = Jetpack::get_module_slug( $module );
2818
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2819
	}
2820
2821
	public static function module_configuration_load( $module, $method ) {
2822
		$module = Jetpack::get_module_slug( $module );
2823
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2824
	}
2825
2826
	public static function module_configuration_head( $module, $method ) {
2827
		$module = Jetpack::get_module_slug( $module );
2828
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2829
	}
2830
2831
	public static function module_configuration_screen( $module, $method ) {
2832
		$module = Jetpack::get_module_slug( $module );
2833
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2834
	}
2835
2836
	public static function module_configuration_activation_screen( $module, $method ) {
2837
		$module = Jetpack::get_module_slug( $module );
2838
		add_action( 'display_activate_module_setting_' . $module, $method );
2839
	}
2840
2841
/* Installation */
2842
2843
	public static function bail_on_activation( $message, $deactivate = true ) {
2844
?>
2845
<!doctype html>
2846
<html>
2847
<head>
2848
<meta charset="<?php bloginfo( 'charset' ); ?>">
2849
<style>
2850
* {
2851
	text-align: center;
2852
	margin: 0;
2853
	padding: 0;
2854
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2855
}
2856
p {
2857
	margin-top: 1em;
2858
	font-size: 18px;
2859
}
2860
</style>
2861
<body>
2862
<p><?php echo esc_html( $message ); ?></p>
2863
</body>
2864
</html>
2865
<?php
2866
		if ( $deactivate ) {
2867
			$plugins = get_option( 'active_plugins' );
2868
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2869
			$update  = false;
2870
			foreach ( $plugins as $i => $plugin ) {
2871
				if ( $plugin === $jetpack ) {
2872
					$plugins[$i] = false;
2873
					$update = true;
2874
				}
2875
			}
2876
2877
			if ( $update ) {
2878
				update_option( 'active_plugins', array_filter( $plugins ) );
2879
			}
2880
		}
2881
		exit;
2882
	}
2883
2884
	/**
2885
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2886
	 * @static
2887
	 */
2888
	public static function plugin_activation( $network_wide ) {
2889
		Jetpack_Options::update_option( 'activated', 1 );
2890
2891
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2892
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2893
		}
2894
2895
		if ( $network_wide )
2896
			Jetpack::state( 'network_nag', true );
2897
2898
		Jetpack::plugin_initialize();
2899
	}
2900
	/**
2901
	 * Runs before bumping version numbers up to a new version
2902
	 * @param  (string) $version    Version:timestamp
2903
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2904
	 * @return null              [description]
2905
	 */
2906
	public static function do_version_bump( $version, $old_version ) {
2907
2908
		if ( ! $old_version ) { // For new sites
2909
			// Setting up jetpack manage
2910
			Jetpack::activate_manage();
2911
		}
2912
	}
2913
2914
	/**
2915
	 * Sets the internal version number and activation state.
2916
	 * @static
2917
	 */
2918
	public static function plugin_initialize() {
2919
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2920
			Jetpack_Options::update_option( 'activated', 2 );
2921
		}
2922
2923 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2924
			$version = $old_version = JETPACK__VERSION . ':' . time();
2925
			/** This action is documented in class.jetpack.php */
2926
			do_action( 'updating_jetpack_version', $version, false );
2927
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2928
		}
2929
2930
		Jetpack::load_modules();
2931
2932
		Jetpack_Options::delete_option( 'do_activate' );
2933
	}
2934
2935
	/**
2936
	 * Removes all connection options
2937
	 * @static
2938
	 */
2939
	public static function plugin_deactivation( ) {
2940
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2941
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2942
			Jetpack_Network::init()->deactivate();
2943
		} else {
2944
			Jetpack::disconnect( false );
2945
			//Jetpack_Heartbeat::init()->deactivate();
2946
		}
2947
	}
2948
2949
	/**
2950
	 * Disconnects from the Jetpack servers.
2951
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2952
	 * @static
2953
	 */
2954
	public static function disconnect( $update_activated_state = true ) {
2955
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2956
		Jetpack::clean_nonces( true );
2957
2958
		Jetpack::load_xml_rpc_client();
2959
		$xml = new Jetpack_IXR_Client();
2960
		$xml->query( 'jetpack.deregister' );
2961
2962
		Jetpack_Options::delete_option(
2963
			array(
2964
				'register',
2965
				'blog_token',
2966
				'user_token',
2967
				'user_tokens',
2968
				'master_user',
2969
				'time_diff',
2970
				'fallback_no_verify_ssl_certs',
2971
			)
2972
		);
2973
2974
		if ( $update_activated_state ) {
2975
			Jetpack_Options::update_option( 'activated', 4 );
2976
		}
2977
2978
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2979
		// Check then record unique disconnection if site has never been disconnected previously
2980
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2981
			$jetpack_unique_connection['disconnected'] = 1;
2982
		}
2983
		else {
2984
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2985
				//track unique disconnect
2986
				$jetpack = Jetpack::init();
2987
2988
				$jetpack->stat( 'connections', 'unique-disconnect' );
2989
				$jetpack->do_stats( 'server_side' );
2990
			}
2991
			// increment number of times disconnected
2992
			$jetpack_unique_connection['disconnected'] += 1;
2993
		}
2994
2995
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2996
2997
		// Disable the Heartbeat cron
2998
		Jetpack_Heartbeat::init()->deactivate();
2999
	}
3000
3001
	/**
3002
	 * Unlinks the current user from the linked WordPress.com user
3003
	 */
3004
	public static function unlink_user( $user_id = null ) {
3005
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3006
			return false;
3007
3008
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3009
3010
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3011
			return false;
3012
3013
		if ( ! isset( $tokens[ $user_id ] ) )
3014
			return false;
3015
3016
		Jetpack::load_xml_rpc_client();
3017
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3018
		$xml->query( 'jetpack.unlink_user', $user_id );
3019
3020
		unset( $tokens[ $user_id ] );
3021
3022
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3023
3024
		/**
3025
		 * Fires after the current user has been unlinked from WordPress.com.
3026
		 *
3027
		 * @since 4.1.0
3028
		 *
3029
		 * @param int $user_id The current user's ID.
3030
		 */
3031
		do_action( 'jetpack_unlinked_user', $user_id );
3032
3033
		return true;
3034
	}
3035
3036
	/**
3037
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3038
	 */
3039
	public static function try_registration() {
3040
		// Let's get some testing in beta versions and such.
3041
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3042
			// Before attempting to connect, let's make sure that the domains are viable.
3043
			$domains_to_check = array_unique( array(
3044
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3045
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3046
			) );
3047
			foreach ( $domains_to_check as $domain ) {
3048
				$result = Jetpack_Data::is_usable_domain( $domain );
3049
				if ( is_wp_error( $result ) ) {
3050
					return $result;
3051
				}
3052
			}
3053
		}
3054
3055
		$result = Jetpack::register();
3056
3057
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3058
		if ( ! $result || is_wp_error( $result ) ) {
3059
			return $result;
3060
		} else {
3061
			return true;
3062
		}
3063
	}
3064
3065
	/**
3066
	 * Tracking an internal event log. Try not to put too much chaff in here.
3067
	 *
3068
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3069
	 */
3070
	public static function log( $code, $data = null ) {
3071
		// only grab the latest 200 entries
3072
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3073
3074
		// Append our event to the log
3075
		$log_entry = array(
3076
			'time'    => time(),
3077
			'user_id' => get_current_user_id(),
3078
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3079
			'code'    => $code,
3080
		);
3081
		// Don't bother storing it unless we've got some.
3082
		if ( ! is_null( $data ) ) {
3083
			$log_entry['data'] = $data;
3084
		}
3085
		$log[] = $log_entry;
3086
3087
		// Try add_option first, to make sure it's not autoloaded.
3088
		// @todo: Add an add_option method to Jetpack_Options
3089
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3090
			Jetpack_Options::update_option( 'log', $log );
3091
		}
3092
3093
		/**
3094
		 * Fires when Jetpack logs an internal event.
3095
		 *
3096
		 * @since 3.0.0
3097
		 *
3098
		 * @param array $log_entry {
3099
		 *	Array of details about the log entry.
3100
		 *
3101
		 *	@param string time Time of the event.
3102
		 *	@param int user_id ID of the user who trigerred the event.
3103
		 *	@param int blog_id Jetpack Blog ID.
3104
		 *	@param string code Unique name for the event.
3105
		 *	@param string data Data about the event.
3106
		 * }
3107
		 */
3108
		do_action( 'jetpack_log_entry', $log_entry );
3109
	}
3110
3111
	/**
3112
	 * Get the internal event log.
3113
	 *
3114
	 * @param $event (string) - only return the specific log events
3115
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3116
	 *
3117
	 * @return array of log events || WP_Error for invalid params
3118
	 */
3119
	public static function get_log( $event = false, $num = false ) {
3120
		if ( $event && ! is_string( $event ) ) {
3121
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3122
		}
3123
3124
		if ( $num && ! is_numeric( $num ) ) {
3125
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3126
		}
3127
3128
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3129
3130
		// If nothing set - act as it did before, otherwise let's start customizing the output
3131
		if ( ! $num && ! $event ) {
3132
			return $entire_log;
3133
		} else {
3134
			$entire_log = array_reverse( $entire_log );
3135
		}
3136
3137
		$custom_log_output = array();
3138
3139
		if ( $event ) {
3140
			foreach ( $entire_log as $log_event ) {
3141
				if ( $event == $log_event[ 'code' ] ) {
3142
					$custom_log_output[] = $log_event;
3143
				}
3144
			}
3145
		} else {
3146
			$custom_log_output = $entire_log;
3147
		}
3148
3149
		if ( $num ) {
3150
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3151
		}
3152
3153
		return $custom_log_output;
3154
	}
3155
3156
	/**
3157
	 * Log modification of important settings.
3158
	 */
3159
	public static function log_settings_change( $option, $old_value, $value ) {
3160
		switch( $option ) {
3161
			case 'jetpack_sync_non_public_post_stati':
3162
				self::log( $option, $value );
3163
				break;
3164
		}
3165
	}
3166
3167
	/**
3168
	 * Return stat data for WPCOM sync
3169
	 */
3170
	function get_stat_data() {
3171
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3172
		$additional_data = $this->get_additional_stat_data();
3173
3174
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3175
	}
3176
3177
	/**
3178
	 * Get additional stat data to sync to WPCOM
3179
	 */
3180
	function get_additional_stat_data( $prefix = '' ) {
3181
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3182
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3183
		$return["{$prefix}users"]          = count_users();
3184
		$return["{$prefix}site-count"]     = 0;
3185
		if ( function_exists( 'get_blog_count' ) ) {
3186
			$return["{$prefix}site-count"] = get_blog_count();
3187
		}
3188
		return $return;
3189
	}
3190
3191
	/* Admin Pages */
3192
3193
	function admin_init() {
3194
		// If the plugin is not connected, display a connect message.
3195
		if (
3196
			// the plugin was auto-activated and needs its candy
3197
			Jetpack_Options::get_option( 'do_activate' )
3198
		||
3199
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3200
			! Jetpack_Options::get_option( 'activated' )
3201
		) {
3202
			Jetpack::plugin_initialize();
3203
		}
3204
3205
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3206
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3207
				// Show connect notice on dashboard and plugins pages
3208
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3209
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3210
			}
3211
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3212
			// Upgrade: 1.1 -> 1.1.1
3213
			// Check and see if host can verify the Jetpack servers' SSL certificate
3214
			$args = array();
3215
			Jetpack_Client::_wp_remote_request(
3216
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3217
				$args,
3218
				true
3219
			);
3220
		} else {
3221
			// Show the notice on the Dashboard only for now
3222
3223
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3224
3225
			// Identity crisis notices
3226
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3227
		}
3228
3229
		// If the plugin has just been disconnected from WP.com, show the survey notice
3230
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3231
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3232
		}
3233
3234
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3235
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3236
		}
3237
3238
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3239
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3240
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3241
3242
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3243
			// Artificially throw errors in certain whitelisted cases during plugin activation
3244
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3245
3246
			// Kick off synchronization of user role when it changes
3247
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3248
		}
3249
3250
		// Jetpack Manage Activation Screen from .com
3251
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3252
	}
3253
3254
	function admin_body_class( $admin_body_class = '' ) {
3255
		$classes = explode( ' ', trim( $admin_body_class ) );
3256
3257
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3258
3259
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3260
		return " $admin_body_class ";
3261
	}
3262
3263
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3264
		return $admin_body_class . ' jetpack-pagestyles ';
3265
	}
3266
3267
	function prepare_connect_notice() {
3268
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3269
3270
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3271
3272
		if ( Jetpack::state( 'network_nag' ) )
3273
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3274
	}
3275
	/**
3276
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3277
	 *
3278
	 * @return null
3279
	 */
3280
	function prepare_manage_jetpack_notice() {
3281
3282
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3283
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3284
	}
3285
3286
	function manage_activate_screen() {
3287
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3288
	}
3289
	/**
3290
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3291
	 * This function artificially throws errors for such cases (whitelisted).
3292
	 *
3293
	 * @param string $plugin The activated plugin.
3294
	 */
3295
	function throw_error_on_activate_plugin( $plugin ) {
3296
		$active_modules = Jetpack::get_active_modules();
3297
3298
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3299
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3300
			$throw = false;
3301
3302
			// Try and make sure it really was the stats plugin
3303
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3304
				if ( 'stats.php' == basename( $plugin ) ) {
3305
					$throw = true;
3306
				}
3307
			} else {
3308
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3309
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3310
					$throw = true;
3311
				}
3312
			}
3313
3314
			if ( $throw ) {
3315
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3316
			}
3317
		}
3318
	}
3319
3320
	function intercept_plugin_error_scrape_init() {
3321
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3322
	}
3323
3324
	function intercept_plugin_error_scrape( $action, $result ) {
3325
		if ( ! $result ) {
3326
			return;
3327
		}
3328
3329
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3330
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3331
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3332
			}
3333
		}
3334
	}
3335
3336
	function add_remote_request_handlers() {
3337
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3338
	}
3339
3340
	function remote_request_handlers() {
3341
		switch ( current_filter() ) {
3342
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3343
			$response = $this->upload_handler();
3344
			break;
3345
		default :
3346
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3347
			break;
3348
		}
3349
3350
		if ( ! $response ) {
3351
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3352
		}
3353
3354
		if ( is_wp_error( $response ) ) {
3355
			$status_code       = $response->get_error_data();
3356
			$error             = $response->get_error_code();
3357
			$error_description = $response->get_error_message();
3358
3359
			if ( ! is_int( $status_code ) ) {
3360
				$status_code = 400;
3361
			}
3362
3363
			status_header( $status_code );
3364
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3365
		}
3366
3367
		status_header( 200 );
3368
		if ( true === $response ) {
3369
			exit;
3370
		}
3371
3372
		die( json_encode( (object) $response ) );
3373
	}
3374
3375
	function upload_handler() {
3376
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3377
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3378
		}
3379
3380
		$user = wp_authenticate( '', '' );
3381
		if ( ! $user || is_wp_error( $user ) ) {
3382
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3383
		}
3384
3385
		wp_set_current_user( $user->ID );
3386
3387
		if ( ! current_user_can( 'upload_files' ) ) {
3388
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3389
		}
3390
3391
		if ( empty( $_FILES ) ) {
3392
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3393
		}
3394
3395
		foreach ( array_keys( $_FILES ) as $files_key ) {
3396
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3397
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3398
			}
3399
		}
3400
3401
		$media_keys = array_keys( $_FILES['media'] );
3402
3403
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3404
		if ( ! $token || is_wp_error( $token ) ) {
3405
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3406
		}
3407
3408
		$uploaded_files = array();
3409
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3410
		unset( $GLOBALS['post'] );
3411
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3412
			$file = array();
3413
			foreach ( $media_keys as $media_key ) {
3414
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3415
			}
3416
3417
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3418
3419
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3420
			if ( $hmac_provided !== $hmac_file ) {
3421
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3422
				continue;
3423
			}
3424
3425
			$_FILES['.jetpack.upload.'] = $file;
3426
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3427
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3428
				$post_id = 0;
3429
			}
3430
			$attachment_id = media_handle_upload(
3431
				'.jetpack.upload.',
3432
				$post_id,
3433
				array(),
3434
				array(
3435
					'action' => 'jetpack_upload_file',
3436
				)
3437
			);
3438
3439
			if ( ! $attachment_id ) {
3440
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3441
			} elseif ( is_wp_error( $attachment_id ) ) {
3442
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3443
			} else {
3444
				$attachment = get_post( $attachment_id );
3445
				$uploaded_files[$index] = (object) array(
3446
					'id'   => (string) $attachment_id,
3447
					'file' => $attachment->post_title,
3448
					'url'  => wp_get_attachment_url( $attachment_id ),
3449
					'type' => $attachment->post_mime_type,
3450
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3451
				);
3452
			}
3453
		}
3454
		if ( ! is_null( $global_post ) ) {
3455
			$GLOBALS['post'] = $global_post;
3456
		}
3457
3458
		return $uploaded_files;
3459
	}
3460
3461
	/**
3462
	 * Add help to the Jetpack page
3463
	 *
3464
	 * @since Jetpack (1.2.3)
3465
	 * @return false if not the Jetpack page
3466
	 */
3467
	function admin_help() {
3468
		$current_screen = get_current_screen();
3469
3470
		// Overview
3471
		$current_screen->add_help_tab(
3472
			array(
3473
				'id'		=> 'home',
3474
				'title'		=> __( 'Home', 'jetpack' ),
3475
				'content'	=>
3476
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3477
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3478
					'<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>',
3479
			)
3480
		);
3481
3482
		// Screen Content
3483
		if ( current_user_can( 'manage_options' ) ) {
3484
			$current_screen->add_help_tab(
3485
				array(
3486
					'id'		=> 'settings',
3487
					'title'		=> __( 'Settings', 'jetpack' ),
3488
					'content'	=>
3489
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3490
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3491
						'<ol>' .
3492
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3493
							'<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>' .
3494
						'</ol>' .
3495
						'<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>'
3496
				)
3497
			);
3498
		}
3499
3500
		// Help Sidebar
3501
		$current_screen->set_help_sidebar(
3502
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3503
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3504
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3505
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3506
		);
3507
	}
3508
3509
	function admin_menu_css() {
3510
		wp_enqueue_style( 'jetpack-icons' );
3511
	}
3512
3513
	function admin_menu_order() {
3514
		return true;
3515
	}
3516
3517 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3518
		$jp_menu_order = array();
3519
3520
		foreach ( $menu_order as $index => $item ) {
3521
			if ( $item != 'jetpack' ) {
3522
				$jp_menu_order[] = $item;
3523
			}
3524
3525
			if ( $index == 0 ) {
3526
				$jp_menu_order[] = 'jetpack';
3527
			}
3528
		}
3529
3530
		return $jp_menu_order;
3531
	}
3532
3533
	function admin_head() {
3534 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3535
			/** This action is documented in class.jetpack-admin-page.php */
3536
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3537
	}
3538
3539
	function admin_banner_styles() {
3540
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3541
3542
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3543
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3544
		wp_style_add_data( 'jetpack', 'suffix', $min );
3545
	}
3546
3547
	function admin_scripts() {
3548
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3549
		wp_localize_script(
3550
			'jetpack-js',
3551
			'jetpackL10n',
3552
			array(
3553
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3554
				'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?",
3555
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3556
			)
3557
		);
3558
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3559
	}
3560
3561
	function plugin_action_links( $actions ) {
3562
3563
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3564
3565
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3566
			return array_merge(
3567
				$jetpack_home,
3568
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3569
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3570
				$actions
3571
				);
3572
			}
3573
3574
		return array_merge( $jetpack_home, $actions );
3575
	}
3576
3577
	function admin_connect_notice() {
3578
		// Don't show the connect notice anywhere but the plugins.php after activating
3579
		$current = get_current_screen();
3580
		if ( 'plugins' !== $current->parent_base )
3581
			return;
3582
3583
		if ( ! current_user_can( 'jetpack_connect' ) )
3584
			return;
3585
3586
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3587
		?>
3588
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3589
			<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>
3590
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3591
				<div class="jp-banner__content is-connection">
3592
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3593
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3594
				</div>
3595
				<div class="jp-banner__action-container is-connection">
3596
						<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3597
				</div>
3598 View Code Duplication
			<?php else : ?>
3599
				<div class="jp-banner__content">
3600
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3601
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3602
				</div>
3603
				<div class="jp-banner__action-container">
3604
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3605
				</div>
3606
			<?php endif; ?>
3607
		</div>
3608
3609
		<?php
3610
	}
3611
3612
	/**
3613
	 * This is the first banner
3614
	 * It should be visible only to user that can update the option
3615
	 * Are not connected
3616
	 *
3617
	 * @return null
3618
	 */
3619
	function admin_jetpack_manage_notice() {
3620
		$screen = get_current_screen();
3621
3622
		// Don't show the connect notice on the jetpack settings page.
3623
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3624
			return;
3625
3626
		// Only show it if don't have the managment option set.
3627
		// And not dismissed it already.
3628
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3629
			return;
3630
		}
3631
3632
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3633
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3634
		/**
3635
		 * I think it would be great to have different wordsing depending on where you are
3636
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3637
		 * etc..
3638
		 */
3639
3640
		?>
3641
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3642
			<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>
3643
			<div class="jp-banner__content">
3644
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3645
				<p><?php printf( __( 'Manage multiple sites from one dashboard at wordpress.com/sites. Enabling allows all existing, connected Administrators to modify your site from WordPress.com. <a href="%s" target="_blank">Learn More</a>.', 'jetpack' ), 'http://jetpack.com/support/site-management' ); ?></p>
3646
			</div>
3647
			<div class="jp-banner__action-container is-opt-in">
3648
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3649
			</div>
3650
		</div>
3651
		<?php
3652
	}
3653
3654
	/**
3655
	 * Returns the url that the user clicks to remove the notice for the big banner
3656
	 * @return (string)
3657
	 */
3658
	function opt_out_jetpack_manage_url() {
3659
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3660
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3661
	}
3662
	/**
3663
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3664
	 * @return (string)
3665
	 */
3666
	function opt_in_jetpack_manage_url() {
3667
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3668
	}
3669
3670
	function opt_in_jetpack_manage_notice() {
3671
		?>
3672
		<div class="wrap">
3673
			<div id="message" class="jetpack-message is-opt-in">
3674
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'http://jetpack.com/support/site-management' ); ?>
3675
			</div>
3676
		</div>
3677
		<?php
3678
3679
	}
3680
	/**
3681
	 * Determines whether to show the notice of not true = display notice
3682
	 * @return (bool)
3683
	 */
3684
	function can_display_jetpack_manage_notice() {
3685
		// never display the notice to users that can't do anything about it anyways
3686
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3687
			return false;
3688
3689
		// don't display if we are in development more
3690
		if( Jetpack::is_development_mode() ) {
3691
			return false;
3692
		}
3693
		// don't display if the site is private
3694
		if(  ! Jetpack_Options::get_option( 'public' ) )
3695
			return false;
3696
3697
		/**
3698
		 * Should the Jetpack Remote Site Management notice be displayed.
3699
		 *
3700
		 * @since 3.3.0
3701
		 *
3702
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3703
		 */
3704
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3705
	}
3706
3707
	function network_connect_notice() {
3708
		?>
3709
		<div id="message" class="updated jetpack-message">
3710
			<div class="squeezer">
3711
				<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>
3712
			</div>
3713
		</div>
3714
		<?php
3715
	}
3716
3717
	public static function jetpack_comment_notice() {
3718
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3719
			return '';
3720
		}
3721
3722
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3723
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3724
3725
		if ( $jetpack_old_version ) {
3726
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3727
				return '';
3728
			}
3729
		}
3730
3731
		if ( $jetpack_new_version ) {
3732
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3733
				return '';
3734
			}
3735
		}
3736
3737
		return '<br /><br />' . sprintf(
3738
			__( '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' ),
3739
			wp_nonce_url(
3740
				Jetpack::admin_url(
3741
					array(
3742
						'page'   => 'jetpack',
3743
						'action' => 'activate',
3744
						'module' => 'comments',
3745
					)
3746
				),
3747
				'jetpack_activate-comments'
3748
			),
3749
			__( 'click here', 'jetpack' )
3750
		);
3751
	}
3752
3753
	/**
3754
	 * Show the survey link when the user has just disconnected Jetpack.
3755
	 */
3756
	function disconnect_survey_notice() {
3757
		?>
3758
		<div class="wrap">
3759
			<div id="message" class="jetpack-message stay-visible">
3760
				<div class="squeezer">
3761
					<h2>
3762
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3763
						<br />
3764
						<?php echo sprintf(
3765
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3766
							'https://jetpack.com/survey-disconnected/',
3767
							'_blank'
3768
						); ?>
3769
					</h2>
3770
				</div>
3771
			</div>
3772
		</div>
3773
		<?php
3774
	}
3775
3776
	/*
3777
	 * Registration flow:
3778
	 * 1 - ::admin_page_load() action=register
3779
	 * 2 - ::try_registration()
3780
	 * 3 - ::register()
3781
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3782
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3783
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3784
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3785
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3786
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3787
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3788
	 *       jetpack_id, jetpack_secret, jetpack_public
3789
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3790
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3791
	 * 5 - user logs in with WP.com account
3792
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3793
	 *		- Jetpack_Client_Server::authorize()
3794
	 *		- Jetpack_Client_Server::get_token()
3795
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3796
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3797
	 *			- which responds with access_token, token_type, scope
3798
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3799
	 *		- Jetpack::activate_default_modules()
3800
	 *     		- Deactivates deprecated plugins
3801
	 *     		- Activates all default modules
3802
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3803
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3804
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3805
	 *     Done!
3806
	 */
3807
3808
	/**
3809
	 * Handles the page load events for the Jetpack admin page
3810
	 */
3811
	function admin_page_load() {
3812
		$error = false;
3813
3814
		// Make sure we have the right body class to hook stylings for subpages off of.
3815
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3816
3817
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3818
			// Should only be used in intermediate redirects to preserve state across redirects
3819
			Jetpack::restate();
3820
		}
3821
3822
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3823
			// User clicked in the iframe to link their accounts
3824
			if ( ! Jetpack::is_user_connected() ) {
3825
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3826
				if ( isset( $_GET['notes_iframe'] ) )
3827
					$connect_url .= '&notes_iframe';
3828
				wp_redirect( $connect_url );
3829
				exit;
3830
			} else {
3831
				Jetpack::state( 'message', 'already_authorized' );
3832
				wp_safe_redirect( Jetpack::admin_url() );
3833
				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...
3834
			}
3835
		}
3836
3837
3838
		if ( isset( $_GET['action'] ) ) {
3839
			switch ( $_GET['action'] ) {
3840
			case 'authorize':
3841
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3842
					Jetpack::state( 'message', 'already_authorized' );
3843
					wp_safe_redirect( Jetpack::admin_url() );
3844
					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...
3845
				}
3846
				Jetpack::log( 'authorize' );
3847
				$client_server = new Jetpack_Client_Server;
3848
				$client_server->client_authorize();
3849
				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...
3850
			case 'register' :
3851
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3852
					$error = 'cheatin';
3853
					break;
3854
				}
3855
				check_admin_referer( 'jetpack-register' );
3856
				Jetpack::log( 'register' );
3857
				Jetpack::maybe_set_version_option();
3858
				$registered = Jetpack::try_registration();
3859
				if ( is_wp_error( $registered ) ) {
3860
					$error = $registered->get_error_code();
3861
					Jetpack::state( 'error_description', $registered->get_error_message() );
3862
					break;
3863
				}
3864
3865
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3866
3867
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3868
				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...
3869
			case 'activate' :
3870
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3871
					$error = 'cheatin';
3872
					break;
3873
				}
3874
3875
				$module = stripslashes( $_GET['module'] );
3876
				check_admin_referer( "jetpack_activate-$module" );
3877
				Jetpack::log( 'activate', $module );
3878
				Jetpack::activate_module( $module );
3879
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3880
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3881
				exit;
3882
			case 'activate_default_modules' :
3883
				check_admin_referer( 'activate_default_modules' );
3884
				Jetpack::log( 'activate_default_modules' );
3885
				Jetpack::restate();
3886
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3887
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3888
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3889
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3890
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3891
				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...
3892
			case 'disconnect' :
3893
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3894
					$error = 'cheatin';
3895
					break;
3896
				}
3897
3898
				check_admin_referer( 'jetpack-disconnect' );
3899
				Jetpack::log( 'disconnect' );
3900
				Jetpack::disconnect();
3901
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3902
				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...
3903
			case 'reconnect' :
3904
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3905
					$error = 'cheatin';
3906
					break;
3907
				}
3908
3909
				check_admin_referer( 'jetpack-reconnect' );
3910
				Jetpack::log( 'reconnect' );
3911
				$this->disconnect();
3912
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3913
				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...
3914 View Code Duplication
			case 'deactivate' :
3915
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3916
					$error = 'cheatin';
3917
					break;
3918
				}
3919
3920
				$modules = stripslashes( $_GET['module'] );
3921
				check_admin_referer( "jetpack_deactivate-$modules" );
3922
				foreach ( explode( ',', $modules ) as $module ) {
3923
					Jetpack::log( 'deactivate', $module );
3924
					Jetpack::deactivate_module( $module );
3925
					Jetpack::state( 'message', 'module_deactivated' );
3926
				}
3927
				Jetpack::state( 'module', $modules );
3928
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3929
				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...
3930
			case 'unlink' :
3931
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3932
				check_admin_referer( 'jetpack-unlink' );
3933
				Jetpack::log( 'unlink' );
3934
				$this->unlink_user();
3935
				Jetpack::state( 'message', 'unlinked' );
3936
				if ( 'sub-unlink' == $redirect ) {
3937
					wp_safe_redirect( admin_url() );
3938
				} else {
3939
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3940
				}
3941
				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...
3942
			default:
3943
				/**
3944
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3945
				 *
3946
				 * @since 2.6.0
3947
				 *
3948
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3949
				 */
3950
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3951
			}
3952
		}
3953
3954
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3955
			self::activate_new_modules( true );
3956
		}
3957
3958
		switch ( $error ) {
3959
		case 'cheatin' :
3960
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3961
			break;
3962
		case 'access_denied' :
3963
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'http://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
3964
			break;
3965
		case 'wrong_state' :
3966
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3967
			break;
3968
		case 'invalid_client' :
3969
			// @todo re-register instead of deactivate/reactivate
3970
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3971
			break;
3972
		case 'invalid_grant' :
3973
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3974
			break;
3975
		case 'site_inaccessible' :
3976
		case 'site_requires_authorization' :
3977
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3978
			break;
3979
		case 'module_activation_failed' :
3980
			$module = Jetpack::state( 'module' );
3981
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3982
				$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'] );
3983
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3984
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3985
				}
3986
			} else {
3987
				$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' );
3988
			}
3989
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
3990
				$this->error .= "<br />\n";
3991
				$this->error .= $php_errors;
3992
			}
3993
			break;
3994
		case 'master_user_required' :
3995
			$module = Jetpack::state( 'module' );
3996
			$module_name = '';
3997
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3998
				$module_name = $mod['name'];
3999
			}
4000
4001
			$master_user = Jetpack_Options::get_option( 'master_user' );
4002
			$master_userdata = get_userdata( $master_user ) ;
4003
			if ( $master_userdata ) {
4004
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
4005
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
4006
				} else {
4007
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
4008
				}
4009
				$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 ) );
4010
4011
			} else {
4012
				$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 );
4013
			}
4014
			break;
4015
		case 'not_public' :
4016
			$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' );
4017
			break;
4018
		case 'wpcom_408' :
4019
		case 'wpcom_5??' :
4020
		case 'wpcom_bad_response' :
4021
		case 'wpcom_outage' :
4022
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
4023
			break;
4024
		case 'register_http_request_failed' :
4025
		case 'token_http_request_failed' :
4026
			$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>" );
4027
			break;
4028
		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...
4029
			if ( empty( $error ) ) {
4030
				break;
4031
			}
4032
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
4033
			// no break: fall through
4034
		case 'no_role' :
4035
		case 'no_cap' :
4036
		case 'no_code' :
4037
		case 'no_state' :
4038
		case 'invalid_state' :
4039
		case 'invalid_request' :
4040
		case 'invalid_scope' :
4041
		case 'unsupported_response_type' :
4042
		case 'invalid_token' :
4043
		case 'no_token' :
4044
		case 'missing_secrets' :
4045
		case 'home_missing' :
4046
		case 'siteurl_missing' :
4047
		case 'gmt_offset_missing' :
4048
		case 'site_name_missing' :
4049
		case 'secret_1_missing' :
4050
		case 'secret_2_missing' :
4051
		case 'site_lang_missing' :
4052
		case 'home_malformed' :
4053
		case 'siteurl_malformed' :
4054
		case 'gmt_offset_malformed' :
4055
		case 'timezone_string_malformed' :
4056
		case 'site_name_malformed' :
4057
		case 'secret_1_malformed' :
4058
		case 'secret_2_malformed' :
4059
		case 'site_lang_malformed' :
4060
		case 'secrets_mismatch' :
4061
		case 'verify_secret_1_missing' :
4062
		case 'verify_secret_1_malformed' :
4063
		case 'verify_secrets_missing' :
4064
		case 'verify_secrets_mismatch' :
4065
			$error = esc_html( $error );
4066
			$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>" );
4067
			if ( ! Jetpack::is_active() ) {
4068
				$this->error .= '<br />';
4069
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4070
			}
4071
			break;
4072
		}
4073
4074
		$message_code = Jetpack::state( 'message' );
4075
4076
		$active_state = Jetpack::state( 'activated_modules' );
4077
		if ( ! empty( $active_state ) ) {
4078
			$available    = Jetpack::get_available_modules();
4079
			$active_state = explode( ',', $active_state );
4080
			$active_state = array_intersect( $active_state, $available );
4081
			if ( count( $active_state ) ) {
4082
				foreach ( $active_state as $mod ) {
4083
					$this->stat( 'module-activated', $mod );
4084
				}
4085
			} else {
4086
				$active_state = false;
4087
			}
4088
		}
4089
		if( Jetpack::state( 'optin-manage' ) ) {
4090
			$activated_manage = $message_code;
4091
			$message_code = 'jetpack-manage';
4092
4093
		}
4094
		switch ( $message_code ) {
4095
		case 'modules_activated' :
4096
			$this->message = sprintf(
4097
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4098
				JETPACK__VERSION
4099
			);
4100
4101
			if ( $active_state ) {
4102
				$titles = array();
4103 View Code Duplication
				foreach ( $active_state as $mod ) {
4104
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4105
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4106
					}
4107
				}
4108
				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...
4109
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4110
				}
4111
			}
4112
4113
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4114
				$titles = array();
4115 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4116
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4117
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4118
					}
4119
				}
4120
				if ( $titles ) {
4121
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4122
				}
4123
			}
4124
4125
			$this->message .= Jetpack::jetpack_comment_notice();
4126
			break;
4127
		case 'jetpack-manage':
4128
			$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>';
4129
			if ( $activated_manage ) {
4130
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4131
			}
4132
			break;
4133
		case 'module_activated' :
4134
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4135
				$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'] );
4136
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4137
			}
4138
			break;
4139
4140
		case 'module_deactivated' :
4141
			$modules = Jetpack::state( 'module' );
4142
			if ( ! $modules ) {
4143
				break;
4144
			}
4145
4146
			$module_names = array();
4147
			foreach ( explode( ',', $modules ) as $module_slug ) {
4148
				$module = Jetpack::get_module( $module_slug );
4149
				if ( $module ) {
4150
					$module_names[] = $module['name'];
4151
				}
4152
4153
				$this->stat( 'module-deactivated', $module_slug );
4154
			}
4155
4156
			if ( ! $module_names ) {
4157
				break;
4158
			}
4159
4160
			$this->message = wp_sprintf(
4161
				_nx(
4162
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4163
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4164
					count( $module_names ),
4165
					'%l = list of Jetpack module/feature names',
4166
					'jetpack'
4167
				),
4168
				$module_names
4169
			);
4170
			break;
4171
4172
		case 'module_configured' :
4173
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4174
			break;
4175
4176
		case 'already_authorized' :
4177
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4178
			break;
4179
4180
		case 'authorized' :
4181
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4182
			$this->message .= Jetpack::jetpack_comment_notice();
4183
			break;
4184
4185
		case 'linked' :
4186
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4187
			$this->message .= Jetpack::jetpack_comment_notice();
4188
			break;
4189
4190
		case 'unlinked' :
4191
			$user = wp_get_current_user();
4192
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4193
			break;
4194
4195
		case 'switch_master' :
4196
			global $current_user;
4197
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4198
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4199
			if ( $is_master_user ) {
4200
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4201
			} else {
4202
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4203
			}
4204
			break;
4205
		}
4206
4207
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4208
4209
		if ( ! empty( $deactivated_plugins ) ) {
4210
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4211
			$deactivated_titles  = array();
4212
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4213
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4214
					continue;
4215
				}
4216
4217
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4218
			}
4219
4220
			if ( $deactivated_titles ) {
4221
				if ( $this->message ) {
4222
					$this->message .= "<br /><br />\n";
4223
				}
4224
4225
				$this->message .= wp_sprintf(
4226
					_n(
4227
						'Jetpack contains the most recent version of the old %l plugin.',
4228
						'Jetpack contains the most recent versions of the old %l plugins.',
4229
						count( $deactivated_titles ),
4230
						'jetpack'
4231
					),
4232
					$deactivated_titles
4233
				);
4234
4235
				$this->message .= "<br />\n";
4236
4237
				$this->message .= _n(
4238
					'The old version has been deactivated and can be removed from your site.',
4239
					'The old versions have been deactivated and can be removed from your site.',
4240
					count( $deactivated_titles ),
4241
					'jetpack'
4242
				);
4243
			}
4244
		}
4245
4246
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4247
4248
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4249
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4250
		}
4251
4252 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4253
			/**
4254
			 * Fires when a module configuration page is loaded.
4255
			 * The dynamic part of the hook is the configure parameter from the URL.
4256
			 *
4257
			 * @since 1.1.0
4258
			 */
4259
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4260
		}
4261
4262
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4263
	}
4264
4265
	function admin_notices() {
4266
4267
		if ( $this->error ) {
4268
?>
4269
<div id="message" class="jetpack-message jetpack-err">
4270
	<div class="squeezer">
4271
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4272
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4273
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4274
<?php	endif; ?>
4275
	</div>
4276
</div>
4277
<?php
4278
		}
4279
4280
		if ( $this->message ) {
4281
?>
4282
<div id="message" class="jetpack-message">
4283
	<div class="squeezer">
4284
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4285
	</div>
4286
</div>
4287
<?php
4288
		}
4289
4290
		if ( $this->privacy_checks ) :
4291
			$module_names = $module_slugs = array();
4292
4293
			$privacy_checks = explode( ',', $this->privacy_checks );
4294
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4295
			foreach ( $privacy_checks as $module_slug ) {
4296
				$module = Jetpack::get_module( $module_slug );
4297
				if ( ! $module ) {
4298
					continue;
4299
				}
4300
4301
				$module_slugs[] = $module_slug;
4302
				$module_names[] = "<strong>{$module['name']}</strong>";
4303
			}
4304
4305
			$module_slugs = join( ',', $module_slugs );
4306
?>
4307
<div id="message" class="jetpack-message jetpack-err">
4308
	<div class="squeezer">
4309
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4310
		<p><?php
4311
			echo wp_kses(
4312
				wptexturize(
4313
					wp_sprintf(
4314
						_nx(
4315
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4316
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4317
							count( $privacy_checks ),
4318
							'%l = list of Jetpack module/feature names',
4319
							'jetpack'
4320
						),
4321
						$module_names
4322
					)
4323
				),
4324
				array( 'strong' => true )
4325
			);
4326
4327
			echo "\n<br />\n";
4328
4329
			echo wp_kses(
4330
				sprintf(
4331
					_nx(
4332
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4333
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4334
						count( $privacy_checks ),
4335
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4336
						'jetpack'
4337
					),
4338
					wp_nonce_url(
4339
						Jetpack::admin_url(
4340
							array(
4341
								'page'   => 'jetpack',
4342
								'action' => 'deactivate',
4343
								'module' => urlencode( $module_slugs ),
4344
							)
4345
						),
4346
						"jetpack_deactivate-$module_slugs"
4347
					),
4348
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4349
				),
4350
				array( 'a' => array( 'href' => true, 'title' => true ) )
4351
			);
4352
		?></p>
4353
	</div>
4354
</div>
4355
<?php endif;
4356
	// only display the notice if the other stuff is not there
4357
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4358
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4359
			$this->opt_in_jetpack_manage_notice();
4360
		}
4361
	}
4362
4363
	/**
4364
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4365
	 */
4366
	function stat( $group, $detail ) {
4367
		if ( ! isset( $this->stats[ $group ] ) )
4368
			$this->stats[ $group ] = array();
4369
		$this->stats[ $group ][] = $detail;
4370
	}
4371
4372
	/**
4373
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4374
	 */
4375
	function do_stats( $method = '' ) {
4376
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4377
			foreach ( $this->stats as $group => $stats ) {
4378
				if ( is_array( $stats ) && count( $stats ) ) {
4379
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4380
					if ( 'server_side' === $method ) {
4381
						self::do_server_side_stat( $args );
4382
					} else {
4383
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4384
					}
4385
				}
4386
				unset( $this->stats[ $group ] );
4387
			}
4388
		}
4389
	}
4390
4391
	/**
4392
	 * Runs stats code for a one-off, server-side.
4393
	 *
4394
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4395
	 *
4396
	 * @return bool If it worked.
4397
	 */
4398
	static function do_server_side_stat( $args ) {
4399
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4400
		if ( is_wp_error( $response ) )
4401
			return false;
4402
4403
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4404
			return false;
4405
4406
		return true;
4407
	}
4408
4409
	/**
4410
	 * Builds the stats url.
4411
	 *
4412
	 * @param $args array|string The arguments to append to the URL.
4413
	 *
4414
	 * @return string The URL to be pinged.
4415
	 */
4416
	static function build_stats_url( $args ) {
4417
		$defaults = array(
4418
			'v'    => 'wpcom2',
4419
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4420
		);
4421
		$args     = wp_parse_args( $args, $defaults );
4422
		/**
4423
		 * Filter the URL used as the Stats tracking pixel.
4424
		 *
4425
		 * @since 2.3.2
4426
		 *
4427
		 * @param string $url Base URL used as the Stats tracking pixel.
4428
		 */
4429
		$base_url = apply_filters(
4430
			'jetpack_stats_base_url',
4431
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4432
		);
4433
		$url      = add_query_arg( $args, $base_url );
4434
		return $url;
4435
	}
4436
4437
	function translate_current_user_to_role() {
4438
		foreach ( $this->capability_translations as $role => $cap ) {
4439
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4440
				return $role;
4441
			}
4442
		}
4443
4444
		return false;
4445
	}
4446
4447
	function translate_role_to_cap( $role ) {
4448
		if ( ! isset( $this->capability_translations[$role] ) ) {
4449
			return false;
4450
		}
4451
4452
		return $this->capability_translations[$role];
4453
	}
4454
4455
	function sign_role( $role ) {
4456
		if ( ! $user_id = (int) get_current_user_id() ) {
4457
			return false;
4458
		}
4459
4460
		$token = Jetpack_Data::get_access_token();
4461
		if ( ! $token || is_wp_error( $token ) ) {
4462
			return false;
4463
		}
4464
4465
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4466
	}
4467
4468
4469
	/**
4470
	 * Builds a URL to the Jetpack connection auth page
4471
	 *
4472
	 * @since 3.9.5
4473
	 *
4474
	 * @param bool $raw If true, URL will not be escaped.
4475
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4476
	 *                              If string, will be a custom redirect.
4477
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4478
	 *
4479
	 * @return string Connect URL
4480
	 */
4481
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4482
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4483
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4484
			if( is_network_admin() ) {
4485
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4486
			    'admin.php?page=jetpack-settings' ), $url );
4487
			}
4488
		} else {
4489
			require_once JETPACK__GLOTPRESS_LOCALES_PATH;
4490
			$role = $this->translate_current_user_to_role();
4491
			$signed_role = $this->sign_role( $role );
4492
4493
			$user = wp_get_current_user();
4494
4495
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4496
4497
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4498
4499
			if( isset( $_REQUEST['is_multisite'] ) ) {
4500
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4501
			}
4502
4503
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4504
			@list( $secret ) = explode( ':', $secrets );
4505
4506
			$args = urlencode_deep(
4507
				array(
4508
					'response_type' => 'code',
4509
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4510
					'redirect_uri'  => add_query_arg(
4511
						array(
4512
							'action'   => 'authorize',
4513
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4514
							'redirect' => urlencode( $redirect ),
4515
						),
4516
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4517
					),
4518
					'state'         => $user->ID,
4519
					'scope'         => $signed_role,
4520
					'user_email'    => $user->user_email,
4521
					'user_login'    => $user->user_login,
4522
					'is_active'     => Jetpack::is_active(),
4523
					'jp_version'    => JETPACK__VERSION,
4524
					'auth_type'     => 'calypso',
4525
					'secret'        => $secret,
4526
					'locale'        => isset( $gp_locale->slug ) ? $gp_locale->slug : '',
4527
					'blogname'      => get_option( 'blogname' ),
4528
				)
4529
			);
4530
4531
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4532
		}
4533
4534
		if ( $from ) {
4535
			$url = add_query_arg( 'from', $from, $url );
4536
		}
4537
4538
		if ( isset( $_GET['calypso_env'] ) ) {
4539
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4540
		}
4541
4542
		return $raw ? $url : esc_url( $url );
4543
	}
4544
4545
	function build_reconnect_url( $raw = false ) {
4546
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4547
		return $raw ? $url : esc_url( $url );
4548
	}
4549
4550
	public static function admin_url( $args = null ) {
4551
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4552
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4553
		return $url;
4554
	}
4555
4556
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4557
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4558
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4559
	}
4560
4561
	function dismiss_jetpack_notice() {
4562
4563
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4564
			return;
4565
		}
4566
4567
		switch( $_GET['jetpack-notice'] ) {
4568
			case 'dismiss':
4569
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4570
4571
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4572
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4573
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4574
				}
4575
				break;
4576 View Code Duplication
			case 'jetpack-manage-opt-out':
4577
4578
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4579
					// Don't show the banner again
4580
4581
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4582
					// redirect back to the page that had the notice
4583
					if ( wp_get_referer() ) {
4584
						wp_safe_redirect( wp_get_referer() );
4585
					} else {
4586
						// Take me to Jetpack
4587
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4588
					}
4589
				}
4590
				break;
4591 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4592
4593
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4594
					// Don't show the banner again
4595
4596
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4597
					// redirect back to the page that had the notice
4598
					if ( wp_get_referer() ) {
4599
						wp_safe_redirect( wp_get_referer() );
4600
					} else {
4601
						// Take me to Jetpack
4602
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4603
					}
4604
				}
4605
				break;
4606
			case 'jetpack-manage-opt-in':
4607
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4608
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4609
4610
					$redirection_url = Jetpack::admin_url();
4611
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4612
4613
					// Don't redirect form the Jetpack Setting Page
4614
					$referer_parsed = parse_url ( wp_get_referer() );
4615
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4616
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4617
						// Take the user to Jetpack home except when on the setting page
4618
						$redirection_url = wp_get_referer();
4619
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4620
					}
4621
					// Also update the JSON API FULL MANAGEMENT Option
4622
					Jetpack::activate_module( 'manage', false, false );
4623
4624
					// Special Message when option in.
4625
					Jetpack::state( 'optin-manage', 'true' );
4626
					// Activate the Module if not activated already
4627
4628
					// Redirect properly
4629
					wp_safe_redirect( $redirection_url );
4630
4631
				}
4632
				break;
4633
		}
4634
	}
4635
4636
	function debugger_page() {
4637
		nocache_headers();
4638
		if ( ! current_user_can( 'manage_options' ) ) {
4639
			die( '-1' );
4640
		}
4641
		Jetpack_Debugger::jetpack_debug_display_handler();
4642
		exit;
4643
	}
4644
4645
	public static function admin_screen_configure_module( $module_id ) {
4646
4647
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4648
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4649
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4650
				/**
4651
				 * Fires to diplay a custom module activation screen.
4652
				 *
4653
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4654
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4655
				 *
4656
				 * @module manage
4657
				 *
4658
				 * @since 3.8.0
4659
				 *
4660
				 * @param int $module_id Module ID.
4661
				 */
4662
				do_action( 'display_activate_module_setting_' . $module_id );
4663
			} else {
4664
				self::display_activate_module_link( $module_id );
4665
			}
4666
4667
			return false;
4668
		} ?>
4669
4670
		<div id="jp-settings-screen" style="position: relative">
4671
			<h3>
4672
			<?php
4673
				$module = Jetpack::get_module( $module_id );
4674
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4675
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4676
			?>
4677
			</h3>
4678
			<?php
4679
				/**
4680
				 * Fires within the displayed message when a feature configuation is updated.
4681
				 *
4682
				 * @since 3.4.0
4683
				 *
4684
				 * @param int $module_id Module ID.
4685
				 */
4686
				do_action( 'jetpack_notices_update_settings', $module_id );
4687
				/**
4688
				 * Fires when a feature configuation screen is loaded.
4689
				 * The dynamic part of the hook, $module_id, is the module ID.
4690
				 *
4691
				 * @since 1.1.0
4692
				 */
4693
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4694
			?>
4695
		</div><?php
4696
	}
4697
4698
	/**
4699
	 * Display link to activate the module to see the settings screen.
4700
	 * @param  string $module_id
4701
	 * @return null
4702
	 */
4703
	public static function display_activate_module_link( $module_id ) {
4704
4705
		$info =  Jetpack::get_module( $module_id );
4706
		$extra = '';
4707
		$activate_url = wp_nonce_url(
4708
				Jetpack::admin_url(
4709
					array(
4710
						'page'   => 'jetpack',
4711
						'action' => 'activate',
4712
						'module' => $module_id,
4713
					)
4714
				),
4715
				"jetpack_activate-$module_id"
4716
			);
4717
4718
		?>
4719
4720
		<div class="wrap configure-module">
4721
			<div id="jp-settings-screen">
4722
				<?php
4723
				if ( $module_id == 'json-api' ) {
4724
4725
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4726
4727
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4728
4729
					$info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'http://jetpack.com/support/site-management' );
4730
4731
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4732
				} ?>
4733
4734
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4735
				<div class="narrow">
4736
					<p><?php echo  $info['description']; ?></p>
4737
					<?php if( $extra ) { ?>
4738
					<p><?php echo esc_html( $extra ); ?></p>
4739
					<?php } ?>
4740
					<p>
4741
						<?php
4742
						if( wp_get_referer() ) {
4743
							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() );
4744
						} else {
4745
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4746
						} ?>
4747
					</p>
4748
				</div>
4749
4750
			</div>
4751
		</div>
4752
4753
		<?php
4754
	}
4755
4756
	public static function sort_modules( $a, $b ) {
4757
		if ( $a['sort'] == $b['sort'] )
4758
			return 0;
4759
4760
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4761
	}
4762
4763 View Code Duplication
	function sync_reindex_trigger() {
4764
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4765
			echo json_encode( $this->sync->reindex_trigger() );
4766
		} else {
4767
			echo '{"status":"ERROR"}';
4768
		}
4769
		exit;
4770
	}
4771
4772 View Code Duplication
	function sync_reindex_status(){
4773
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4774
			echo json_encode( $this->sync->reindex_status() );
4775
		} else {
4776
			echo '{"status":"ERROR"}';
4777
		}
4778
		exit;
4779
	}
4780
4781
/* Client API */
4782
4783
	/**
4784
	 * Returns the requested Jetpack API URL
4785
	 *
4786
	 * @return string
4787
	 */
4788
	public static function api_url( $relative_url ) {
4789
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4790
	}
4791
4792
	/**
4793
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4794
	 */
4795
	public static function fix_url_for_bad_hosts( $url ) {
4796
		if ( 0 !== strpos( $url, 'https://' ) ) {
4797
			return $url;
4798
		}
4799
4800
		switch ( JETPACK_CLIENT__HTTPS ) {
4801
			case 'ALWAYS' :
4802
				return $url;
4803
			case 'NEVER' :
4804
				return set_url_scheme( $url, 'http' );
4805
			// default : case 'AUTO' :
4806
		}
4807
4808
		// we now return the unmodified SSL URL by default, as a security precaution
4809
		return $url;
4810
	}
4811
4812
	/**
4813
	 * Checks to see if the URL is using SSL to connect with Jetpack
4814
	 *
4815
	 * @since 2.3.3
4816
	 * @return boolean
4817
	 */
4818
	public static function permit_ssl( $force_recheck = false ) {
4819
		// Do some fancy tests to see if ssl is being supported
4820
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4821
			$message = '';
4822
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4823
				$ssl = 0;
4824
			} else {
4825
				switch ( JETPACK_CLIENT__HTTPS ) {
4826
					case 'NEVER':
4827
						$ssl = 0;
4828
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4829
						break;
4830
					case 'ALWAYS':
4831
					case 'AUTO':
4832
					default:
4833
						$ssl = 1;
4834
						break;
4835
				}
4836
4837
				// If it's not 'NEVER', test to see
4838
				if ( $ssl ) {
4839
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4840
						$ssl = 0;
4841
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4842
					} else {
4843
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4844
						if ( is_wp_error( $response ) ) {
4845
							$ssl = 0;
4846
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4847
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4848
							$ssl = 0;
4849
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4850
						}
4851
					}
4852
				}
4853
			}
4854
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4855
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4856
		}
4857
4858
		return (bool) $ssl;
4859
	}
4860
4861
	/*
4862
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4863
	 */
4864
	public function alert_auto_ssl_fail() {
4865
		if ( ! current_user_can( 'manage_options' ) )
4866
			return;
4867
		?>
4868
4869
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4870
			<div class="jp-banner__content">
4871
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4872
				<p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
4873
				<p>
4874
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4875
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4876
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4877
				</p>
4878
				<p>
4879
					<?php printf( __( 'For more help, try our <a href="$1%s">connection debugger</a> or <a href="$2%s" target="_blank">troubleshooting tips</a>', 'jetpack' ), 
4880
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4881
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4882
				</p>
4883
			</div>
4884
		</div>
4885
		<style>
4886
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4887
		</style>
4888
		<script type="text/javascript">
4889
			jQuery( document ).ready( function( $ ) {
4890
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4891
					var $this = $( this );
4892
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4893
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4894
					e.preventDefault();
4895
					$.post( '/wp-json/jetpack/v4/recheck-ssl' )
4896
					  .done( function( response ) {
4897
					  	if ( response.enabled ) {
4898
					  		$( '#jetpack-ssl-warning' ).hide();
4899
					  	} else {
4900
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4901
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4902
					  	}
4903
					  }.bind( $this ) );
4904
				} );
4905
			} );
4906
		</script>
4907
4908
		<?php
4909
	}
4910
4911
	/**
4912
	 * Returns the Jetpack XML-RPC API
4913
	 *
4914
	 * @return string
4915
	 */
4916
	public static function xmlrpc_api_url() {
4917
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4918
		return untrailingslashit( $base ) . '/xmlrpc.php';
4919
	}
4920
4921
	/**
4922
	 * Creates two secret tokens and the end of life timestamp for them.
4923
	 *
4924
	 * Note these tokens are unique per call, NOT static per site for connecting.
4925
	 *
4926
	 * @since 2.6
4927
	 * @return array
4928
	 */
4929
	public function generate_secrets( $action ) {
4930
	    $secret = wp_generate_password( 32, false ) // secret_1
4931
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4932
	    		. ':' . ( time() + 600 ) // eol ( End of Life )
4933
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4934
		Jetpack_Options::update_option( $action, $secret );
4935
4936
	    return Jetpack_Options::get_option( $action );
4937
	}
4938
4939
	/**
4940
	 * Builds the timeout limit for queries talking with the wpcom servers.
4941
	 *
4942
	 * Based on local php max_execution_time in php.ini
4943
	 *
4944
	 * @since 2.6
4945
	 * @return int
4946
	 **/
4947
	public function get_remote_query_timeout_limit() {
4948
	    $timeout = (int) ini_get( 'max_execution_time' );
4949
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4950
		$timeout = 30;
4951
	    return intval( $timeout / 2 );
4952
	}
4953
4954
4955
	/**
4956
	 * Takes the response from the Jetpack register new site endpoint and
4957
	 * verifies it worked properly.
4958
	 *
4959
	 * @since 2.6
4960
	 * @return true or Jetpack_Error
4961
	 **/
4962
	public function validate_remote_register_response( $response ) {
4963
	    	if ( is_wp_error( $response ) ) {
4964
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4965
		}
4966
4967
		$code   = wp_remote_retrieve_response_code( $response );
4968
		$entity = wp_remote_retrieve_body( $response );
4969
		if ( $entity )
4970
			$json = json_decode( $entity );
4971
		else
4972
			$json = false;
4973
4974
		$code_type = intval( $code / 100 );
4975
		if ( 5 == $code_type ) {
4976
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4977
		} elseif ( 408 == $code ) {
4978
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4979
		} elseif ( ! empty( $json->error ) ) {
4980
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4981
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4982
		} elseif ( 200 != $code ) {
4983
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4984
		}
4985
4986
		// Jetpack ID error block
4987
		if ( empty( $json->jetpack_id ) ) {
4988
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4989
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4990
			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 );
4991
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4992
			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 );
4993
		}
4994
4995
	    return true;
4996
	}
4997
	/**
4998
	 * @return bool|WP_Error
4999
	 */
5000
	public static function register() {
5001
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5002
		$secrets = Jetpack::init()->generate_secrets( 'register' );
5003
5004
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
5005 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
5006
			return new Jetpack_Error( 'missing_secrets' );
5007
		}
5008
5009
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
5010
5011
		$gmt_offset = get_option( 'gmt_offset' );
5012
		if ( ! $gmt_offset ) {
5013
			$gmt_offset = 0;
5014
		}
5015
5016
		$stats_options = get_option( 'stats_options' );
5017
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5018
5019
		$args = array(
5020
			'method'  => 'POST',
5021
			'body'    => array(
5022
				'siteurl'         => site_url(),
5023
				'home'            => home_url(),
5024
				'gmt_offset'      => $gmt_offset,
5025
				'timezone_string' => (string) get_option( 'timezone_string' ),
5026
				'site_name'       => (string) get_option( 'blogname' ),
5027
				'secret_1'        => $secret_1,
5028
				'secret_2'        => $secret_2,
5029
				'site_lang'       => get_locale(),
5030
				'timeout'         => $timeout,
5031
				'stats_id'        => $stats_id,
5032
				'state'           => get_current_user_id(),
5033
			),
5034
			'headers' => array(
5035
				'Accept' => 'application/json',
5036
			),
5037
			'timeout' => $timeout,
5038
		);
5039
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5040
5041
5042
		// Make sure the response is valid and does not contain any Jetpack errors
5043
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
5044
		if( is_wp_error( $valid_response ) || !$valid_response ) {
5045
		    return $valid_response;
5046
		}
5047
5048
		// Grab the response values to work with
5049
		$code   = wp_remote_retrieve_response_code( $response );
5050
		$entity = wp_remote_retrieve_body( $response );
5051
5052
		if ( $entity )
5053
			$json = json_decode( $entity );
5054
		else
5055
			$json = false;
5056
5057 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
5058
			return new Jetpack_Error( 'jetpack_secret', '', $code );
5059
5060
		if ( isset( $json->jetpack_public ) ) {
5061
			$jetpack_public = (int) $json->jetpack_public;
5062
		} else {
5063
			$jetpack_public = false;
5064
		}
5065
5066
		Jetpack_Options::update_options(
5067
			array(
5068
				'id'         => (int)    $json->jetpack_id,
5069
				'blog_token' => (string) $json->jetpack_secret,
5070
				'public'     => $jetpack_public,
5071
			)
5072
		);
5073
5074
		/**
5075
		 * Fires when a site is registered on WordPress.com.
5076
		 *
5077
		 * @since 3.7.0
5078
		 *
5079
		 * @param int $json->jetpack_id Jetpack Blog ID.
5080
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5081
		 * @param int|bool $jetpack_public Is the site public.
5082
		 */
5083
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
5084
5085
		// Initialize Jump Start for the first and only time.
5086
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5087
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5088
5089
			$jetpack = Jetpack::init();
5090
5091
			$jetpack->stat( 'jumpstart', 'unique-views' );
5092
			$jetpack->do_stats( 'server_side' );
5093
		};
5094
5095
		return true;
5096
	}
5097
5098
	/**
5099
	 * If the db version is showing something other that what we've got now, bump it to current.
5100
	 *
5101
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5102
	 */
5103
	public static function maybe_set_version_option() {
5104
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5105
		if ( JETPACK__VERSION != $version ) {
5106
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5107
			return true;
5108
		}
5109
		return false;
5110
	}
5111
5112
/* Client Server API */
5113
5114
	/**
5115
	 * Loads the Jetpack XML-RPC client
5116
	 */
5117
	public static function load_xml_rpc_client() {
5118
		require_once ABSPATH . WPINC . '/class-IXR.php';
5119
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5120
	}
5121
5122
	function verify_xml_rpc_signature() {
5123
		if ( $this->xmlrpc_verification ) {
5124
			return $this->xmlrpc_verification;
5125
		}
5126
5127
		// It's not for us
5128
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5129
			return false;
5130
		}
5131
5132
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5133
		if (
5134
			empty( $token_key )
5135
		||
5136
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5137
		) {
5138
			return false;
5139
		}
5140
5141
		if ( '0' === $user_id ) {
5142
			$token_type = 'blog';
5143
			$user_id = 0;
5144
		} else {
5145
			$token_type = 'user';
5146
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5147
				return false;
5148
			}
5149
			$user_id = (int) $user_id;
5150
5151
			$user = new WP_User( $user_id );
5152
			if ( ! $user || ! $user->exists() ) {
5153
				return false;
5154
			}
5155
		}
5156
5157
		$token = Jetpack_Data::get_access_token( $user_id );
5158
		if ( ! $token ) {
5159
			return false;
5160
		}
5161
5162
		$token_check = "$token_key.";
5163
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5164
			return false;
5165
		}
5166
5167
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5168
5169
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5170
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5171
			$post_data   = $_POST;
5172
			$file_hashes = array();
5173
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5174
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5175
					continue;
5176
				}
5177
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5178
				$file_hashes[$post_data_key] = $post_data_value;
5179
			}
5180
5181
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5182
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5183
				$post_data[$post_data_key] = $post_data_value;
5184
			}
5185
5186
			ksort( $post_data );
5187
5188
			$body = http_build_query( stripslashes_deep( $post_data ) );
5189
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5190
			$body = file_get_contents( 'php://input' );
5191
		} else {
5192
			$body = null;
5193
		}
5194
		$signature = $jetpack_signature->sign_current_request(
5195
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5196
		);
5197
5198
		if ( ! $signature ) {
5199
			return false;
5200
		} else if ( is_wp_error( $signature ) ) {
5201
			return $signature;
5202
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5203
			return false;
5204
		}
5205
5206
		$timestamp = (int) $_GET['timestamp'];
5207
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5208
5209
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5210
			return false;
5211
		}
5212
5213
		$this->xmlrpc_verification = array(
5214
			'type'    => $token_type,
5215
			'user_id' => $token->external_user_id,
5216
		);
5217
5218
		return $this->xmlrpc_verification;
5219
	}
5220
5221
	/**
5222
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5223
	 */
5224
	function authenticate_jetpack( $user, $username, $password ) {
5225
		if ( is_a( $user, 'WP_User' ) ) {
5226
			return $user;
5227
		}
5228
5229
		$token_details = $this->verify_xml_rpc_signature();
5230
5231
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5232
			return $user;
5233
		}
5234
5235
		if ( 'user' !== $token_details['type'] ) {
5236
			return $user;
5237
		}
5238
5239
		if ( ! $token_details['user_id'] ) {
5240
			return $user;
5241
		}
5242
5243
		nocache_headers();
5244
5245
		return new WP_User( $token_details['user_id'] );
5246
	}
5247
5248
	function add_nonce( $timestamp, $nonce ) {
5249
		global $wpdb;
5250
		static $nonces_used_this_request = array();
5251
5252
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5253
			return $nonces_used_this_request["$timestamp:$nonce"];
5254
		}
5255
5256
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5257
		$timestamp = (int) $timestamp;
5258
		$nonce     = esc_sql( $nonce );
5259
5260
		// Raw query so we can avoid races: add_option will also update
5261
		$show_errors = $wpdb->show_errors( false );
5262
5263
		$old_nonce = $wpdb->get_row(
5264
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5265
		);
5266
5267
		if ( is_null( $old_nonce ) ) {
5268
			$return = $wpdb->query(
5269
				$wpdb->prepare(
5270
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5271
					"jetpack_nonce_{$timestamp}_{$nonce}",
5272
					time(),
5273
					'no'
5274
				)
5275
			);
5276
		} else {
5277
			$return = false;
5278
		}
5279
5280
		$wpdb->show_errors( $show_errors );
5281
5282
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5283
5284
		return $return;
5285
	}
5286
5287
	/**
5288
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5289
	 * Capture it here so we can verify the signature later.
5290
	 */
5291
	function xmlrpc_methods( $methods ) {
5292
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5293
		return $methods;
5294
	}
5295
5296
	function public_xmlrpc_methods( $methods ) {
5297
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5298
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5299
		}
5300
		return $methods;
5301
	}
5302
5303
	function jetpack_getOptions( $args ) {
5304
		global $wp_xmlrpc_server;
5305
5306
		$wp_xmlrpc_server->escape( $args );
5307
5308
		$username	= $args[1];
5309
		$password	= $args[2];
5310
5311
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5312
			return $wp_xmlrpc_server->error;
5313
		}
5314
5315
		$options = array();
5316
		$user_data = $this->get_connected_user_data();
5317
		if ( is_array( $user_data ) ) {
5318
			$options['jetpack_user_id'] = array(
5319
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5320
				'readonly'      => true,
5321
				'value'         => $user_data['ID'],
5322
			);
5323
			$options['jetpack_user_login'] = array(
5324
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5325
				'readonly'      => true,
5326
				'value'         => $user_data['login'],
5327
			);
5328
			$options['jetpack_user_email'] = array(
5329
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5330
				'readonly'      => true,
5331
				'value'         => $user_data['email'],
5332
			);
5333
			$options['jetpack_user_site_count'] = array(
5334
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5335
				'readonly'      => true,
5336
				'value'         => $user_data['site_count'],
5337
			);
5338
		}
5339
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5340
		$args = stripslashes_deep( $args );
5341
		return $wp_xmlrpc_server->wp_getOptions( $args );
5342
	}
5343
5344
	function xmlrpc_options( $options ) {
5345
		$jetpack_client_id = false;
5346
		if ( self::is_active() ) {
5347
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5348
		}
5349
		$options['jetpack_version'] = array(
5350
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5351
				'readonly'      => true,
5352
				'value'         => JETPACK__VERSION,
5353
		);
5354
5355
		$options['jetpack_client_id'] = array(
5356
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5357
				'readonly'      => true,
5358
				'value'         => $jetpack_client_id,
5359
		);
5360
		return $options;
5361
	}
5362
5363
	public static function clean_nonces( $all = false ) {
5364
		global $wpdb;
5365
5366
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5367
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
5368
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5369
		} else {
5370
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
5371
		}
5372
5373
		if ( true !== $all ) {
5374
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5375
			$sql_args[] = time() - 3600;
5376
		}
5377
5378
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5379
5380
		$sql = $wpdb->prepare( $sql, $sql_args );
5381
5382
		for ( $i = 0; $i < 1000; $i++ ) {
5383
			if ( ! $wpdb->query( $sql ) ) {
5384
				break;
5385
			}
5386
		}
5387
	}
5388
5389
	/**
5390
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5391
	 * SET: state( $key, $value );
5392
	 * GET: $value = state( $key );
5393
	 *
5394
	 * @param string $key
5395
	 * @param string $value
5396
	 * @param bool $restate private
5397
	 */
5398
	public static function state( $key = null, $value = null, $restate = false ) {
5399
		static $state = array();
5400
		static $path, $domain;
5401
		if ( ! isset( $path ) ) {
5402
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5403
			$admin_url = Jetpack::admin_url();
5404
			$bits      = parse_url( $admin_url );
5405
5406
			if ( is_array( $bits ) ) {
5407
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5408
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5409
			} else {
5410
				$path = $domain = null;
5411
			}
5412
		}
5413
5414
		// Extract state from cookies and delete cookies
5415
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5416
			$yum = $_COOKIE[ 'jetpackState' ];
5417
			unset( $_COOKIE[ 'jetpackState' ] );
5418
			foreach ( $yum as $k => $v ) {
5419
				if ( strlen( $v ) )
5420
					$state[ $k ] = $v;
5421
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5422
			}
5423
		}
5424
5425
		if ( $restate ) {
5426
			foreach ( $state as $k => $v ) {
5427
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5428
			}
5429
			return;
5430
		}
5431
5432
		// Get a state variable
5433
		if ( isset( $key ) && ! isset( $value ) ) {
5434
			if ( array_key_exists( $key, $state ) )
5435
				return $state[ $key ];
5436
			return null;
5437
		}
5438
5439
		// Set a state variable
5440
		if ( isset ( $key ) && isset( $value ) ) {
5441
			if( is_array( $value ) && isset( $value[0] ) ) {
5442
				$value = $value[0];
5443
			}
5444
			$state[ $key ] = $value;
5445
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5446
		}
5447
	}
5448
5449
	public static function restate() {
5450
		Jetpack::state( null, null, true );
5451
	}
5452
5453
	public static function check_privacy( $file ) {
5454
		static $is_site_publicly_accessible = null;
5455
5456
		if ( is_null( $is_site_publicly_accessible ) ) {
5457
			$is_site_publicly_accessible = false;
5458
5459
			Jetpack::load_xml_rpc_client();
5460
			$rpc = new Jetpack_IXR_Client();
5461
5462
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5463
			if ( $success ) {
5464
				$response = $rpc->getResponse();
5465
				if ( $response ) {
5466
					$is_site_publicly_accessible = true;
5467
				}
5468
			}
5469
5470
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5471
		}
5472
5473
		if ( $is_site_publicly_accessible ) {
5474
			return;
5475
		}
5476
5477
		$module_slug = self::get_module_slug( $file );
5478
5479
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5480
		if ( ! $privacy_checks ) {
5481
			$privacy_checks = $module_slug;
5482
		} else {
5483
			$privacy_checks .= ",$module_slug";
5484
		}
5485
5486
		Jetpack::state( 'privacy_checks', $privacy_checks );
5487
	}
5488
5489
	/**
5490
	 * Helper method for multicall XMLRPC.
5491
	 */
5492
	public static function xmlrpc_async_call() {
5493
		global $blog_id;
5494
		static $clients = array();
5495
5496
		$client_blog_id = is_multisite() ? $blog_id : 0;
5497
5498
		if ( ! isset( $clients[$client_blog_id] ) ) {
5499
			Jetpack::load_xml_rpc_client();
5500
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5501
			if ( function_exists( 'ignore_user_abort' ) ) {
5502
				ignore_user_abort( true );
5503
			}
5504
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5505
		}
5506
5507
		$args = func_get_args();
5508
5509
		if ( ! empty( $args[0] ) ) {
5510
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5511
		} elseif ( is_multisite() ) {
5512
			foreach ( $clients as $client_blog_id => $client ) {
5513
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5514
					continue;
5515
				}
5516
5517
				$switch_success = switch_to_blog( $client_blog_id, true );
5518
				if ( ! $switch_success ) {
5519
					continue;
5520
				}
5521
5522
				flush();
5523
				$client->query();
5524
5525
				restore_current_blog();
5526
			}
5527
		} else {
5528
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5529
				flush();
5530
				$clients[0]->query();
5531
			}
5532
		}
5533
	}
5534
5535
	public static function staticize_subdomain( $url ) {
5536
5537
		// Extract hostname from URL
5538
		$host = parse_url( $url, PHP_URL_HOST );
5539
5540
		// Explode hostname on '.'
5541
		$exploded_host = explode( '.', $host );
5542
5543
		// Retrieve the name and TLD
5544
		if ( count( $exploded_host ) > 1 ) {
5545
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5546
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5547
			// Rebuild domain excluding subdomains
5548
			$domain = $name . '.' . $tld;
5549
		} else {
5550
			$domain = $host;
5551
		}
5552
		// Array of Automattic domains
5553
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5554
5555
		// Return $url if not an Automattic domain
5556
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5557
			return $url;
5558
		}
5559
5560
		if ( is_ssl() ) {
5561
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5562
		}
5563
5564
		srand( crc32( basename( $url ) ) );
5565
		$static_counter = rand( 0, 2 );
5566
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5567
5568
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5569
	}
5570
5571
/* JSON API Authorization */
5572
5573
	/**
5574
	 * Handles the login action for Authorizing the JSON API
5575
	 */
5576
	function login_form_json_api_authorization() {
5577
		$this->verify_json_api_authorization_request();
5578
5579
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5580
5581
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5582
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5583
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5584
	}
5585
5586
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5587
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5588
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5589
			return $url;
5590
		}
5591
5592
		$parsed_url = parse_url( $url );
5593
		$url = strtok( $url, '?' );
5594
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5595
		if ( ! empty( $parsed_url['query'] ) )
5596
			$url .= "&{$parsed_url['query']}";
5597
5598
		return $url;
5599
	}
5600
5601
	// Make sure the POSTed request is handled by the same action
5602
	function preserve_action_in_login_form_for_json_api_authorization() {
5603
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5604
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5605
	}
5606
5607
	// If someone logs in to approve API access, store the Access Code in usermeta
5608
	function store_json_api_authorization_token( $user_login, $user ) {
5609
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5610
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5611
		$token = wp_generate_password( 32, false );
5612
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5613
	}
5614
5615
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5616
	function allow_wpcom_public_api_domain( $domains ) {
5617
		$domains[] = 'public-api.wordpress.com';
5618
		return $domains;
5619
	}
5620
5621
	// Add the Access Code details to the public-api.wordpress.com redirect
5622
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5623
		return add_query_arg(
5624
			urlencode_deep(
5625
				array(
5626
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5627
					'jetpack-user-id' => (int) $user->ID,
5628
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5629
				)
5630
			),
5631
			$redirect_to
5632
		);
5633
	}
5634
5635
	// Verifies the request by checking the signature
5636
	function verify_json_api_authorization_request() {
5637
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5638
5639
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5640
		if ( ! $token || empty( $token->secret ) ) {
5641
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5642
		}
5643
5644
		$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' );
5645
5646
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5647
5648
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5649
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5650
		} else {
5651
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5652
		}
5653
5654
		if ( ! $signature ) {
5655
			wp_die( $die_error );
5656
		} else if ( is_wp_error( $signature ) ) {
5657
			wp_die( $die_error );
5658
		} else if ( $signature !== $_GET['signature'] ) {
5659
			if ( is_ssl() ) {
5660
				// 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
5661
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5662
				if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5663
					wp_die( $die_error );
5664
				}
5665
			} else {
5666
				wp_die( $die_error );
5667
			}
5668
		}
5669
5670
		$timestamp = (int) $_GET['timestamp'];
5671
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5672
5673
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5674
			// De-nonce the nonce, at least for 5 minutes.
5675
			// 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)
5676
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5677
			if ( $old_nonce_time < time() - 300 ) {
5678
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5679
			}
5680
		}
5681
5682
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5683
		$data_filters = array(
5684
			'state'        => 'opaque',
5685
			'client_id'    => 'int',
5686
			'client_title' => 'string',
5687
			'client_image' => 'url',
5688
		);
5689
5690
		foreach ( $data_filters as $key => $sanitation ) {
5691
			if ( ! isset( $data->$key ) ) {
5692
				wp_die( $die_error );
5693
			}
5694
5695
			switch ( $sanitation ) {
5696
			case 'int' :
5697
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5698
				break;
5699
			case 'opaque' :
5700
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5701
				break;
5702
			case 'string' :
5703
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5704
				break;
5705
			case 'url' :
5706
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5707
				break;
5708
			}
5709
		}
5710
5711
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5712
			wp_die( $die_error );
5713
		}
5714
	}
5715
5716
	function login_message_json_api_authorization( $message ) {
5717
		return '<p class="message">' . sprintf(
5718
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5719
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5720
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5721
	}
5722
5723
	/**
5724
	 * Get $content_width, but with a <s>twist</s> filter.
5725
	 */
5726
	public static function get_content_width() {
5727
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5728
		/**
5729
		 * Filter the Content Width value.
5730
		 *
5731
		 * @since 2.2.3
5732
		 *
5733
		 * @param string $content_width Content Width value.
5734
		 */
5735
		return apply_filters( 'jetpack_content_width', $content_width );
5736
	}
5737
5738
	/**
5739
	 * Centralize the function here until it gets added to core.
5740
	 *
5741
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5742
	 * @param int $size Size of the avatar image
5743
	 * @param string $default URL to a default image to use if no avatar is available
5744
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5745
	 *
5746
	 * @return array First element is the URL, second is the class.
5747
	 */
5748
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5749
		// Don't bother adding the __return_true filter if it's already there.
5750
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5751
5752
		if ( $force_display && ! $has_filter )
5753
			add_filter( 'pre_option_show_avatars', '__return_true' );
5754
5755
		$avatar = get_avatar( $id_or_email, $size, $default );
5756
5757
		if ( $force_display && ! $has_filter )
5758
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5759
5760
		// If no data, fail out.
5761
		if ( is_wp_error( $avatar ) || ! $avatar )
5762
			return array( null, null );
5763
5764
		// Pull out the URL.  If it's not there, fail out.
5765
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5766
			return array( null, null );
5767
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5768
5769
		// Pull out the class, but it's not a big deal if it's missing.
5770
		$class = '';
5771
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5772
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5773
5774
		return array( $url, $class );
5775
	}
5776
5777
	/**
5778
	 * Pings the WordPress.com Mirror Site for the specified options.
5779
	 *
5780
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5781
	 *
5782
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5783
	 */
5784
	public function get_cloud_site_options( $option_names ) {
5785
		$option_names = array_filter( (array) $option_names, 'is_string' );
5786
5787
		Jetpack::load_xml_rpc_client();
5788
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5789
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5790
		if ( $xml->isError() ) {
5791
			return array(
5792
				'error_code' => $xml->getErrorCode(),
5793
				'error_msg'  => $xml->getErrorMessage(),
5794
			);
5795
		}
5796
		$cloud_site_options = $xml->getResponse();
5797
5798
		return $cloud_site_options;
5799
	}
5800
5801
	/**
5802
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5803
	 *
5804
	 * @return array An array of options to check.
5805
	 */
5806
	public static function identity_crisis_options_to_check() {
5807
		return array(
5808
			'siteurl',
5809
			'home',
5810
		);
5811
	}
5812
5813
	/**
5814
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5815
	 *
5816
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5817
	 *
5818
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5819
	 */
5820
	public static function check_identity_crisis( $force_recheck = false ) {
5821
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5822
			return false;
5823
5824
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5825
			$options_to_check = self::identity_crisis_options_to_check();
5826
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5827
			$errors        = array();
5828
5829
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5830
5831
				// If it's not the same as the local value...
5832
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5833
5834
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5835
					if ( 'error_code' == $cloud_key ) {
5836
						$errors[ $cloud_key ] = $cloud_value;
5837
						break;
5838
					}
5839
5840
					$parsed_cloud_value = parse_url( $cloud_value );
5841
					// If the current options is an IP address
5842
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5843
						// Give the new value a Jetpack to fly in to the clouds
5844
						Jetpack::resolve_identity_crisis( $cloud_key );
5845
						continue;
5846
					}
5847
5848
					// And it's not been added to the whitelist...
5849
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5850
						/*
5851
						 * This should be a temporary hack until a cleaner solution is found.
5852
						 *
5853
						 * The siteurl and home can be set to use http in General > Settings
5854
						 * however some constants can be defined that can force https in wp-admin
5855
						 * when this happens wpcom can confuse wporg with a fake identity
5856
						 * crisis with a mismatch of http vs https when it should be allowed.
5857
						 * we need to check that here.
5858
						 *
5859
						 * @see https://github.com/Automattic/jetpack/issues/1006
5860
						 */
5861
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5862
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5863
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5864
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5865
							continue;
5866
						}
5867
5868
5869
						// Then kick an error!
5870
						$errors[ $cloud_key ] = $cloud_value;
5871
					}
5872
				}
5873
			}
5874
		}
5875
5876
		/**
5877
		 * Filters the errors returned when checking for an Identity Crisis.
5878
		 *
5879
		 * @since 2.3.2
5880
		 *
5881
		 * @param array $errors Array of Identity Crisis errors.
5882
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5883
		 */
5884
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5885
	}
5886
5887
	/*
5888
	 * Resolve ID crisis
5889
	 *
5890
	 * If the URL has changed, but the rest of the options are the same (i.e. blog/user tokens)
5891
	 * The user has the option to update the shadow site with the new URL before a new
5892
	 * token is created.
5893
	 *
5894
	 * @param $key : Which option to sync.  null defautlts to home and siteurl
5895
	 */
5896
	public static function resolve_identity_crisis( $key = null ) {
5897
		if ( $key ) {
5898
			$identity_options = array( $key );
5899
		} else {
5900
			$identity_options = self::identity_crisis_options_to_check();
5901
		}
5902
5903
		if ( is_array( $identity_options ) ) {
5904
			foreach( $identity_options as $identity_option ) {
5905
				Jetpack_Sync::sync_options( __FILE__, $identity_option );
5906
5907
				/**
5908
				 * Fires when a shadow site option is updated.
5909
				 * These options are updated via the Identity Crisis UI.
5910
				 * $identity_option is the option that gets updated.
5911
				 *
5912
				 * @since 3.7.0
5913
				 */
5914
				do_action( "update_option_{$identity_option}" );
5915
			}
5916
		}
5917
	}
5918
5919
	/*
5920
	 * Whitelist URL
5921
	 *
5922
	 * Ignore the URL differences between the blog and the shadow site.
5923
	 */
5924
	public static function whitelist_current_url() {
5925
		$options_to_check = Jetpack::identity_crisis_options_to_check();
5926
		$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5927
5928
		foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5929
			Jetpack::whitelist_identity_crisis_value( $cloud_key, $cloud_value );
5930
		}
5931
	}
5932
5933
	/*
5934
	 * Ajax callbacks for ID crisis resolutions
5935
	 *
5936
	 * Things that could happen here:
5937
	 *  - site_migrated : Update the URL on the shadow blog to match new domain
5938
	 *  - whitelist     : Ignore the URL difference
5939
	 *  - default       : Error message
5940
	 */
5941
	public static function resolve_identity_crisis_ajax_callback() {
5942
		check_ajax_referer( 'resolve-identity-crisis', 'ajax-nonce' );
5943
5944
		switch ( $_POST[ 'crisis_resolution_action' ] ) {
5945
			case 'site_migrated':
5946
				Jetpack::resolve_identity_crisis();
5947
				echo 'resolved';
5948
				break;
5949
5950
			case 'whitelist':
5951
				Jetpack::whitelist_current_url();
5952
				echo 'whitelisted';
5953
				break;
5954
5955
			case 'reset_connection':
5956
				// Delete the options first so it doesn't get confused which site to disconnect dotcom-side
5957
				Jetpack_Options::delete_option(
5958
					array(
5959
						'register',
5960
						'blog_token',
5961
						'user_token',
5962
						'user_tokens',
5963
						'master_user',
5964
						'time_diff',
5965
						'fallback_no_verify_ssl_certs',
5966
						'id',
5967
					)
5968
				);
5969
				delete_transient( 'jetpack_has_identity_crisis' );
5970
5971
				echo 'reset-connection-success';
5972
				break;
5973
5974
			default:
5975
				echo 'missing action';
5976
				break;
5977
		}
5978
5979
		wp_die();
5980
	}
5981
5982
	/**
5983
	 * Adds a value to the whitelist for the specified key.
5984
	 *
5985
	 * @param string $key The option name that we're whitelisting the value for.
5986
	 * @param string $value The value that we're intending to add to the whitelist.
5987
	 *
5988
	 * @return bool Whether the value was added to the whitelist, or false if it was already there.
5989
	 */
5990
	public static function whitelist_identity_crisis_value( $key, $value ) {
5991
		if ( Jetpack::is_identity_crisis_value_whitelisted( $key, $value ) ) {
5992
			return false;
5993
		}
5994
5995
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
5996
		if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
5997
			$whitelist[ $key ] = array();
5998
		}
5999
		array_push( $whitelist[ $key ], $value );
6000
6001
		Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
6002
		return true;
6003
	}
6004
6005
	/**
6006
	 * Checks whether a value is already whitelisted.
6007
	 *
6008
	 * @param string $key The option name that we're checking the value for.
6009
	 * @param string $value The value that we're curious to see if it's on the whitelist.
6010
	 *
6011
	 * @return bool Whether the value is whitelisted.
6012
	 */
6013
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
6014
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6015
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
6016
			return true;
6017
		}
6018
		return false;
6019
	}
6020
6021
	/**
6022
	 * Checks whether the home and siteurl specifically are whitelisted
6023
	 * Written so that we don't have re-check $key and $value params every time
6024
	 * we want to check if this site is whitelisted, for example in footer.php
6025
	 *
6026
	 * @return bool True = already whitelsisted False = not whitelisted
6027
	 */
6028
	public static function is_staging_site() {
6029
		$is_staging = false;
6030
6031
		$current_whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist' );
6032
		if ( $current_whitelist ) {
6033
			$options_to_check  = Jetpack::identity_crisis_options_to_check();
6034
			$cloud_options     = Jetpack::init()->get_cloud_site_options( $options_to_check );
6035
6036
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6037
				if ( self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
6038
					$is_staging = true;
6039
					break;
6040
				}
6041
			}
6042
		}
6043
		$known_staging = array(
6044
			'urls' => array(
6045
				'#\.staging\.wpengine\.com$#i',
6046
				),
6047
			'constants' => array(
6048
				'IS_WPE_SNAPSHOT',
6049
				'KINSTA_DEV_ENV',
6050
				'JETPACK_STAGING_MODE',
6051
				)
6052
			);
6053
		/**
6054
		 * Filters the flags of known staging sites.
6055
		 *
6056
		 * @since 3.9.0
6057
		 *
6058
		 * @param array $known_staging {
6059
		 *     An array of arrays that each are used to check if the current site is staging.
6060
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6061
		 *     @type array $cosntants PHP constants of known staging/developement environments.
6062
		 *  }
6063
		 */
6064
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6065
6066
		if ( isset( $known_staging['urls'] ) ) {
6067
			foreach ( $known_staging['urls'] as $url ){
6068
				if ( preg_match( $url, site_url() ) ) {
6069
					$is_staging = true;
6070
					break;
6071
				}
6072
			}
6073
		}
6074
6075
		if ( isset( $known_staging['constants'] ) ) {
6076
			foreach ( $known_staging['constants'] as $constant ) {
6077
				if ( defined( $constant ) && constant( $constant ) ) {
6078
					$is_staging = true;
6079
				}
6080
			}
6081
		}
6082
6083
		/**
6084
		 * Filters is_staging_site check.
6085
		 *
6086
		 * @since 3.9.0
6087
		 *
6088
		 * @param bool $is_staging If the current site is a staging site.
6089
		 */
6090
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6091
	}
6092
6093
	public function identity_crisis_js( $nonce ) {
6094
?>
6095
<script>
6096
(function( $ ) {
6097
	var SECOND_IN_MS = 1000;
6098
6099
	function contactSupport( e ) {
6100
		e.preventDefault();
6101
		$( '.jp-id-crisis-question' ).hide();
6102
		$( '#jp-id-crisis-contact-support' ).show();
6103
	}
6104
6105
	function autodismissSuccessBanner() {
6106
		$( '.jp-identity-crisis' ).fadeOut(600); //.addClass( 'dismiss' );
6107
	}
6108
6109
	var data = { action: 'jetpack_resolve_identity_crisis', 'ajax-nonce': '<?php echo $nonce; ?>' };
6110
6111
	$( document ).ready(function() {
6112
6113
		// Site moved: Update the URL on the shadow blog
6114
		$( '.site-moved' ).click(function( e ) {
6115
			e.preventDefault();
6116
			data.crisis_resolution_action = 'site_migrated';
6117
			$( '#jp-id-crisis-question-1 .spinner' ).show();
6118
			$.post( ajaxurl, data, function() {
6119
				$( '.jp-id-crisis-question' ).hide();
6120
				$( '.banner-title' ).hide();
6121
				$( '#jp-id-crisis-success' ).show();
6122
				setTimeout( autodismissSuccessBanner, 6 * SECOND_IN_MS );
6123
			});
6124
6125
		});
6126
6127
		// URL hasn't changed, next question please.
6128
		$( '.site-not-moved' ).click(function( e ) {
6129
			e.preventDefault();
6130
			$( '.jp-id-crisis-question' ).hide();
6131
			$( '#jp-id-crisis-question-2' ).show();
6132
		});
6133
6134
		// Reset connection: two separate sites.
6135
		$( '.reset-connection' ).click(function( e ) {
6136
			data.crisis_resolution_action = 'reset_connection';
6137
			$.post( ajaxurl, data, function( response ) {
6138
				if ( 'reset-connection-success' === response ) {
6139
					window.location.replace( '<?php echo Jetpack::admin_url(); ?>' );
6140
				}
6141
			});
6142
		});
6143
6144
		// It's a dev environment.  Ignore.
6145
		$( '.is-dev-env' ).click(function( e ) {
6146
			data.crisis_resolution_action = 'whitelist';
6147
			$( '#jp-id-crisis-question-2 .spinner' ).show();
6148
			$.post( ajaxurl, data, function() {
6149
				$( '.jp-id-crisis-question' ).hide();
6150
				$( '.banner-title' ).hide();
6151
				$( '#jp-id-crisis-success' ).show();
6152
				setTimeout( autodismissSuccessBanner, 4 * SECOND_IN_MS );
6153
			});
6154
		});
6155
6156
		$( '.not-reconnecting' ).click(contactSupport);
6157
		$( '.not-staging-or-dev' ).click(contactSupport);
6158
	});
6159
})( jQuery );
6160
</script>
6161
<?php
6162
	}
6163
6164
	/**
6165
	 * Displays an admin_notice, alerting the user to an identity crisis.
6166
	 */
6167
	public function alert_identity_crisis() {
6168
		// @todo temporary killing of feature in 3.8.1 as it revealed a number of scenarios not foreseen.
6169
		if ( ! Jetpack::is_development_version() ) {
6170
			return;
6171
		}
6172
6173
		// @todo temporary copout for dealing with domain mapping
6174
		// @see https://github.com/Automattic/jetpack/issues/2702
6175
		if ( is_multisite() && defined( 'SUNRISE' ) && ! Jetpack::is_development_version() ) {
6176
			return;
6177
		}
6178
6179
		if ( ! current_user_can( 'jetpack_disconnect' ) ) {
6180
			return;
6181
		}
6182
6183
		if ( ! $errors = self::check_identity_crisis() ) {
6184
			return;
6185
		}
6186
6187
		// Only show on dashboard and jetpack pages
6188
		$screen = get_current_screen();
6189
		if ( 'dashboard' !== $screen->base && ! did_action( 'jetpack_notices' ) ) {
6190
			return;
6191
		}
6192
6193
		// Include the js!
6194
		$ajax_nonce = wp_create_nonce( 'resolve-identity-crisis' );
6195
		$this->identity_crisis_js( $ajax_nonce );
6196
6197
		// Include the CSS!
6198
		if ( ! wp_script_is( 'jetpack', 'done' ) ) {
6199
			$this->admin_banner_styles();
6200
		}
6201
6202
		if ( ! array_key_exists( 'error_code', $errors ) ) {
6203
			$key = 'siteurl';
6204
			if ( ! $errors[ $key ] ) {
6205
				$key = 'home';
6206
			}
6207
		} else {
6208
			$key = 'error_code';
6209
			// 401 is the only error we care about.  Any other errors should not trigger the alert.
6210
			if ( 401 !== $errors[ $key ] ) {
6211
				return;
6212
			}
6213
		}
6214
6215
		?>
6216
6217
		<style>
6218
			.jp-identity-crisis .jp-btn-group {
6219
					margin: 15px 0;
6220
				}
6221
			.jp-identity-crisis strong {
6222
					color: #518d2a;
6223
				}
6224
			.jp-identity-crisis.dismiss {
6225
				display: none;
6226
			}
6227
			.jp-identity-crisis .button {
6228
				margin-right: 4px;
6229
			}
6230
		</style>
6231
6232
		<div id="message" class="error jetpack-message jp-identity-crisis stay-visible">
6233
			<div class="service-mark"></div>
6234
			<div class="jp-id-banner__content">
6235
				<!-- <h3 class="banner-title"><?php _e( 'Something\'s not quite right with your Jetpack connection! Let\'s fix that.', 'jetpack' ); ?></h3> -->
6236
6237
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-1">
6238
					<?php
6239
					// 401 means that this site has been disconnected from wpcom, but the remote site still thinks it's connected.
6240
					if ( 'error_code' == $key && '401' == $errors[ $key ] ) : ?>
6241
						<div class="banner-content">
6242
							<p><?php
6243
								/* translators: %s is a URL */
6244
								printf( __( 'Our records show that this site does not have a valid connection to WordPress.com. Please reset your connection to fix this. <a href="%s" target="_blank">What caused this?</a>', 'jetpack' ), 'https://jetpack.com/support/no-valid-wordpress-com-connection/' );
6245
							?></p>
6246
						</div>
6247
						<div class="jp-btn-group">
6248
							<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a>
6249
							<span class="idc-separator">|</span>
6250
							<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>"><?php _e( 'Deactivate Jetpack', 'jetpack' ); ?></a>
6251
						</div>
6252
					<?php else : ?>
6253
							<div class="banner-content">
6254
							<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>
6255
							</div>
6256
						<div class="jp-btn-group">
6257
							<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>
6258
							<span class="spinner"></span>
6259
						</div>
6260
					<?php endif ; ?>
6261
				</div>
6262
6263
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-2" style="display: none;">
6264
					<div class="banner-content">
6265
						<p><?php printf(
6266
							/* translators: %1$s, %2$s and %3$s are URLs */
6267
							__(
6268
								'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>',
6269
								'jetpack'
6270
							),
6271
							$errors[ $key ],
6272
							(string) get_option( $key ),
6273
							'https://jetpack.com/support/what-does-resetting-the-connection-mean/'
6274
						); ?></p>
6275
					</div>
6276
					<div class="jp-btn-group">
6277
						<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6278
						<a href="#" class="is-dev-env"><?php _e( 'This is a development environment', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6279
						<a href="https://jetpack.com/contact-support/" class="contact-support"><?php _e( 'Submit a support ticket', 'jetpack' ); ?></a>
6280
						<span class="spinner"></span>
6281
					</div>
6282
				</div>
6283
6284
				<div class="jp-id-crisis-success" id="jp-id-crisis-success" style="display: none;">
6285
					<h3 class="success-notice"><?php printf( __( 'Thanks for taking the time to sort things out. We&#039;ve updated our records accordingly!', 'jetpack' ) ); ?></h3>
6286
				</div>
6287
			</div>
6288
		</div>
6289
6290
		<?php
6291
	}
6292
6293
	/**
6294
	 * Maybe Use a .min.css stylesheet, maybe not.
6295
	 *
6296
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6297
	 */
6298
	public static function maybe_min_asset( $url, $path, $plugin ) {
6299
		// Short out on things trying to find actual paths.
6300
		if ( ! $path || empty( $plugin ) ) {
6301
			return $url;
6302
		}
6303
6304
		// Strip out the abspath.
6305
		$base = dirname( plugin_basename( $plugin ) );
6306
6307
		// Short out on non-Jetpack assets.
6308
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6309
			return $url;
6310
		}
6311
6312
		// File name parsing.
6313
		$file              = "{$base}/{$path}";
6314
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6315
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6316
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6317
		$extension         = array_shift( $file_name_parts_r );
6318
6319
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6320
			// Already pointing at the minified version.
6321
			if ( 'min' === $file_name_parts_r[0] ) {
6322
				return $url;
6323
			}
6324
6325
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6326
			if ( file_exists( $min_full_path ) ) {
6327
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6328
			}
6329
		}
6330
6331
		return $url;
6332
	}
6333
6334
	/**
6335
	 * Maybe inlines a stylesheet.
6336
	 *
6337
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6338
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6339
	 *
6340
	 * Attached to `style_loader_tag` filter.
6341
	 *
6342
	 * @param string $tag The tag that would link to the external asset.
6343
	 * @param string $handle The registered handle of the script in question.
6344
	 *
6345
	 * @return string
6346
	 */
6347
	public static function maybe_inline_style( $tag, $handle ) {
6348
		global $wp_styles;
6349
		$item = $wp_styles->registered[ $handle ];
6350
6351
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6352
			return $tag;
6353
		}
6354
6355
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6356
			$href = $matches[1];
6357
			// Strip off query string
6358
			if ( $pos = strpos( $href, '?' ) ) {
6359
				$href = substr( $href, 0, $pos );
6360
			}
6361
			// Strip off fragment
6362
			if ( $pos = strpos( $href, '#' ) ) {
6363
				$href = substr( $href, 0, $pos );
6364
			}
6365
		} else {
6366
			return $tag;
6367
		}
6368
6369
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6370
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6371
			return $tag;
6372
		}
6373
6374
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6375
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6376
			// And this isn't the pass that actually deals with the RTL version...
6377
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6378
				// Short out, as the RTL version will deal with it in a moment.
6379
				return $tag;
6380
			}
6381
		}
6382
6383
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6384
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6385
		if ( $css ) {
6386
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6387
			if ( empty( $item->extra['after'] ) ) {
6388
				wp_add_inline_style( $handle, $css );
6389
			} else {
6390
				array_unshift( $item->extra['after'], $css );
6391
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6392
			}
6393
		}
6394
6395
		return $tag;
6396
	}
6397
6398
	/**
6399
	 * Loads a view file from the views
6400
	 *
6401
	 * Data passed in with the $data parameter will be available in the
6402
	 * template file as $data['value']
6403
	 *
6404
	 * @param string $template - Template file to load
6405
	 * @param array $data - Any data to pass along to the template
6406
	 * @return boolean - If template file was found
6407
	 **/
6408
	public function load_view( $template, $data = array() ) {
6409
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6410
6411
		if( file_exists( $views_dir . $template ) ) {
6412
			require_once( $views_dir . $template );
6413
			return true;
6414
		}
6415
6416
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6417
		return false;
6418
	}
6419
6420
	/**
6421
	 * Sends a ping to the Jetpack servers to toggle on/off remote portions
6422
	 * required by some modules.
6423
	 *
6424
	 * @param string $module_slug
6425
	 */
6426
	public function toggle_module_on_wpcom( $module_slug ) {
6427
		Jetpack::init()->sync->register( 'noop' );
6428
6429
		if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
6430
			self::check_privacy( $module_slug );
6431
		}
6432
6433
	}
6434
6435
	/**
6436
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6437
	 */
6438
	public function deprecated_hooks() {
6439
		global $wp_filter;
6440
6441
		/*
6442
		 * Format:
6443
		 * deprecated_filter_name => replacement_name
6444
		 *
6445
		 * If there is no replacement us null for replacement_name
6446
		 */
6447
		$deprecated_list = array(
6448
			'jetpack_bail_on_shortcode'                => 'jetpack_shortcodes_to_include',
6449
			'wpl_sharing_2014_1'                       => null,
6450
			'jetpack-tools-to-include'                 => 'jetpack_tools_to_include',
6451
			'jetpack_identity_crisis_options_to_check' => null,
6452
		);
6453
6454
		// This is a silly loop depth. Better way?
6455
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6456
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
6457
				foreach( $wp_filter[$hook] AS $func => $values ) {
6458
					foreach( $values AS $hooked ) {
6459
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
6460
					}
6461
				}
6462
			}
6463
		}
6464
	}
6465
6466
	/**
6467
	 * Converts any url in a stylesheet, to the correct absolute url.
6468
	 *
6469
	 * Considerations:
6470
	 *  - Normal, relative URLs     `feh.png`
6471
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6472
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6473
	 *  - Absolute URLs             `http://domain.com/feh.png`
6474
	 *  - Domain root relative URLs `/feh.png`
6475
	 *
6476
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6477
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6478
	 *
6479
	 * @return mixed|string
6480
	 */
6481
	public static function absolutize_css_urls( $css, $css_file_url ) {
6482
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6483
		$css_dir = dirname( $css_file_url );
6484
		$p       = parse_url( $css_dir );
6485
		$domain  = sprintf(
6486
					'%1$s//%2$s%3$s%4$s',
6487
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6488
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6489
					$p['host'],
6490
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6491
				);
6492
6493
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6494
			$find = $replace = array();
6495
			foreach ( $matches as $match ) {
6496
				$url = trim( $match['path'], "'\" \t" );
6497
6498
				// If this is a data url, we don't want to mess with it.
6499
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6500
					continue;
6501
				}
6502
6503
				// If this is an absolute or protocol-agnostic url,
6504
				// we don't want to mess with it.
6505
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6506
					continue;
6507
				}
6508
6509
				switch ( substr( $url, 0, 1 ) ) {
6510
					case '/':
6511
						$absolute = $domain . $url;
6512
						break;
6513
					default:
6514
						$absolute = $css_dir . '/' . $url;
6515
				}
6516
6517
				$find[]    = $match[0];
6518
				$replace[] = sprintf( 'url("%s")', $absolute );
6519
			}
6520
			$css = str_replace( $find, $replace, $css );
6521
		}
6522
6523
		return $css;
6524
	}
6525
6526
	/**
6527
	 * This method checks to see if SSL is required by the site in
6528
	 * order to visit it in some way other than only setting the
6529
	 * https value in the home or siteurl values.
6530
	 *
6531
	 * @since 3.2
6532
	 * @return boolean
6533
	 **/
6534
	private function is_ssl_required_to_visit_site() {
6535
		global $wp_version;
6536
		$ssl = is_ssl();
6537
6538
		if ( force_ssl_admin() ) {
6539
			$ssl = true;
6540
		}
6541
		return $ssl;
6542
	}
6543
6544
	/**
6545
	 * This methods removes all of the registered css files on the frontend
6546
	 * from Jetpack in favor of using a single file. In effect "imploding"
6547
	 * all the files into one file.
6548
	 *
6549
	 * Pros:
6550
	 * - Uses only ONE css asset connection instead of 15
6551
	 * - Saves a minimum of 56k
6552
	 * - Reduces server load
6553
	 * - Reduces time to first painted byte
6554
	 *
6555
	 * Cons:
6556
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6557
	 *		should not cause any issues with themes.
6558
	 * - Plugins/themes dequeuing styles no longer do anything. See
6559
	 *		jetpack_implode_frontend_css filter for a workaround
6560
	 *
6561
	 * For some situations developers may wish to disable css imploding and
6562
	 * instead operate in legacy mode where each file loads seperately and
6563
	 * can be edited individually or dequeued. This can be accomplished with
6564
	 * the following line:
6565
	 *
6566
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6567
	 *
6568
	 * @since 3.2
6569
	 **/
6570
	public function implode_frontend_css( $travis_test = false ) {
6571
		$do_implode = true;
6572
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6573
			$do_implode = false;
6574
		}
6575
6576
		/**
6577
		 * Allow CSS to be concatenated into a single jetpack.css file.
6578
		 *
6579
		 * @since 3.2.0
6580
		 *
6581
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6582
		 */
6583
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6584
6585
		// Do not use the imploded file when default behaviour was altered through the filter
6586
		if ( ! $do_implode ) {
6587
			return;
6588
		}
6589
6590
		// We do not want to use the imploded file in dev mode, or if not connected
6591
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6592
			if ( ! $travis_test ) {
6593
				return;
6594
			}
6595
		}
6596
6597
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6598
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6599
			return;
6600
		}
6601
6602
		/*
6603
		 * Now we assume Jetpack is connected and able to serve the single
6604
		 * file.
6605
		 *
6606
		 * In the future there will be a check here to serve the file locally
6607
		 * or potentially from the Jetpack CDN
6608
		 *
6609
		 * For now:
6610
		 * - Enqueue a single imploded css file
6611
		 * - Zero out the style_loader_tag for the bundled ones
6612
		 * - Be happy, drink scotch
6613
		 */
6614
6615
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6616
6617
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6618
6619
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6620
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6621
	}
6622
6623
	function concat_remove_style_loader_tag( $tag, $handle ) {
6624
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6625
			$tag = '';
6626
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6627
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6628
			}
6629
		}
6630
6631
		return $tag;
6632
	}
6633
6634
	/*
6635
	 * Check the heartbeat data
6636
	 *
6637
	 * Organizes the heartbeat data by severity.  For example, if the site
6638
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6639
	 *
6640
	 * Data will be added to "caution" array, if it either:
6641
	 *  - Out of date Jetpack version
6642
	 *  - Out of date WP version
6643
	 *  - Out of date PHP version
6644
	 *
6645
	 * $return array $filtered_data
6646
	 */
6647
	public static function jetpack_check_heartbeat_data() {
6648
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6649
6650
		$good    = array();
6651
		$caution = array();
6652
		$bad     = array();
6653
6654
		foreach ( $raw_data as $stat => $value ) {
6655
6656
			// Check jetpack version
6657
			if ( 'version' == $stat ) {
6658
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6659
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6660
					continue;
6661
				}
6662
			}
6663
6664
			// Check WP version
6665
			if ( 'wp-version' == $stat ) {
6666
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6667
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6668
					continue;
6669
				}
6670
			}
6671
6672
			// Check PHP version
6673
			if ( 'php-version' == $stat ) {
6674
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6675
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6676
					continue;
6677
				}
6678
			}
6679
6680
			// Check ID crisis
6681
			if ( 'identitycrisis' == $stat ) {
6682
				if ( 'yes' == $value ) {
6683
					$bad[ $stat ] = $value;
6684
					continue;
6685
				}
6686
			}
6687
6688
			// The rest are good :)
6689
			$good[ $stat ] = $value;
6690
		}
6691
6692
		$filtered_data = array(
6693
			'good'    => $good,
6694
			'caution' => $caution,
6695
			'bad'     => $bad
6696
		);
6697
6698
		return $filtered_data;
6699
	}
6700
6701
6702
	/*
6703
	 * This method is used to organize all options that can be reset
6704
	 * without disconnecting Jetpack.
6705
	 *
6706
	 * It is used in class.jetpack-cli.php to reset options
6707
	 *
6708
	 * @return array of options to delete.
6709
	 */
6710
	public static function get_jetpack_options_for_reset() {
6711
		$jetpack_options            = Jetpack_Options::get_option_names();
6712
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6713
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6714
6715
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6716
6717
		// A manual build of the wp options
6718
		$wp_options = array(
6719
			'sharing-options',
6720
			'disabled_likes',
6721
			'disabled_reblogs',
6722
			'jetpack_comments_likes_enabled',
6723
			'wp_mobile_excerpt',
6724
			'wp_mobile_featured_images',
6725
			'wp_mobile_app_promos',
6726
			'stats_options',
6727
			'stats_dashboard_widget',
6728
			'safecss_preview_rev',
6729
			'safecss_rev',
6730
			'safecss_revision_migrated',
6731
			'nova_menu_order',
6732
			'jetpack_portfolio',
6733
			'jetpack_portfolio_posts_per_page',
6734
			'jetpack_testimonial',
6735
			'jetpack_testimonial_posts_per_page',
6736
			'wp_mobile_custom_css',
6737
			'sharedaddy_disable_resources',
6738
			'sharing-options',
6739
			'sharing-services',
6740
			'site_icon_temp_data',
6741
			'featured-content',
6742
			'site_logo',
6743
		);
6744
6745
		// Flag some Jetpack options as unsafe
6746
		$unsafe_options = array(
6747
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6748
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6749
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6750
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6751
6752
			// non_compact
6753
			'activated',
6754
6755
			// private
6756
			'register',
6757
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6758
			'user_token',                  // (string) The User Token of this site. (deprecated)
6759
			'user_tokens'
6760
		);
6761
6762
		// Remove the unsafe Jetpack options
6763
		foreach ( $unsafe_options as $unsafe_option ) {
6764
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6765
				unset( $all_jp_options[ $key ] );
6766
			}
6767
		}
6768
6769
		$options = array(
6770
			'jp_options' => $all_jp_options,
6771
			'wp_options' => $wp_options
6772
		);
6773
6774
		return $options;
6775
	}
6776
6777
	/**
6778
	 * Check if an option of a Jetpack module has been updated.
6779
	 *
6780
	 * If any module option has been updated before Jump Start has been dismissed,
6781
	 * update the 'jumpstart' option so we can hide Jump Start.
6782
	 *
6783
	 * @param string $option_name
6784
	 *
6785
	 * @return bool
6786
	 */
6787
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6788
		// Bail if Jump Start has already been dismissed
6789
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6790
			return false;
6791
		}
6792
6793
		$jetpack = Jetpack::init();
6794
6795
		// Manual build of module options
6796
		$option_names = self::get_jetpack_options_for_reset();
6797
6798
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6799
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6800
6801
			//Jump start is being dismissed send data to MC Stats
6802
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6803
6804
			$jetpack->do_stats( 'server_side' );
6805
		}
6806
6807
	}
6808
6809
	/*
6810
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6811
	 * so we can bring them directly to their site in calypso.
6812
	 *
6813
	 * @param string | url
6814
	 * @return string | url without the guff
6815
	 */
6816
	public static function build_raw_urls( $url ) {
6817
		$strip_http = '/.*?:\/\//i';
6818
		$url = preg_replace( $strip_http, '', $url  );
6819
		$url = str_replace( '/', '::', $url );
6820
		return $url;
6821
	}
6822
6823
	/**
6824
	 * Stores and prints out domains to prefetch for page speed optimization.
6825
	 *
6826
	 * @param mixed $new_urls
6827
	 */
6828
	public static function dns_prefetch( $new_urls = null ) {
6829
		static $prefetch_urls = array();
6830
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6831
			echo "\r\n";
6832
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6833
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6834
			}
6835
		} elseif ( ! empty( $new_urls ) ) {
6836
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6837
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6838
			}
6839
			foreach ( (array) $new_urls as $this_new_url ) {
6840
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6841
			}
6842
			$prefetch_urls = array_unique( $prefetch_urls );
6843
		}
6844
	}
6845
6846
	public function wp_dashboard_setup() {
6847
		if ( self::is_active() ) {
6848
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6849
			$widget_title = __( 'Site Stats', 'jetpack' );
6850
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6851
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6852
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6853
		}
6854
6855
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6856
			wp_add_dashboard_widget(
6857
				'jetpack_summary_widget',
6858
				$widget_title,
6859
				array( __CLASS__, 'dashboard_widget' )
6860
			);
6861
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6862
6863
			// If we're inactive and not in development mode, sort our box to the top.
6864
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6865
				global $wp_meta_boxes;
6866
6867
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6868
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6869
6870
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6871
			}
6872
		}
6873
	}
6874
6875
	/**
6876
	 * @param mixed $result Value for the user's option
6877
	 * @return mixed
6878
	 */
6879
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6880
		if ( ! is_array( $sorted ) ) {
6881
			return $sorted;
6882
		}
6883
6884
		foreach ( $sorted as $box_context => $ids ) {
6885
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6886
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6887
				continue;
6888
			}
6889
6890
			$ids_array = explode( ',', $ids );
6891
			$key = array_search( 'dashboard_stats', $ids_array );
6892
6893
			if ( false !== $key ) {
6894
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6895
				$ids_array[ $key ] = 'jetpack_summary_widget';
6896
				$sorted[ $box_context ] = implode( ',', $ids_array );
6897
				// We've found it, stop searching, and just return.
6898
				break;
6899
			}
6900
		}
6901
6902
		return $sorted;
6903
	}
6904
6905
	public static function dashboard_widget() {
6906
		/**
6907
		 * Fires when the dashboard is loaded.
6908
		 *
6909
		 * @since 3.4.0
6910
		 */
6911
		do_action( 'jetpack_dashboard_widget' );
6912
	}
6913
6914
	public static function dashboard_widget_footer() {
6915
		?>
6916
		<footer>
6917
6918
		<div class="protect">
6919
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6920
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6921
				<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>
6922
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6923
				<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' ); ?>">
6924
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6925
				</a>
6926
			<?php else : ?>
6927
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6928
			<?php endif; ?>
6929
		</div>
6930
6931
		<div class="akismet">
6932
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6933
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6934
				<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>
6935
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6936
				<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">
6937
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6938
				</a>
6939
			<?php else : ?>
6940
				<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>
6941
			<?php endif; ?>
6942
		</div>
6943
6944
		</footer>
6945
		<?php
6946
	}
6947
6948
	public function dashboard_widget_connect_to_wpcom() {
6949
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6950
			return;
6951
		}
6952
		?>
6953
		<div class="wpcom-connect">
6954
			<div class="jp-emblem">
6955
			<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">
6956
				<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"/>
6957
			</svg>
6958
			</div>
6959
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6960
			<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>
6961
6962
			<div class="actions">
6963
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6964
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6965
				</a>
6966
			</div>
6967
		</div>
6968
		<?php
6969
	}
6970
6971
	/*
6972
	 * A graceful transition to using Core's site icon.
6973
	 *
6974
	 * All of the hard work has already been done with the image
6975
	 * in all_done_page(). All that needs to be done now is update
6976
	 * the option and display proper messaging.
6977
	 *
6978
	 * @todo remove when WP 4.3 is minimum
6979
	 *
6980
	 * @since 3.6.1
6981
	 *
6982
	 * @return bool false = Core's icon not available || true = Core's icon is available
6983
	 */
6984
	public static function jetpack_site_icon_available_in_core() {
6985
		global $wp_version;
6986
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
6987
6988
		if ( ! $core_icon_available ) {
6989
			return false;
6990
		}
6991
6992
		// No need for Jetpack's site icon anymore if core's is already set
6993
		if ( has_site_icon() ) {
6994
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
6995
				Jetpack::log( 'deactivate', 'site-icon' );
6996
				Jetpack::deactivate_module( 'site-icon' );
6997
			}
6998
			return true;
6999
		}
7000
7001
		// Transfer Jetpack's site icon to use core.
7002
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
7003
		if ( $site_icon_id ) {
7004
			// Update core's site icon
7005
			update_option( 'site_icon', $site_icon_id );
7006
7007
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
7008
			delete_option( 'site_icon_id' );
7009
		}
7010
7011
		// No need for Jetpack's site icon anymore
7012
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
7013
			Jetpack::log( 'deactivate', 'site-icon' );
7014
			Jetpack::deactivate_module( 'site-icon' );
7015
		}
7016
7017
		return true;
7018
	}
7019
7020
}
7021