Completed
Push — update/more-activate-module-ev... ( bd246f...1c50f8 )
by
unknown
87:14 queued 77:24
created

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