Completed
Push — update/manage-baked-in ( f10b77...0004b4 )
by
unknown
31:21 queued 23:16
created

class.jetpack.php (1 issue)

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