Completed
Push — add/gui-testing ( 5d6617...131071 )
by
unknown
82:01 queued 73:42
created

class.jetpack.php (14 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'jetpack-responsive-videos-style',
46
		'jetpack-social-menu',
47
		'tiled-gallery',
48
		'jetpack_display_posts_widget',
49
		'gravatar-profile-widget',
50
		'goodreads-widget',
51
		'jetpack_social_media_icons_widget',
52
		'jetpack-top-posts-widget',
53
		'jetpack_image_widget',
54
	);
55
56
	public $plugins_to_deactivate = array(
57
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
59
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
60
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
61
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
62
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
63
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
64
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
65
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
66
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
67
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
68
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
69
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
70
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
71
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
72
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
73
	);
74
75
	static $capability_translations = array(
76
		'administrator' => 'manage_options',
77
		'editor'        => 'edit_others_posts',
78
		'author'        => 'publish_posts',
79
		'contributor'   => 'edit_posts',
80
		'subscriber'    => 'read',
81
	);
82
83
	/**
84
	 * Map of modules that have conflicts with plugins and should not be auto-activated
85
	 * if the plugins are active.  Used by filter_default_modules
86
	 *
87
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
88
	 * change `module-slug` and add this to your plugin:
89
	 *
90
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
91
	 * function my_jetpack_get_default_modules( $modules ) {
92
	 *     return array_diff( $modules, array( 'module-slug' ) );
93
	 * }
94
	 *
95
	 * @var array
96
	 */
97
	private $conflicting_plugins = array(
98
		'comments'          => array(
99
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
100
			'Disqus'                               => 'disqus-comment-system/disqus.php',
101
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
102
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
103
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
104
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
105
		),
106
		'contact-form'      => array(
107
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
108
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
109
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
110
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
111
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
112
		),
113
		'minileven'         => array(
114
			'WPtouch'                              => 'wptouch/wptouch.php',
115
		),
116
		'latex'             => array(
117
			'LaTeX for WordPress'                  => 'latex/latex.php',
118
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
119
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
120
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
121
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
122
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
123
		),
124
		'protect'           => array(
125
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
126
			'Captcha'                              => 'captcha/captcha.php',
127
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
128
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
129
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
130
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
131
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
132
			'Security-protection'                  => 'security-protection/security-protection.php',
133
			'Login Security'                       => 'login-security/login-security.php',
134
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
135
			'Wordfence Security'                   => 'wordfence/wordfence.php',
136
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
137
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
138
		),
139
		'random-redirect'   => array(
140
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
141
		),
142
		'related-posts'     => array(
143
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
144
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
145
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
146
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
147
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
148
			'outbrain'                             => 'outbrain/outbrain.php',
149
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
150
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
151
		),
152
		'sharedaddy'        => array(
153
			'AddThis'                              => 'addthis/addthis_social_widget.php',
154
			'Add To Any'                           => 'add-to-any/add-to-any.php',
155
			'ShareThis'                            => 'share-this/sharethis.php',
156
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
157
		),
158
		'verification-tools' => array(
159
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
160
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
161
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
162
		),
163
		'widget-visibility' => array(
164
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
165
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
166
		),
167
		'sitemaps' => array(
168
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
169
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
170
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
171
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
172
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
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
			'Sitemap'                              => 'sitemap/sitemap.php',
177
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
178
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
179
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
180
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
181
		),
182
	);
183
184
	/**
185
	 * Plugins for which we turn off our Facebook OG Tags implementation.
186
	 *
187
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
188
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
189
	 *
190
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
191
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
192
	 */
193
	private $open_graph_conflicting_plugins = array(
194
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
195
		                                                         // 2 Click Social Media Buttons
196
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
197
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
198
		'autodescription/autodescription.php',                   // The SEO Framework
199
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
200
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
201
		                                                         // Open Graph Meta Tags by Heateor
202
		'facebook/facebook.php',                                 // Facebook (official plugin)
203
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
204
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
205
		                                                         // Facebook Featured Image & OG Meta Tags
206
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
207
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
208
		                                                         // Facebook Open Graph Meta Tags for WordPress
209
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
210
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
211
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
212
		                                                         // Fedmich's Facebook Open Graph Meta
213
		'header-footer/plugin.php',                              // Header and Footer
214
		'network-publisher/networkpub.php',                      // Network Publisher
215
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
216
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
217
		                                                         // NextScripts SNAP
218
		'og-tags/og-tags.php',                                   // OG Tags
219
		'opengraph/opengraph.php',                               // Open Graph
220
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
221
		                                                         // Open Graph Protocol Framework
222
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
223
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
224
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
225
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
226
		'sharepress/sharepress.php',                             // SharePress
227
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
228
		'social-discussions/social-discussions.php',             // Social Discussions
229
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
230
		'socialize/socialize.php',                               // Socialize
231
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
232
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
233
		                                                         // Tweet, Like, Google +1 and Share
234
		'wordbooker/wordbooker.php',                             // Wordbooker
235
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
236
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
237
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
238
		                                                         // WP Facebook Like Send & Open Graph Meta
239
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
240
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
241
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
242
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
243
	);
244
245
	/**
246
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
247
	 */
248
	private $twitter_cards_conflicting_plugins = array(
249
	//	'twitter/twitter.php',                       // The official one handles this on its own.
250
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
251
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
252
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
253
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
254
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
255
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
256
		'twitter-cards/twitter-cards.php',           // Twitter Cards
257
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
258
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
259
	);
260
261
	/**
262
	 * Message to display in admin_notice
263
	 * @var string
264
	 */
265
	public $message = '';
266
267
	/**
268
	 * Error to display in admin_notice
269
	 * @var string
270
	 */
271
	public $error = '';
272
273
	/**
274
	 * Modules that need more privacy description.
275
	 * @var string
276
	 */
277
	public $privacy_checks = '';
278
279
	/**
280
	 * Stats to record once the page loads
281
	 *
282
	 * @var array
283
	 */
284
	public $stats = array();
285
286
	/**
287
	 * Jetpack_Sync object
288
	 */
289
	public $sync;
290
291
	/**
292
	 * Verified data for JSON authorization request
293
	 */
294
	public $json_api_authorization_request = array();
295
296
	/**
297
	 * Holds the singleton instance of this class
298
	 * @since 2.3.3
299
	 * @var Jetpack
300
	 */
301
	static $instance = false;
302
303
	/**
304
	 * Singleton
305
	 * @static
306
	 */
307
	public static function init() {
308
		if ( ! self::$instance ) {
309
			self::$instance = new Jetpack;
310
311
			self::$instance->plugin_upgrade();
312
		}
313
314
		return self::$instance;
315
	}
316
317
	/**
318
	 * Must never be called statically
319
	 */
320
	function plugin_upgrade() {
321
		if ( Jetpack::is_active() ) {
322
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
323
			if ( JETPACK__VERSION != $version ) {
324
325
				// Check which active modules actually exist and remove others from active_modules list
326
				$unfiltered_modules = Jetpack::get_active_modules();
327
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
328
				if ( array_diff( $unfiltered_modules, $modules ) ) {
329
					Jetpack::update_active_modules( $modules );
330
				}
331
332
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
333
334
				// Upgrade to 4.3.0
335
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
336
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
337
				}
338
339
				Jetpack::maybe_set_version_option();
340
			}
341
		}
342
	}
343
344
	static function activate_manage( ) {
345
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
346
			self::activate_module( 'manage', false, false );
347
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
348
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
349
		}
350
	}
351
352
	static function update_active_modules( $modules ) {
353
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
354
355
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
356
357
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
358
			$new_active_modules = array_diff( $modules, $current_modules );
359
			foreach( $new_active_modules as $module ) {
360
				/**
361
				 * Fires when a specific module is activated.
362
				 *
363
				 * @since 1.9.0
364
				 *
365
				 * @param string $module Module slug.
366
				 * @param boolean $success whether the module was activated. @since 4.2
367
				 */
368
				do_action( 'jetpack_activate_module', $module, $success );
369
370
				/**
371
				 * Fires when a module is activated.
372
				 * The dynamic part of the filter, $module, is the module slug.
373
				 *
374
				 * @since 1.9.0
375
				 *
376
				 * @param string $module Module slug.
377
				 */
378
				do_action( "jetpack_activate_module_$module", $module );
379
			}
380
381
			$new_deactive_modules = array_diff( $current_modules, $modules );
382
			foreach( $new_deactive_modules as $module ) {
383
				/**
384
				 * Fired after a module has been deactivated.
385
				 *
386
				 * @since 4.2.0
387
				 *
388
				 * @param string $module Module slug.
389
				 * @param boolean $success whether the module was deactivated.
390
				 */
391
				do_action( 'jetpack_deactivate_module', $module, $success );
392
				/**
393
				 * Fires when a module is deactivated.
394
				 * The dynamic part of the filter, $module, is the module slug.
395
				 *
396
				 * @since 1.9.0
397
				 *
398
				 * @param string $module Module slug.
399
				 */
400
				do_action( "jetpack_deactivate_module_$module", $module );
401
			}
402
		}
403
404
		return $success;
405
	}
406
407
	static function delete_active_modules() {
408
		self::update_active_modules( array() );
409
	}
410
411
	/**
412
	 * Constructor.  Initializes WordPress hooks
413
	 */
414
	private function __construct() {
415
		/*
416
		 * Check for and alert any deprecated hooks
417
		 */
418
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
419
420
421
		/*
422
		 * Load things that should only be in Network Admin.
423
		 *
424
		 * For now blow away everything else until a more full
425
		 * understanding of what is needed at the network level is
426
		 * available
427
		 */
428
		if( is_multisite() ) {
429
			Jetpack_Network::init();
430
		}
431
432
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
433
434
		// Unlink user before deleting the user from .com
435
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
436
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
437
438
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
439
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
440
441
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
442
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
443
444
			$this->require_jetpack_authentication();
445
446
			if ( Jetpack::is_active() ) {
447
				// Hack to preserve $HTTP_RAW_POST_DATA
448
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
449
450
				$signed = $this->verify_xml_rpc_signature();
451
				if ( $signed && ! is_wp_error( $signed ) ) {
452
					// The actual API methods.
453
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
454
				} else {
455
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
456
					// active Jetpack connection, so that additional users can link their account.
457
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
458
				}
459
			} else {
460
				// The bootstrap API methods.
461
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
462
			}
463
464
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
465
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
466
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
467
			$this->require_jetpack_authentication();
468
			$this->add_remote_request_handlers();
469
		} else {
470
			if ( Jetpack::is_active() ) {
471
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
472
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
473
			}
474
		}
475
476
		if ( Jetpack::is_active() ) {
477
			Jetpack_Heartbeat::init();
478
		}
479
480
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
481
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
482
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
483
		}
484
485
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
486
487
		add_action( 'admin_init', array( $this, 'admin_init' ) );
488
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
489
490
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
491
492
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
493
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
494
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
495
496
		// returns HTTPS support status
497
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
498
499
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
500
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
501
502
		// JITM AJAX callback function
503
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
504
505
		// Universal ajax callback for all tracking events triggered via js
506
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
507
508
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
509
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
510
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
511
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
512
513
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
514
515
		/**
516
		 * These actions run checks to load additional files.
517
		 * They check for external files or plugins, so they need to run as late as possible.
518
		 */
519
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
520
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
521
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
522
523
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
524
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
525
526
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
527
528
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
529
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
530
531
		// A filter to control all just in time messages
532
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
533
534
		/**
535
		 * This is the hack to concatinate all css files into one.
536
		 * For description and reasoning see the implode_frontend_css method
537
		 *
538
		 * Super late priority so we catch all the registered styles
539
		 */
540
		if( !is_admin() ) {
541
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
542
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
543
		}
544
545
	}
546
547
	function jetpack_admin_ajax_tracks_callback() {
548
		// Check for nonce
549
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
550
			wp_die( 'Permissions check failed.' );
551
		}
552
553
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
554
			wp_die( 'No valid event name or type.' );
555
		}
556
557
		$tracks_data = array();
558
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
559
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
560
		}
561
562
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
563
		wp_send_json_success();
564
		wp_die();
565
	}
566
567
	/**
568
	 * The callback for the JITM ajax requests.
569
	 */
570
	function jetpack_jitm_ajax_callback() {
571
		// Check for nonce
572
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
573
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
574
		}
575
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
576
			$module_slug = $_REQUEST['jitmModule'];
577
			Jetpack::log( 'activate', $module_slug );
578
			Jetpack::activate_module( $module_slug, false, false );
579
			Jetpack::state( 'message', 'no_message' );
580
581
			//A Jetpack module is being activated through a JITM, track it
582
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
583
			$this->do_stats( 'server_side' );
584
585
			wp_send_json_success();
586
		}
587
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
588
			// get the hide_jitm options array
589
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
590
			$module_slug = $_REQUEST['jitmModule'];
591
592
			if( ! $jetpack_hide_jitm ) {
593
				$jetpack_hide_jitm = array(
594
					$module_slug => 'hide'
595
				);
596
			} else {
597
				$jetpack_hide_jitm[$module_slug] = 'hide';
598
			}
599
600
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
601
602
			//jitm is being dismissed forever, track it
603
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
604
			$this->do_stats( 'server_side' );
605
606
			wp_send_json_success();
607
		}
608 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
609
			$module_slug = $_REQUEST['jitmModule'];
610
611
			// User went to WordPress.com, track this
612
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
613
			$this->do_stats( 'server_side' );
614
615
			wp_send_json_success();
616
		}
617 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
618
			$track = $_REQUEST['jitmModule'];
619
620
			// User is viewing JITM, track it.
621
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
622
			$this->do_stats( 'server_side' );
623
624
			wp_send_json_success();
625
		}
626
	}
627
628
	/**
629
	 * If there are any stats that need to be pushed, but haven't been, push them now.
630
	 */
631
	function __destruct() {
632
		if ( ! empty( $this->stats ) ) {
633
			$this->do_stats( 'server_side' );
634
		}
635
	}
636
637
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
638
		switch( $cap ) {
639
			case 'jetpack_connect' :
640
			case 'jetpack_reconnect' :
641
				if ( Jetpack::is_development_mode() ) {
642
					$caps = array( 'do_not_allow' );
643
					break;
644
				}
645
				/**
646
				 * Pass through. If it's not development mode, these should match disconnect.
647
				 * Let users disconnect if it's development mode, just in case things glitch.
648
				 */
649
			case 'jetpack_disconnect' :
650
				/**
651
				 * In multisite, can individual site admins manage their own connection?
652
				 *
653
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
654
				 */
655
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
656
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
657
						/**
658
						 * We need to update the option name -- it's terribly unclear which
659
						 * direction the override goes.
660
						 *
661
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
662
						 */
663
						$caps = array( 'do_not_allow' );
664
						break;
665
					}
666
				}
667
668
				$caps = array( 'manage_options' );
669
				break;
670
			case 'jetpack_manage_modules' :
671
			case 'jetpack_activate_modules' :
672
			case 'jetpack_deactivate_modules' :
673
				$caps = array( 'manage_options' );
674
				break;
675
			case 'jetpack_configure_modules' :
676
				$caps = array( 'manage_options' );
677
				break;
678
			case 'jetpack_network_admin_page':
679
			case 'jetpack_network_settings_page':
680
				$caps = array( 'manage_network_plugins' );
681
				break;
682
			case 'jetpack_network_sites_page':
683
				$caps = array( 'manage_sites' );
684
				break;
685
			case 'jetpack_admin_page' :
686
				if ( Jetpack::is_development_mode() ) {
687
					$caps = array( 'manage_options' );
688
					break;
689
				} else {
690
					$caps = array( 'read' );
691
				}
692
				break;
693
			case 'jetpack_connect_user' :
694
				if ( Jetpack::is_development_mode() ) {
695
					$caps = array( 'do_not_allow' );
696
					break;
697
				}
698
				$caps = array( 'read' );
699
				break;
700
		}
701
		return $caps;
702
	}
703
704
	function require_jetpack_authentication() {
705
		// Don't let anyone authenticate
706
		$_COOKIE = array();
707
		remove_all_filters( 'authenticate' );
708
		remove_all_actions( 'wp_login_failed' );
709
710
		if ( Jetpack::is_active() ) {
711
			// Allow Jetpack authentication
712
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
713
		}
714
	}
715
716
	/**
717
	 * Load language files
718
	 * @action plugins_loaded
719
	 */
720
	public static function plugin_textdomain() {
721
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
722
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
723
	}
724
725
	/**
726
	 * Register assets for use in various modules and the Jetpack admin page.
727
	 *
728
	 * @uses wp_script_is, wp_register_script, plugins_url
729
	 * @action wp_loaded
730
	 * @return null
731
	 */
732
	public function register_assets() {
733
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
734
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
735
		}
736
737 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
738
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
739
		}
740
741 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
742
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
743
		}
744
745 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
746
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
747
		}
748
749
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
750
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
751
752
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
753
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
754
			if ( ! is_numeric( $fb_app_id ) ) {
755
				$fb_app_id = '';
756
			}
757
			wp_localize_script(
758
				'jetpack-facebook-embed',
759
				'jpfbembed',
760
				array(
761
					'appid' => $fb_app_id,
762
					'locale' => $this->get_locale(),
763
				)
764
			);
765
		}
766
767
		/**
768
		 * As jetpack_register_genericons is by default fired off a hook,
769
		 * the hook may have already fired by this point.
770
		 * So, let's just trigger it manually.
771
		 */
772
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
773
		jetpack_register_genericons();
774
775
		/**
776
		 * Register the social logos
777
		 */
778
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
779
		jetpack_register_social_logos();
780
781 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
782
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
783
	}
784
785
	/**
786
	 * Guess locale from language code.
787
	 *
788
	 * @param string $lang Language code.
789
	 * @return string|bool
790
	 */
791 View Code Duplication
	function guess_locale_from_lang( $lang ) {
792
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
793
			return 'en_US';
794
		}
795
796
		if ( ! class_exists( 'GP_Locales' ) ) {
797
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
798
				return false;
799
			}
800
801
			require JETPACK__GLOTPRESS_LOCALES_PATH;
802
		}
803
804
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
805
			// WP.com: get_locale() returns 'it'
806
			$locale = GP_Locales::by_slug( $lang );
807
		} else {
808
			// Jetpack: get_locale() returns 'it_IT';
809
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
810
		}
811
812
		if ( ! $locale ) {
813
			return false;
814
		}
815
816
		if ( empty( $locale->facebook_locale ) ) {
817
			if ( empty( $locale->wp_locale ) ) {
818
				return false;
819
			} else {
820
				// Facebook SDK is smart enough to fall back to en_US if a
821
				// locale isn't supported. Since supported Facebook locales
822
				// can fall out of sync, we'll attempt to use the known
823
				// wp_locale value and rely on said fallback.
824
				return $locale->wp_locale;
825
			}
826
		}
827
828
		return $locale->facebook_locale;
829
	}
830
831
	/**
832
	 * Get the locale.
833
	 *
834
	 * @return string|bool
835
	 */
836
	function get_locale() {
837
		$locale = $this->guess_locale_from_lang( get_locale() );
838
839
		if ( ! $locale ) {
840
			$locale = 'en_US';
841
		}
842
843
		return $locale;
844
	}
845
846
	/**
847
	 * Device Pixels support
848
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
849
	 */
850
	function devicepx() {
851
		if ( Jetpack::is_active() ) {
852
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
853
		}
854
	}
855
856
	/**
857
	 * Return the network_site_url so that .com knows what network this site is a part of.
858
	 * @param  bool $option
859
	 * @return string
860
	 */
861
	public function jetpack_main_network_site_option( $option ) {
862
		return network_site_url();
863
	}
864
	/**
865
	 * Network Name.
866
	 */
867
	static function network_name( $option = null ) {
868
		global $current_site;
869
		return $current_site->site_name;
870
	}
871
	/**
872
	 * Does the network allow new user and site registrations.
873
	 * @return string
874
	 */
875
	static function network_allow_new_registrations( $option = null ) {
876
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
877
	}
878
	/**
879
	 * Does the network allow admins to add new users.
880
	 * @return boolian
881
	 */
882
	static function network_add_new_users( $option = null ) {
883
		return (bool) get_site_option( 'add_new_users' );
884
	}
885
	/**
886
	 * File upload psace left per site in MB.
887
	 *  -1 means NO LIMIT.
888
	 * @return number
889
	 */
890
	static function network_site_upload_space( $option = null ) {
891
		// value in MB
892
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
893
	}
894
895
	/**
896
	 * Network allowed file types.
897
	 * @return string
898
	 */
899
	static function network_upload_file_types( $option = null ) {
900
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
901
	}
902
903
	/**
904
	 * Maximum file upload size set by the network.
905
	 * @return number
906
	 */
907
	static function network_max_upload_file_size( $option = null ) {
908
		// value in KB
909
		return get_site_option( 'fileupload_maxk', 300 );
910
	}
911
912
	/**
913
	 * Lets us know if a site allows admins to manage the network.
914
	 * @return array
915
	 */
916
	static function network_enable_administration_menus( $option = null ) {
917
		return get_site_option( 'menu_items' );
918
	}
919
920
	/**
921
	 * If a user has been promoted to or demoted from admin, we need to clear the
922
	 * jetpack_other_linked_admins transient.
923
	 *
924
	 * @since 4.3.2
925
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
926
	 *
927
	 * @param int    $user_id   The user ID whose role changed.
928
	 * @param string $role      The new role.
929
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
930
	 */
931
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
932
		if ( 'administrator' == $role
933
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
934
			|| is_null( $old_roles )
935
		) {
936
			delete_transient( 'jetpack_other_linked_admins' );
937
		}
938
	}
939
940
	/**
941
	 * Checks to see if there are any other users available to become primary
942
	 * Users must both:
943
	 * - Be linked to wpcom
944
	 * - Be an admin
945
	 *
946
	 * @return mixed False if no other users are linked, Int if there are.
947
	 */
948
	static function get_other_linked_admins() {
949
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
950
951
		if ( false === $other_linked_users ) {
952
			$admins = get_users( array( 'role' => 'administrator' ) );
953
			if ( count( $admins ) > 1 ) {
954
				$available = array();
955
				foreach ( $admins as $admin ) {
956
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
957
						$available[] = $admin->ID;
958
					}
959
				}
960
961
				$count_connected_admins = count( $available );
962
				if ( count( $available ) > 1 ) {
963
					$other_linked_users = $count_connected_admins;
964
				} else {
965
					$other_linked_users = 0;
966
				}
967
			} else {
968
				$other_linked_users = 0;
969
			}
970
971
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
972
		}
973
974
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
975
	}
976
977
	/**
978
	 * Return whether we are dealing with a multi network setup or not.
979
	 * The reason we are type casting this is because we want to avoid the situation where
980
	 * the result is false since when is_main_network_option return false it cases
981
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
982
	 * database which could be set to anything as opposed to what this function returns.
983
	 * @param  bool  $option
984
	 *
985
	 * @return boolean
986
	 */
987
	public function is_main_network_option( $option ) {
988
		// return '1' or ''
989
		return (string) (bool) Jetpack::is_multi_network();
990
	}
991
992
	/**
993
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
994
	 *
995
	 * @param  string  $option
996
	 * @return boolean
997
	 */
998
	public function is_multisite( $option ) {
999
		return (string) (bool) is_multisite();
1000
	}
1001
1002
	/**
1003
	 * Implemented since there is no core is multi network function
1004
	 * Right now there is no way to tell if we which network is the dominant network on the system
1005
	 *
1006
	 * @since  3.3
1007
	 * @return boolean
1008
	 */
1009
	public static function is_multi_network() {
1010
		global  $wpdb;
1011
1012
		// if we don't have a multi site setup no need to do any more
1013
		if ( ! is_multisite() ) {
1014
			return false;
1015
		}
1016
1017
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1018
		if ( $num_sites > 1 ) {
1019
			return true;
1020
		} else {
1021
			return false;
1022
		}
1023
	}
1024
1025
	/**
1026
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1027
	 * @return null
1028
	 */
1029
	function update_jetpack_main_network_site_option() {
1030
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1031
	}
1032
	/**
1033
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1034
	 *
1035
	 */
1036
	function update_jetpack_network_settings() {
1037
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1038
		// Only sync this info for the main network site.
1039
	}
1040
1041
	/**
1042
	 * Get back if the current site is single user site.
1043
	 *
1044
	 * @return bool
1045
	 */
1046
	public static function is_single_user_site() {
1047
		global $wpdb;
1048
		$some_users = $wpdb->get_var( "select count(*) from (select user_id from $wpdb->usermeta where meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) as someusers" );
1049
		return 1 === (int) $some_users;
1050
	}
1051
1052
	/**
1053
	 * Returns true if the site has file write access false otherwise.
1054
	 * @return string ( '1' | '0' )
1055
	 **/
1056
	public static function file_system_write_access() {
1057
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1058
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1059
		}
1060
1061
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1062
1063
		$filesystem_method = get_filesystem_method();
1064
		if ( $filesystem_method === 'direct' ) {
1065
			return 1;
1066
		}
1067
1068
		ob_start();
1069
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1070
		ob_end_clean();
1071
		if ( $filesystem_credentials_are_stored ) {
1072
			return 1;
1073
		}
1074
		return 0;
1075
	}
1076
1077
	/**
1078
	 * Finds out if a site is using a version control system.
1079
	 * @return string ( '1' | '0' )
1080
	 **/
1081
	public static function is_version_controlled() {
1082
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1083
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1084
	}
1085
1086
	/**
1087
	 * Determines whether the current theme supports featured images or not.
1088
	 * @return string ( '1' | '0' )
1089
	 */
1090
	public static function featured_images_enabled() {
1091
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1092
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1093
	}
1094
1095
	/**
1096
	 * jetpack_updates is saved in the following schema:
1097
	 *
1098
	 * array (
1099
	 *      'plugins'                       => (int) Number of plugin updates available.
1100
	 *      'themes'                        => (int) Number of theme updates available.
1101
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1102
	 *      'translations'                  => (int) Number of translation updates available.
1103
	 *      'total'                         => (int) Total of all available updates.
1104
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1105
	 * )
1106
	 * @return array
1107
	 */
1108
	public static function get_updates() {
1109
		$update_data = wp_get_update_data();
1110
1111
		// Stores the individual update counts as well as the total count.
1112
		if ( isset( $update_data['counts'] ) ) {
1113
			$updates = $update_data['counts'];
1114
		}
1115
1116
		// If we need to update WordPress core, let's find the latest version number.
1117 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1118
			$cur = get_preferred_from_update_core();
1119
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1120
				$updates['wp_update_version'] = $cur->current;
1121
			}
1122
		}
1123
		return isset( $updates ) ? $updates : array();
1124
	}
1125
1126
	public static function get_update_details() {
1127
		$update_details = array(
1128
			'update_core' => get_site_transient( 'update_core' ),
1129
			'update_plugins' => get_site_transient( 'update_plugins' ),
1130
			'update_themes' => get_site_transient( 'update_themes' ),
1131
		);
1132
		return $update_details;
1133
	}
1134
1135
	public static function refresh_update_data() {
1136
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1137
1138
	}
1139
1140
	public static function refresh_theme_data() {
1141
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1142
	}
1143
1144
	/**
1145
	 * Is Jetpack active?
1146
	 */
1147
	public static function is_active() {
1148
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1149
	}
1150
1151
	/**
1152
	 * Is Jetpack in development (offline) mode?
1153
	 */
1154
	public static function is_development_mode() {
1155
		$development_mode = false;
1156
1157
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1158
			$development_mode = JETPACK_DEV_DEBUG;
1159
		}
1160
1161
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1162
			$development_mode = true;
1163
		}
1164
		/**
1165
		 * Filters Jetpack's development mode.
1166
		 *
1167
		 * @see https://jetpack.com/support/development-mode/
1168
		 *
1169
		 * @since 2.2.1
1170
		 *
1171
		 * @param bool $development_mode Is Jetpack's development mode active.
1172
		 */
1173
		return apply_filters( 'jetpack_development_mode', $development_mode );
1174
	}
1175
1176
	/**
1177
	* Get Jetpack development mode notice text and notice class.
1178
	*
1179
	* Mirrors the checks made in Jetpack::is_development_mode
1180
	*
1181
	*/
1182
	public static function show_development_mode_notice() {
1183
		if ( Jetpack::is_development_mode() ) {
1184
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1185
				$notice = sprintf(
1186
					/* translators: %s is a URL */
1187
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1188
					'https://jetpack.com/support/development-mode/'
1189
				);
1190
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1191
				$notice = sprintf(
1192
					/* translators: %s is a URL */
1193
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1194
					'https://jetpack.com/support/development-mode/'
1195
				);
1196
			} else {
1197
				$notice = sprintf(
1198
					/* translators: %s is a URL */
1199
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1200
					'https://jetpack.com/support/development-mode/'
1201
				);
1202
			}
1203
1204
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1205
		}
1206
1207
		// Throw up a notice if using a development version and as for feedback.
1208
		if ( Jetpack::is_development_version() ) {
1209
			/* translators: %s is a URL */
1210
			$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/' );
1211
1212
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1213
		}
1214
		// Throw up a notice if using staging mode
1215
		if ( Jetpack::is_staging_site() ) {
1216
			/* translators: %s is a URL */
1217
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1218
1219
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1220
		}
1221
	}
1222
1223
	/**
1224
	 * Whether Jetpack's version maps to a public release, or a development version.
1225
	 */
1226
	public static function is_development_version() {
1227
		/**
1228
		 * Allows filtering whether this is a development version of Jetpack.
1229
		 *
1230
		 * This filter is especially useful for tests.
1231
		 *
1232
		 * @since 4.3.0
1233
		 *
1234
		 * @param bool $development_version Is this a develoment version of Jetpack?
1235
		 */
1236
		return (bool) apply_filters(
1237
			'jetpack_development_version',
1238
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1239
		);
1240
	}
1241
1242
	/**
1243
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1244
	 */
1245
	public static function is_user_connected( $user_id = false ) {
1246
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1247
		if ( ! $user_id ) {
1248
			return false;
1249
		}
1250
1251
		return (bool) Jetpack_Data::get_access_token( $user_id );
1252
	}
1253
1254
	/**
1255
	 * Get the wpcom user data of the current|specified connected user.
1256
	 */
1257
	public static function get_connected_user_data( $user_id = null ) {
1258
		if ( ! $user_id ) {
1259
			$user_id = get_current_user_id();
1260
		}
1261
1262
		$transient_key = "jetpack_connected_user_data_$user_id";
1263
1264
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1265
			return $cached_user_data;
1266
		}
1267
1268
		Jetpack::load_xml_rpc_client();
1269
		$xml = new Jetpack_IXR_Client( array(
1270
			'user_id' => $user_id,
1271
		) );
1272
		$xml->query( 'wpcom.getUser' );
1273
		if ( ! $xml->isError() ) {
1274
			$user_data = $xml->getResponse();
1275
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1276
			return $user_data;
1277
		}
1278
1279
		return false;
1280
	}
1281
1282
	/**
1283
	 * Get the wpcom email of the current|specified connected user.
1284
	 */
1285 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1286
		if ( ! $user_id ) {
1287
			$user_id = get_current_user_id();
1288
		}
1289
		Jetpack::load_xml_rpc_client();
1290
		$xml = new Jetpack_IXR_Client( array(
1291
			'user_id' => $user_id,
1292
		) );
1293
		$xml->query( 'wpcom.getUserEmail' );
1294
		if ( ! $xml->isError() ) {
1295
			return $xml->getResponse();
1296
		}
1297
		return false;
1298
	}
1299
1300
	/**
1301
	 * Get the wpcom email of the master user.
1302
	 */
1303
	public static function get_master_user_email() {
1304
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1305
		if ( $master_user_id ) {
1306
			return self::get_connected_user_email( $master_user_id );
1307
		}
1308
		return '';
1309
	}
1310
1311
	function current_user_is_connection_owner() {
1312
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1313
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1314
	}
1315
1316
	/**
1317
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1318
	 */
1319
	function extra_oembed_providers() {
1320
		// Cloudup: https://dev.cloudup.com/#oembed
1321
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1322
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1323
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1324
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1325
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1326
	}
1327
1328
	/**
1329
	 * Synchronize connected user role changes
1330
	 */
1331
	function user_role_change( $user_id ) {
1332
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1333
		Jetpack_Sync_Users::user_role_change( $user_id );
1334
	}
1335
1336
	/**
1337
	 * Loads the currently active modules.
1338
	 */
1339
	public static function load_modules() {
1340
		if ( ! self::is_active() && !self::is_development_mode() ) {
1341
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1342
				return;
1343
			}
1344
		}
1345
1346
		$version = Jetpack_Options::get_option( 'version' );
1347 View Code Duplication
		if ( ! $version ) {
1348
			$version = $old_version = JETPACK__VERSION . ':' . time();
1349
			/** This action is documented in class.jetpack.php */
1350
			do_action( 'updating_jetpack_version', $version, false );
1351
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1352
		}
1353
		list( $version ) = explode( ':', $version );
1354
1355
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1356
1357
		$modules_data = array();
1358
1359
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1360
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1361
			$updated_modules = array();
1362
			foreach ( $modules as $module ) {
1363
				$modules_data[ $module ] = Jetpack::get_module( $module );
1364
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1365
					continue;
1366
				}
1367
1368
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1369
					continue;
1370
				}
1371
1372
				$updated_modules[] = $module;
1373
			}
1374
1375
			$modules = array_diff( $modules, $updated_modules );
1376
		}
1377
1378
		$is_development_mode = Jetpack::is_development_mode();
1379
1380
		foreach ( $modules as $index => $module ) {
1381
			// If we're in dev mode, disable modules requiring a connection
1382
			if ( $is_development_mode ) {
1383
				// Prime the pump if we need to
1384
				if ( empty( $modules_data[ $module ] ) ) {
1385
					$modules_data[ $module ] = Jetpack::get_module( $module );
1386
				}
1387
				// If the module requires a connection, but we're in local mode, don't include it.
1388
				if ( $modules_data[ $module ]['requires_connection'] ) {
1389
					continue;
1390
				}
1391
			}
1392
1393
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1394
				continue;
1395
			}
1396
1397
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1398
				unset( $modules[ $index ] );
1399
				self::update_active_modules( array_values( $modules ) );
1400
				continue;
1401
			}
1402
1403
			/**
1404
			 * Fires when a specific module is loaded.
1405
			 * The dynamic part of the hook, $module, is the module slug.
1406
			 *
1407
			 * @since 1.1.0
1408
			 */
1409
			do_action( 'jetpack_module_loaded_' . $module );
1410
		}
1411
1412
		/**
1413
		 * Fires when all the modules are loaded.
1414
		 *
1415
		 * @since 1.1.0
1416
		 */
1417
		do_action( 'jetpack_modules_loaded' );
1418
1419
		// 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.
1420
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1421
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1422
	}
1423
1424
	/**
1425
	 * Check if Jetpack's REST API compat file should be included
1426
	 * @action plugins_loaded
1427
	 * @return null
1428
	 */
1429
	public function check_rest_api_compat() {
1430
		/**
1431
		 * Filters the list of REST API compat files to be included.
1432
		 *
1433
		 * @since 2.2.5
1434
		 *
1435
		 * @param array $args Array of REST API compat files to include.
1436
		 */
1437
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1438
1439
		if ( function_exists( 'bbpress' ) )
1440
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1441
1442
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1443
			require_once $_jetpack_rest_api_compat_include;
1444
	}
1445
1446
	/**
1447
	 * Gets all plugins currently active in values, regardless of whether they're
1448
	 * traditionally activated or network activated.
1449
	 *
1450
	 * @todo Store the result in core's object cache maybe?
1451
	 */
1452
	public static function get_active_plugins() {
1453
		$active_plugins = (array) get_option( 'active_plugins', array() );
1454
1455
		if ( is_multisite() ) {
1456
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1457
			// whereas active_plugins stores them in the values.
1458
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1459
			if ( $network_plugins ) {
1460
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1461
			}
1462
		}
1463
1464
		sort( $active_plugins );
1465
1466
		return array_unique( $active_plugins );
1467
	}
1468
1469
	/**
1470
	 * Gets and parses additional plugin data to send with the heartbeat data
1471
	 *
1472
	 * @since 3.8.1
1473
	 *
1474
	 * @return array Array of plugin data
1475
	 */
1476
	public static function get_parsed_plugin_data() {
1477
		if ( ! function_exists( 'get_plugins' ) ) {
1478
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1479
		}
1480
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1481
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1482
		$active_plugins = Jetpack::get_active_plugins();
1483
1484
		$plugins = array();
1485
		foreach ( $all_plugins as $path => $plugin_data ) {
1486
			$plugins[ $path ] = array(
1487
					'is_active' => in_array( $path, $active_plugins ),
1488
					'file'      => $path,
1489
					'name'      => $plugin_data['Name'],
1490
					'version'   => $plugin_data['Version'],
1491
					'author'    => $plugin_data['Author'],
1492
			);
1493
		}
1494
1495
		return $plugins;
1496
	}
1497
1498
	/**
1499
	 * Gets and parses theme data to send with the heartbeat data
1500
	 *
1501
	 * @since 3.8.1
1502
	 *
1503
	 * @return array Array of theme data
1504
	 */
1505
	public static function get_parsed_theme_data() {
1506
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1507
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1508
1509
		$themes = array();
1510
		foreach ( $all_themes as $slug => $theme_data ) {
1511
			$theme_headers = array();
1512
			foreach ( $header_keys as $header_key ) {
1513
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1514
			}
1515
1516
			$themes[ $slug ] = array(
1517
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1518
					'slug' => $slug,
1519
					'theme_root' => $theme_data->get_theme_root_uri(),
1520
					'parent' => $theme_data->parent(),
1521
					'headers' => $theme_headers
1522
			);
1523
		}
1524
1525
		return $themes;
1526
	}
1527
1528
	/**
1529
	 * Checks whether a specific plugin is active.
1530
	 *
1531
	 * We don't want to store these in a static variable, in case
1532
	 * there are switch_to_blog() calls involved.
1533
	 */
1534
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1535
		return in_array( $plugin, self::get_active_plugins() );
1536
	}
1537
1538
	/**
1539
	 * Check if Jetpack's Open Graph tags should be used.
1540
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1541
	 *
1542
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1543
	 * @action plugins_loaded
1544
	 * @return null
1545
	 */
1546
	public function check_open_graph() {
1547
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1548
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1549
		}
1550
1551
		$active_plugins = self::get_active_plugins();
1552
1553
		if ( ! empty( $active_plugins ) ) {
1554
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1555
				if ( in_array( $plugin, $active_plugins ) ) {
1556
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1557
					break;
1558
				}
1559
			}
1560
		}
1561
1562
		/**
1563
		 * Allow the addition of Open Graph Meta Tags to all pages.
1564
		 *
1565
		 * @since 2.0.3
1566
		 *
1567
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1568
		 */
1569
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1570
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1571
		}
1572
	}
1573
1574
	/**
1575
	 * Check if Jetpack's Twitter tags should be used.
1576
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1577
	 *
1578
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1579
	 * @action plugins_loaded
1580
	 * @return null
1581
	 */
1582
	public function check_twitter_tags() {
1583
1584
		$active_plugins = self::get_active_plugins();
1585
1586
		if ( ! empty( $active_plugins ) ) {
1587
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1588
				if ( in_array( $plugin, $active_plugins ) ) {
1589
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1590
					break;
1591
				}
1592
			}
1593
		}
1594
1595
		/**
1596
		 * Allow Twitter Card Meta tags to be disabled.
1597
		 *
1598
		 * @since 2.6.0
1599
		 *
1600
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1601
		 */
1602
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1603
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1604
		}
1605
	}
1606
1607
	/**
1608
	 * Allows plugins to submit security reports.
1609
 	 *
1610
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1611
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1612
	 * @param array   $args         See definitions above
1613
	 */
1614
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1615
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1616
	}
1617
1618
/* Jetpack Options API */
1619
1620
	public static function get_option_names( $type = 'compact' ) {
1621
		return Jetpack_Options::get_option_names( $type );
1622
	}
1623
1624
	/**
1625
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1626
 	 *
1627
	 * @param string $name    Option name
1628
	 * @param mixed  $default (optional)
1629
	 */
1630
	public static function get_option( $name, $default = false ) {
1631
		return Jetpack_Options::get_option( $name, $default );
1632
	}
1633
1634
	/**
1635
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1636
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1637
	* $name must be a registered option name.
1638
	*/
1639
	public static function create_nonce( $name ) {
1640
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1641
1642
		Jetpack_Options::update_option( $name, $secret );
1643
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1644
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1645
			return new Jetpack_Error( 'missing_secrets' );
1646
1647
		return array(
1648
			'secret_1' => $secret_1,
1649
			'secret_2' => $secret_2,
1650
			'eol'      => $eol,
1651
		);
1652
	}
1653
1654
	/**
1655
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1656
 	 *
1657
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1658
	 * @param string $name  Option name
1659
	 * @param mixed  $value Option value
1660
	 */
1661
	public static function update_option( $name, $value ) {
1662
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1663
		return Jetpack_Options::update_option( $name, $value );
1664
	}
1665
1666
	/**
1667
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1668
 	 *
1669
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1670
	 * @param array $array array( option name => option value, ... )
1671
	 */
1672
	public static function update_options( $array ) {
1673
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1674
		return Jetpack_Options::update_options( $array );
1675
	}
1676
1677
	/**
1678
	 * Deletes the given option.  May be passed multiple option names as an array.
1679
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1680
	 *
1681
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1682
	 * @param string|array $names
1683
	 */
1684
	public static function delete_option( $names ) {
1685
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1686
		return Jetpack_Options::delete_option( $names );
1687
	}
1688
1689
	/**
1690
	 * Enters a user token into the user_tokens option
1691
	 *
1692
	 * @param int $user_id
1693
	 * @param string $token
1694
	 * return bool
1695
	 */
1696
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1697
		// not designed for concurrent updates
1698
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1699
		if ( ! is_array( $user_tokens ) )
1700
			$user_tokens = array();
1701
		$user_tokens[$user_id] = $token;
1702
		if ( $is_master_user ) {
1703
			$master_user = $user_id;
1704
			$options     = compact( 'user_tokens', 'master_user' );
1705
		} else {
1706
			$options = compact( 'user_tokens' );
1707
		}
1708
		return Jetpack_Options::update_options( $options );
1709
	}
1710
1711
	/**
1712
	 * Returns an array of all PHP files in the specified absolute path.
1713
	 * Equivalent to glob( "$absolute_path/*.php" ).
1714
	 *
1715
	 * @param string $absolute_path The absolute path of the directory to search.
1716
	 * @return array Array of absolute paths to the PHP files.
1717
	 */
1718
	public static function glob_php( $absolute_path ) {
1719
		if ( function_exists( 'glob' ) ) {
1720
			return glob( "$absolute_path/*.php" );
1721
		}
1722
1723
		$absolute_path = untrailingslashit( $absolute_path );
1724
		$files = array();
1725
		if ( ! $dir = @opendir( $absolute_path ) ) {
1726
			return $files;
1727
		}
1728
1729
		while ( false !== $file = readdir( $dir ) ) {
1730
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1731
				continue;
1732
			}
1733
1734
			$file = "$absolute_path/$file";
1735
1736
			if ( ! is_file( $file ) ) {
1737
				continue;
1738
			}
1739
1740
			$files[] = $file;
1741
		}
1742
1743
		closedir( $dir );
1744
1745
		return $files;
1746
	}
1747
1748
	public static function activate_new_modules( $redirect = false ) {
1749
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1750
			return;
1751
		}
1752
1753
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1754 View Code Duplication
		if ( ! $jetpack_old_version ) {
1755
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1756
			/** This action is documented in class.jetpack.php */
1757
			do_action( 'updating_jetpack_version', $version, false );
1758
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1759
		}
1760
1761
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1762
1763
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1764
			return;
1765
		}
1766
1767
		$active_modules     = Jetpack::get_active_modules();
1768
		$reactivate_modules = array();
1769
		foreach ( $active_modules as $active_module ) {
1770
			$module = Jetpack::get_module( $active_module );
1771
			if ( ! isset( $module['changed'] ) ) {
1772
				continue;
1773
			}
1774
1775
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1776
				continue;
1777
			}
1778
1779
			$reactivate_modules[] = $active_module;
1780
			Jetpack::deactivate_module( $active_module );
1781
		}
1782
1783
		$new_version = JETPACK__VERSION . ':' . time();
1784
		/** This action is documented in class.jetpack.php */
1785
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1786
		Jetpack_Options::update_options(
1787
			array(
1788
				'version'     => $new_version,
1789
				'old_version' => $jetpack_old_version,
1790
			)
1791
		);
1792
1793
		Jetpack::state( 'message', 'modules_activated' );
1794
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
1795
1796
		if ( $redirect ) {
1797
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1798
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1799
				$page = $_GET['page'];
1800
			}
1801
1802
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1803
			exit;
1804
		}
1805
	}
1806
1807
	/**
1808
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1809
	 * Make sure to tuck away module "library" files in a sub-directory.
1810
	 */
1811
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1812
		static $modules = null;
1813
1814
		if ( ! isset( $modules ) ) {
1815
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1816
			// Use the cache if we're on the front-end and it's available...
1817
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1818
				$modules = $available_modules_option[ JETPACK__VERSION ];
1819
			} else {
1820
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1821
1822
				$modules = array();
1823
1824
				foreach ( $files as $file ) {
1825
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1826
						continue;
1827
					}
1828
1829
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1830
				}
1831
1832
				Jetpack_Options::update_option( 'available_modules', array(
1833
					JETPACK__VERSION => $modules,
1834
				) );
1835
			}
1836
		}
1837
1838
		/**
1839
		 * Filters the array of modules available to be activated.
1840
		 *
1841
		 * @since 2.4.0
1842
		 *
1843
		 * @param array $modules Array of available modules.
1844
		 * @param string $min_version Minimum version number required to use modules.
1845
		 * @param string $max_version Maximum version number required to use modules.
1846
		 */
1847
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1848
1849
		if ( ! $min_version && ! $max_version ) {
1850
			return array_keys( $mods );
1851
		}
1852
1853
		$r = array();
1854
		foreach ( $mods as $slug => $introduced ) {
1855
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1856
				continue;
1857
			}
1858
1859
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1860
				continue;
1861
			}
1862
1863
			$r[] = $slug;
1864
		}
1865
1866
		return $r;
1867
	}
1868
1869
	/**
1870
	 * Default modules loaded on activation.
1871
	 */
1872
	public static function get_default_modules( $min_version = false, $max_version = false ) {
1873
		$return = array();
1874
1875
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1876
			$module_data = Jetpack::get_module( $module );
1877
1878
			switch ( strtolower( $module_data['auto_activate'] ) ) {
1879
				case 'yes' :
1880
					$return[] = $module;
1881
					break;
1882
				case 'public' :
1883
					if ( Jetpack_Options::get_option( 'public' ) ) {
1884
						$return[] = $module;
1885
					}
1886
					break;
1887
				case 'no' :
1888
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
1889
					break;
1890
			}
1891
		}
1892
		/**
1893
		 * Filters the array of default modules.
1894
		 *
1895
		 * @since 2.5.0
1896
		 *
1897
		 * @param array $return Array of default modules.
1898
		 * @param string $min_version Minimum version number required to use modules.
1899
		 * @param string $max_version Maximum version number required to use modules.
1900
		 */
1901
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1902
	}
1903
1904
	/**
1905
	 * Checks activated modules during auto-activation to determine
1906
	 * if any of those modules are being deprecated.  If so, close
1907
	 * them out, and add any replacement modules.
1908
	 *
1909
	 * Runs at priority 99 by default.
1910
	 *
1911
	 * This is run late, so that it can still activate a module if
1912
	 * the new module is a replacement for another that the user
1913
	 * currently has active, even if something at the normal priority
1914
	 * would kibosh everything.
1915
	 *
1916
	 * @since 2.6
1917
	 * @uses jetpack_get_default_modules filter
1918
	 * @param array $modules
1919
	 * @return array
1920
	 */
1921
	function handle_deprecated_modules( $modules ) {
1922
		$deprecated_modules = array(
1923
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
1924
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1925
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
1926
		);
1927
1928
		// Don't activate SSO if they never completed activating WPCC.
1929
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
1930
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1931
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1932
				$deprecated_modules['wpcc'] = null;
1933
			}
1934
		}
1935
1936
		foreach ( $deprecated_modules as $module => $replacement ) {
1937
			if ( Jetpack::is_module_active( $module ) ) {
1938
				self::deactivate_module( $module );
1939
				if ( $replacement ) {
1940
					$modules[] = $replacement;
1941
				}
1942
			}
1943
		}
1944
1945
		return array_unique( $modules );
1946
	}
1947
1948
	/**
1949
	 * Checks activated plugins during auto-activation to determine
1950
	 * if any of those plugins are in the list with a corresponding module
1951
	 * that is not compatible with the plugin. The module will not be allowed
1952
	 * to auto-activate.
1953
	 *
1954
	 * @since 2.6
1955
	 * @uses jetpack_get_default_modules filter
1956
	 * @param array $modules
1957
	 * @return array
1958
	 */
1959
	function filter_default_modules( $modules ) {
1960
1961
		$active_plugins = self::get_active_plugins();
1962
1963
		if ( ! empty( $active_plugins ) ) {
1964
1965
			// For each module we'd like to auto-activate...
1966
			foreach ( $modules as $key => $module ) {
1967
				// If there are potential conflicts for it...
1968
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1969
					// For each potential conflict...
1970
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1971
						// If that conflicting plugin is active...
1972
						if ( in_array( $plugin, $active_plugins ) ) {
1973
							// Remove that item from being auto-activated.
1974
							unset( $modules[ $key ] );
1975
						}
1976
					}
1977
				}
1978
			}
1979
		}
1980
1981
		return $modules;
1982
	}
1983
1984
	/**
1985
	 * Extract a module's slug from its full path.
1986
	 */
1987
	public static function get_module_slug( $file ) {
1988
		return str_replace( '.php', '', basename( $file ) );
1989
	}
1990
1991
	/**
1992
	 * Generate a module's path from its slug.
1993
	 */
1994
	public static function get_module_path( $slug ) {
1995
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
1996
	}
1997
1998
	/**
1999
	 * Load module data from module file. Headers differ from WordPress
2000
	 * plugin headers to avoid them being identified as standalone
2001
	 * plugins on the WordPress plugins page.
2002
	 */
2003
	public static function get_module( $module ) {
2004
		$headers = array(
2005
			'name'                      => 'Module Name',
2006
			'description'               => 'Module Description',
2007
			'jumpstart_desc'            => 'Jumpstart Description',
2008
			'sort'                      => 'Sort Order',
2009
			'recommendation_order'      => 'Recommendation Order',
2010
			'introduced'                => 'First Introduced',
2011
			'changed'                   => 'Major Changes In',
2012
			'deactivate'                => 'Deactivate',
2013
			'free'                      => 'Free',
2014
			'requires_connection'       => 'Requires Connection',
2015
			'auto_activate'             => 'Auto Activate',
2016
			'module_tags'               => 'Module Tags',
2017
			'feature'                   => 'Feature',
2018
			'additional_search_queries' => 'Additional Search Queries',
2019
		);
2020
2021
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2022
2023
		$mod = Jetpack::get_file_data( $file, $headers );
2024
		if ( empty( $mod['name'] ) ) {
2025
			return false;
2026
		}
2027
2028
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2029
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2030
		$mod['deactivate']              = empty( $mod['deactivate'] );
2031
		$mod['free']                    = empty( $mod['free'] );
2032
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2033
2034
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2035
			$mod['auto_activate'] = 'No';
2036
		} else {
2037
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2038
		}
2039
2040
		if ( $mod['module_tags'] ) {
2041
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2042
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2043
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2044
		} else {
2045
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2046
		}
2047
2048
		if ( $mod['feature'] ) {
2049
			$mod['feature'] = explode( ',', $mod['feature'] );
2050
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2051
		} else {
2052
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2053
		}
2054
2055
		/**
2056
		 * Filters the feature array on a module.
2057
		 *
2058
		 * This filter allows you to control where each module is filtered: Recommended,
2059
		 * Jumpstart, and the default "Other" listing.
2060
		 *
2061
		 * @since 3.5.0
2062
		 *
2063
		 * @param array   $mod['feature'] The areas to feature this module:
2064
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2065
		 *     'Recommended' shows on the main Jetpack admin screen.
2066
		 *     'Other' should be the default if no other value is in the array.
2067
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2068
		 * @param array   $mod All the currently assembled module data.
2069
		 */
2070
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2071
2072
		/**
2073
		 * Filter the returned data about a module.
2074
		 *
2075
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2076
		 * so please be careful.
2077
		 *
2078
		 * @since 3.6.0
2079
		 *
2080
		 * @param array   $mod    The details of the requested module.
2081
		 * @param string  $module The slug of the module, e.g. sharedaddy
2082
		 * @param string  $file   The path to the module source file.
2083
		 */
2084
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2085
	}
2086
2087
	/**
2088
	 * Like core's get_file_data implementation, but caches the result.
2089
	 */
2090
	public static function get_file_data( $file, $headers ) {
2091
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2092
		$file_name = basename( $file );
2093
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2094
		$key              = md5( $file_name . serialize( $headers ) );
2095
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2096
2097
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2098
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2099
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2100
		}
2101
2102
		$data = get_file_data( $file, $headers );
2103
2104
		// Strip out any old Jetpack versions that are cluttering the option.
2105
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2106
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2107
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2108
2109
		return $data;
2110
	}
2111
2112
	/**
2113
	 * Return translated module tag.
2114
	 *
2115
	 * @param string $tag Tag as it appears in each module heading.
2116
	 *
2117
	 * @return mixed
2118
	 */
2119
	public static function translate_module_tag( $tag ) {
2120
		return jetpack_get_module_i18n_tag( $tag );
2121
	}
2122
2123
	/**
2124
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2125
	 *
2126
	 * @since 3.9.2
2127
	 *
2128
	 * @param array $modules
2129
	 *
2130
	 * @return string|void
2131
	 */
2132
	public static function get_translated_modules( $modules ) {
2133
		foreach ( $modules as $index => $module ) {
2134
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2135
			if ( isset( $module['name'] ) ) {
2136
				$modules[ $index ]['name'] = $i18n_module['name'];
2137
			}
2138
			if ( isset( $module['description'] ) ) {
2139
				$modules[ $index ]['description'] = $i18n_module['description'];
2140
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2141
			}
2142
		}
2143
		return $modules;
2144
	}
2145
2146
	/**
2147
	 * Get a list of activated modules as an array of module slugs.
2148
	 */
2149
	public static function get_active_modules() {
2150
		$active = Jetpack_Options::get_option( 'active_modules' );
2151
		if ( ! is_array( $active ) )
2152
			$active = array();
2153
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2154
			$active[] = 'vaultpress';
2155
		} else {
2156
			$active = array_diff( $active, array( 'vaultpress' ) );
2157
		}
2158
2159
		//If protect is active on the main site of a multisite, it should be active on all sites.
2160
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2161
			$active[] = 'protect';
2162
		}
2163
2164
		return array_unique( $active );
2165
	}
2166
2167
	/**
2168
	 * Check whether or not a Jetpack module is active.
2169
	 *
2170
	 * @param string $module The slug of a Jetpack module.
2171
	 * @return bool
2172
	 *
2173
	 * @static
2174
	 */
2175
	public static function is_module_active( $module ) {
2176
		return in_array( $module, self::get_active_modules() );
2177
	}
2178
2179
	public static function is_module( $module ) {
2180
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2181
	}
2182
2183
	/**
2184
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2185
	 *
2186
	 * @param bool $catch True to start catching, False to stop.
2187
	 *
2188
	 * @static
2189
	 */
2190
	public static function catch_errors( $catch ) {
2191
		static $display_errors, $error_reporting;
2192
2193
		if ( $catch ) {
2194
			$display_errors  = @ini_set( 'display_errors', 1 );
2195
			$error_reporting = @error_reporting( E_ALL );
2196
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2197
		} else {
2198
			@ini_set( 'display_errors', $display_errors );
2199
			@error_reporting( $error_reporting );
2200
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2201
		}
2202
	}
2203
2204
	/**
2205
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2206
	 */
2207
	public static function catch_errors_on_shutdown() {
2208
		Jetpack::state( 'php_errors', ob_get_clean() );
2209
	}
2210
2211
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2212
		$jetpack = Jetpack::init();
2213
2214
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2215
		$modules = array_merge( $other_modules, $modules );
2216
2217
		// Look for standalone plugins and disable if active.
2218
2219
		$to_deactivate = array();
2220
		foreach ( $modules as $module ) {
2221
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2222
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2223
			}
2224
		}
2225
2226
		$deactivated = array();
2227
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2228
			list( $probable_file, $probable_title ) = $deactivate_me;
2229
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2230
				$deactivated[] = $module;
2231
			}
2232
		}
2233
2234
		if ( $deactivated && $redirect ) {
2235
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2236
2237
			$url = add_query_arg(
2238
				array(
2239
					'action'   => 'activate_default_modules',
2240
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2241
				),
2242
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2243
			);
2244
			wp_safe_redirect( $url );
2245
			exit;
2246
		}
2247
2248
		/**
2249
		 * Fires before default modules are activated.
2250
		 *
2251
		 * @since 1.9.0
2252
		 *
2253
		 * @param string $min_version Minimum version number required to use modules.
2254
		 * @param string $max_version Maximum version number required to use modules.
2255
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2256
		 */
2257
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2258
2259
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2260
		Jetpack::restate();
2261
		Jetpack::catch_errors( true );
2262
2263
		$active = Jetpack::get_active_modules();
2264
2265
		foreach ( $modules as $module ) {
2266
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2267
				$active[] = $module;
2268
				self::update_active_modules( $active );
2269
				continue;
2270
			}
2271
2272
			if ( in_array( $module, $active ) ) {
2273
				$module_info = Jetpack::get_module( $module );
2274
				if ( ! $module_info['deactivate'] ) {
2275
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2276 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2277
						$active_state = explode( ',', $active_state );
2278
					} else {
2279
						$active_state = array();
2280
					}
2281
					$active_state[] = $module;
2282
					Jetpack::state( $state, implode( ',', $active_state ) );
2283
				}
2284
				continue;
2285
			}
2286
2287
			$file = Jetpack::get_module_path( $module );
2288
			if ( ! file_exists( $file ) ) {
2289
				continue;
2290
			}
2291
2292
			// we'll override this later if the plugin can be included without fatal error
2293
			if ( $redirect ) {
2294
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2295
			}
2296
			Jetpack::state( 'error', 'module_activation_failed' );
2297
			Jetpack::state( 'module', $module );
2298
			ob_start();
2299
			require $file;
2300
2301
			$active[] = $module;
2302
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2303 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2304
				$active_state = explode( ',', $active_state );
2305
			} else {
2306
				$active_state = array();
2307
			}
2308
			$active_state[] = $module;
2309
			Jetpack::state( $state, implode( ',', $active_state ) );
2310
			Jetpack::update_active_modules( $active );
2311
2312
			ob_end_clean();
2313
		}
2314
		Jetpack::state( 'error', false );
2315
		Jetpack::state( 'module', false );
2316
		Jetpack::catch_errors( false );
2317
		/**
2318
		 * Fires when default modules are activated.
2319
		 *
2320
		 * @since 1.9.0
2321
		 *
2322
		 * @param string $min_version Minimum version number required to use modules.
2323
		 * @param string $max_version Maximum version number required to use modules.
2324
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2325
		 */
2326
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2327
	}
2328
2329
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2330
		/**
2331
		 * Fires before a module is activated.
2332
		 *
2333
		 * @since 2.6.0
2334
		 *
2335
		 * @param string $module Module slug.
2336
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2337
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2338
		 */
2339
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2340
2341
		$jetpack = Jetpack::init();
2342
2343
		if ( ! strlen( $module ) )
2344
			return false;
2345
2346
		if ( ! Jetpack::is_module( $module ) )
2347
			return false;
2348
2349
		// If it's already active, then don't do it again
2350
		$active = Jetpack::get_active_modules();
2351
		foreach ( $active as $act ) {
2352
			if ( $act == $module )
2353
				return true;
2354
		}
2355
2356
		$module_data = Jetpack::get_module( $module );
2357
2358
		if ( ! Jetpack::is_active() ) {
2359
			if ( !Jetpack::is_development_mode() )
2360
				return false;
2361
2362
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2363
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2364
				return false;
2365
		}
2366
2367
		// Check and see if the old plugin is active
2368
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2369
			// Deactivate the old plugin
2370
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2371
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2372
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2373
				Jetpack::state( 'deactivated_plugins', $module );
2374
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2375
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2376
			}
2377
		}
2378
2379
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2380
		Jetpack::state( 'module', $module );
2381
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2382
2383
		Jetpack::catch_errors( true );
2384
		ob_start();
2385
		require Jetpack::get_module_path( $module );
2386
		/** This action is documented in class.jetpack.php */
2387
		do_action( 'jetpack_activate_module', $module );
2388
		$active[] = $module;
2389
		Jetpack::update_active_modules( $active );
2390
2391
		Jetpack::state( 'error', false ); // the override
2392
		ob_end_clean();
2393
		Jetpack::catch_errors( false );
2394
2395
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2396 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2397
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2398
2399
			//Jump start is being dismissed send data to MC Stats
2400
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2401
2402
			$jetpack->do_stats( 'server_side' );
2403
		}
2404
2405
		if ( $redirect ) {
2406
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2407
		}
2408
		if ( $exit ) {
2409
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2410
		}
2411
		return true;
2412
	}
2413
2414
	function activate_module_actions( $module ) {
2415
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2416
	}
2417
2418
	public static function deactivate_module( $module ) {
2419
		/**
2420
		 * Fires when a module is deactivated.
2421
		 *
2422
		 * @since 1.9.0
2423
		 *
2424
		 * @param string $module Module slug.
2425
		 */
2426
		do_action( 'jetpack_pre_deactivate_module', $module );
2427
2428
		$jetpack = Jetpack::init();
2429
2430
		$active = Jetpack::get_active_modules();
2431
		$new    = array_filter( array_diff( $active, (array) $module ) );
2432
2433
		// A flag for Jump Start so it's not shown again.
2434 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2435
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2436
2437
			//Jump start is being dismissed send data to MC Stats
2438
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2439
2440
			$jetpack->do_stats( 'server_side' );
2441
		}
2442
2443
		return self::update_active_modules( $new );
2444
	}
2445
2446
	public static function enable_module_configurable( $module ) {
2447
		$module = Jetpack::get_module_slug( $module );
2448
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2449
	}
2450
2451
	public static function module_configuration_url( $module ) {
2452
		$module = Jetpack::get_module_slug( $module );
2453
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2454
	}
2455
2456
	public static function module_configuration_load( $module, $method ) {
2457
		$module = Jetpack::get_module_slug( $module );
2458
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2459
	}
2460
2461
	public static function module_configuration_head( $module, $method ) {
2462
		$module = Jetpack::get_module_slug( $module );
2463
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2464
	}
2465
2466
	public static function module_configuration_screen( $module, $method ) {
2467
		$module = Jetpack::get_module_slug( $module );
2468
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2469
	}
2470
2471
	public static function module_configuration_activation_screen( $module, $method ) {
2472
		$module = Jetpack::get_module_slug( $module );
2473
		add_action( 'display_activate_module_setting_' . $module, $method );
2474
	}
2475
2476
/* Installation */
2477
2478
	public static function bail_on_activation( $message, $deactivate = true ) {
2479
?>
2480
<!doctype html>
2481
<html>
2482
<head>
2483
<meta charset="<?php bloginfo( 'charset' ); ?>">
2484
<style>
2485
* {
2486
	text-align: center;
2487
	margin: 0;
2488
	padding: 0;
2489
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2490
}
2491
p {
2492
	margin-top: 1em;
2493
	font-size: 18px;
2494
}
2495
</style>
2496
<body>
2497
<p><?php echo esc_html( $message ); ?></p>
2498
</body>
2499
</html>
2500
<?php
2501
		if ( $deactivate ) {
2502
			$plugins = get_option( 'active_plugins' );
2503
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2504
			$update  = false;
2505
			foreach ( $plugins as $i => $plugin ) {
2506
				if ( $plugin === $jetpack ) {
2507
					$plugins[$i] = false;
2508
					$update = true;
2509
				}
2510
			}
2511
2512
			if ( $update ) {
2513
				update_option( 'active_plugins', array_filter( $plugins ) );
2514
			}
2515
		}
2516
		exit;
2517
	}
2518
2519
	/**
2520
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2521
	 * @static
2522
	 */
2523
	public static function plugin_activation( $network_wide ) {
2524
		Jetpack_Options::update_option( 'activated', 1 );
2525
2526
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2527
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2528
		}
2529
2530
		if ( $network_wide )
2531
			Jetpack::state( 'network_nag', true );
2532
2533
		Jetpack::plugin_initialize();
2534
	}
2535
	/**
2536
	 * Runs before bumping version numbers up to a new version
2537
	 * @param  (string) $version    Version:timestamp
2538
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2539
	 * @return null              [description]
2540
	 */
2541
	public static function do_version_bump( $version, $old_version ) {
2542
2543
		if ( ! $old_version ) { // For new sites
2544
			// Setting up jetpack manage
2545
			Jetpack::activate_manage();
2546
		}
2547
	}
2548
2549
	/**
2550
	 * Sets the internal version number and activation state.
2551
	 * @static
2552
	 */
2553
	public static function plugin_initialize() {
2554
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2555
			Jetpack_Options::update_option( 'activated', 2 );
2556
		}
2557
2558 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2559
			$version = $old_version = JETPACK__VERSION . ':' . time();
2560
			/** This action is documented in class.jetpack.php */
2561
			do_action( 'updating_jetpack_version', $version, false );
2562
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2563
		}
2564
2565
		Jetpack::load_modules();
2566
2567
		Jetpack_Options::delete_option( 'do_activate' );
2568
	}
2569
2570
	/**
2571
	 * Removes all connection options
2572
	 * @static
2573
	 */
2574
	public static function plugin_deactivation( ) {
2575
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2576
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2577
			Jetpack_Network::init()->deactivate();
2578
		} else {
2579
			Jetpack::disconnect( false );
2580
			//Jetpack_Heartbeat::init()->deactivate();
2581
		}
2582
	}
2583
2584
	/**
2585
	 * Disconnects from the Jetpack servers.
2586
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2587
	 * @static
2588
	 */
2589
	public static function disconnect( $update_activated_state = true ) {
2590
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2591
		Jetpack::clean_nonces( true );
2592
2593
		// If the site is in an IDC because sync is not allowed,
2594
		// let's make sure to not disconnect the production site.
2595
		if ( ! self::validate_sync_error_idc_option() ) {
2596
			Jetpack::load_xml_rpc_client();
2597
			$xml = new Jetpack_IXR_Client();
2598
			$xml->query( 'jetpack.deregister' );
2599
		}
2600
2601
		Jetpack_Options::delete_option(
2602
			array(
2603
				'register',
2604
				'blog_token',
2605
				'user_token',
2606
				'user_tokens',
2607
				'master_user',
2608
				'time_diff',
2609
				'fallback_no_verify_ssl_certs',
2610
				'sync_error_idc',
2611
			)
2612
		);
2613
2614
		if ( $update_activated_state ) {
2615
			Jetpack_Options::update_option( 'activated', 4 );
2616
		}
2617
2618
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2619
			// Check then record unique disconnection if site has never been disconnected previously
2620
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2621
				$jetpack_unique_connection['disconnected'] = 1;
2622
			} else {
2623
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2624
					//track unique disconnect
2625
					$jetpack = Jetpack::init();
2626
2627
					$jetpack->stat( 'connections', 'unique-disconnect' );
2628
					$jetpack->do_stats( 'server_side' );
2629
				}
2630
				// increment number of times disconnected
2631
				$jetpack_unique_connection['disconnected'] += 1;
2632
			}
2633
2634
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2635
		}
2636
2637
		// Delete all the sync related data. Since it could be taking up space.
2638
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2639
		Jetpack_Sync_Sender::get_instance()->uninstall();
2640
2641
		// Disable the Heartbeat cron
2642
		Jetpack_Heartbeat::init()->deactivate();
2643
	}
2644
2645
	/**
2646
	 * Unlinks the current user from the linked WordPress.com user
2647
	 */
2648
	public static function unlink_user( $user_id = null ) {
2649
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2650
			return false;
2651
2652
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2653
2654
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2655
			return false;
2656
2657
		if ( ! isset( $tokens[ $user_id ] ) )
2658
			return false;
2659
2660
		Jetpack::load_xml_rpc_client();
2661
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2662
		$xml->query( 'jetpack.unlink_user', $user_id );
2663
2664
		unset( $tokens[ $user_id ] );
2665
2666
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2667
2668
		/**
2669
		 * Fires after the current user has been unlinked from WordPress.com.
2670
		 *
2671
		 * @since 4.1.0
2672
		 *
2673
		 * @param int $user_id The current user's ID.
2674
		 */
2675
		do_action( 'jetpack_unlinked_user', $user_id );
2676
2677
		return true;
2678
	}
2679
2680
	/**
2681
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2682
	 */
2683
	public static function try_registration() {
2684
		// Let's get some testing in beta versions and such.
2685
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2686
			// Before attempting to connect, let's make sure that the domains are viable.
2687
			$domains_to_check = array_unique( array(
2688
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2689
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2690
			) );
2691
			foreach ( $domains_to_check as $domain ) {
2692
				$result = Jetpack_Data::is_usable_domain( $domain );
2693
				if ( is_wp_error( $result ) ) {
2694
					return $result;
2695
				}
2696
			}
2697
		}
2698
2699
		$result = Jetpack::register();
2700
2701
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2702
		if ( ! $result || is_wp_error( $result ) ) {
2703
			return $result;
2704
		} else {
2705
			return true;
2706
		}
2707
	}
2708
2709
	/**
2710
	 * Tracking an internal event log. Try not to put too much chaff in here.
2711
	 *
2712
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2713
	 */
2714
	public static function log( $code, $data = null ) {
2715
		// only grab the latest 200 entries
2716
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2717
2718
		// Append our event to the log
2719
		$log_entry = array(
2720
			'time'    => time(),
2721
			'user_id' => get_current_user_id(),
2722
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2723
			'code'    => $code,
2724
		);
2725
		// Don't bother storing it unless we've got some.
2726
		if ( ! is_null( $data ) ) {
2727
			$log_entry['data'] = $data;
2728
		}
2729
		$log[] = $log_entry;
2730
2731
		// Try add_option first, to make sure it's not autoloaded.
2732
		// @todo: Add an add_option method to Jetpack_Options
2733
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2734
			Jetpack_Options::update_option( 'log', $log );
2735
		}
2736
2737
		/**
2738
		 * Fires when Jetpack logs an internal event.
2739
		 *
2740
		 * @since 3.0.0
2741
		 *
2742
		 * @param array $log_entry {
2743
		 *	Array of details about the log entry.
2744
		 *
2745
		 *	@param string time Time of the event.
2746
		 *	@param int user_id ID of the user who trigerred the event.
2747
		 *	@param int blog_id Jetpack Blog ID.
2748
		 *	@param string code Unique name for the event.
2749
		 *	@param string data Data about the event.
2750
		 * }
2751
		 */
2752
		do_action( 'jetpack_log_entry', $log_entry );
2753
	}
2754
2755
	/**
2756
	 * Get the internal event log.
2757
	 *
2758
	 * @param $event (string) - only return the specific log events
2759
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2760
	 *
2761
	 * @return array of log events || WP_Error for invalid params
2762
	 */
2763
	public static function get_log( $event = false, $num = false ) {
2764
		if ( $event && ! is_string( $event ) ) {
2765
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2766
		}
2767
2768
		if ( $num && ! is_numeric( $num ) ) {
2769
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2770
		}
2771
2772
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2773
2774
		// If nothing set - act as it did before, otherwise let's start customizing the output
2775
		if ( ! $num && ! $event ) {
2776
			return $entire_log;
2777
		} else {
2778
			$entire_log = array_reverse( $entire_log );
2779
		}
2780
2781
		$custom_log_output = array();
2782
2783
		if ( $event ) {
2784
			foreach ( $entire_log as $log_event ) {
2785
				if ( $event == $log_event[ 'code' ] ) {
2786
					$custom_log_output[] = $log_event;
2787
				}
2788
			}
2789
		} else {
2790
			$custom_log_output = $entire_log;
2791
		}
2792
2793
		if ( $num ) {
2794
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2795
		}
2796
2797
		return $custom_log_output;
2798
	}
2799
2800
	/**
2801
	 * Log modification of important settings.
2802
	 */
2803
	public static function log_settings_change( $option, $old_value, $value ) {
2804
		switch( $option ) {
2805
			case 'jetpack_sync_non_public_post_stati':
2806
				self::log( $option, $value );
2807
				break;
2808
		}
2809
	}
2810
2811
	/**
2812
	 * Return stat data for WPCOM sync
2813
	 */
2814
	public static function get_stat_data( $encode = true ) {
2815
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
2816
		$additional_data = self::get_additional_stat_data();
2817
2818
		$merged_data = array_merge( $heartbeat_data, $additional_data );
2819
2820
		if ( $encode ) {
2821
			return json_encode( $merged_data );
2822
		}
2823
2824
		return $merged_data;
2825
	}
2826
2827
	/**
2828
	 * Get additional stat data to sync to WPCOM
2829
	 */
2830
	public static function get_additional_stat_data( $prefix = '' ) {
2831
		global $wpdb;
2832
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2833
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2834
		$return["{$prefix}users"]          = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
2835
		$return["{$prefix}site-count"]     = 0;
2836
2837
		if ( function_exists( 'get_blog_count' ) ) {
2838
			$return["{$prefix}site-count"] = get_blog_count();
2839
		}
2840
		return $return;
2841
	}
2842
2843
	/* Admin Pages */
2844
2845
	function admin_init() {
2846
		// If the plugin is not connected, display a connect message.
2847
		if (
2848
			// the plugin was auto-activated and needs its candy
2849
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2850
		||
2851
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2852
			! Jetpack_Options::get_option( 'activated' )
2853
		) {
2854
			Jetpack::plugin_initialize();
2855
		}
2856
2857
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2858
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2859
				// Show connect notice on dashboard and plugins pages
2860
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
2861
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
2862
			}
2863
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2864
			// Upgrade: 1.1 -> 1.1.1
2865
			// Check and see if host can verify the Jetpack servers' SSL certificate
2866
			$args = array();
2867
			Jetpack_Client::_wp_remote_request(
2868
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2869
				$args,
2870
				true
2871
			);
2872
		} else {
2873
			// Show the notice on the Dashboard only for now
2874
2875
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2876
		}
2877
2878
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2879
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2880
		}
2881
2882
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2883
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2884
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2885
2886
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2887
			// Artificially throw errors in certain whitelisted cases during plugin activation
2888
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2889
		}
2890
2891
		// Jetpack Manage Activation Screen from .com
2892
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2893
2894
		// Add custom column in wp-admin/users.php to show whether user is linked.
2895
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2896
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2897
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2898
	}
2899
2900
	function admin_body_class( $admin_body_class = '' ) {
2901
		$classes = explode( ' ', trim( $admin_body_class ) );
2902
2903
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2904
2905
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2906
		return " $admin_body_class ";
2907
	}
2908
2909
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2910
		return $admin_body_class . ' jetpack-pagestyles ';
2911
	}
2912
2913
	function prepare_connect_notice() {
2914
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2915
2916
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
2917
2918
		if ( Jetpack::state( 'network_nag' ) )
2919
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
2920
	}
2921
	/**
2922
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2923
	 *
2924
	 * @return null
2925
	 */
2926
	function prepare_manage_jetpack_notice() {
2927
2928
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2929
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2930
	}
2931
2932
	function manage_activate_screen() {
2933
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2934
	}
2935
	/**
2936
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2937
	 * This function artificially throws errors for such cases (whitelisted).
2938
	 *
2939
	 * @param string $plugin The activated plugin.
2940
	 */
2941
	function throw_error_on_activate_plugin( $plugin ) {
2942
		$active_modules = Jetpack::get_active_modules();
2943
2944
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2945
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2946
			$throw = false;
2947
2948
			// Try and make sure it really was the stats plugin
2949
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2950
				if ( 'stats.php' == basename( $plugin ) ) {
2951
					$throw = true;
2952
				}
2953
			} else {
2954
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2955
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2956
					$throw = true;
2957
				}
2958
			}
2959
2960
			if ( $throw ) {
2961
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2962
			}
2963
		}
2964
	}
2965
2966
	function intercept_plugin_error_scrape_init() {
2967
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2968
	}
2969
2970
	function intercept_plugin_error_scrape( $action, $result ) {
2971
		if ( ! $result ) {
2972
			return;
2973
		}
2974
2975
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2976
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2977
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2978
			}
2979
		}
2980
	}
2981
2982
	function add_remote_request_handlers() {
2983
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2984
	}
2985
2986
	function remote_request_handlers() {
2987
		switch ( current_filter() ) {
2988
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2989
			$response = $this->upload_handler();
2990
			break;
2991
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2992
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2993
			break;
2994
		}
2995
2996
		if ( ! $response ) {
2997
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2998
		}
2999
3000
		if ( is_wp_error( $response ) ) {
3001
			$status_code       = $response->get_error_data();
3002
			$error             = $response->get_error_code();
3003
			$error_description = $response->get_error_message();
3004
3005
			if ( ! is_int( $status_code ) ) {
3006
				$status_code = 400;
3007
			}
3008
3009
			status_header( $status_code );
3010
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3011
		}
3012
3013
		status_header( 200 );
3014
		if ( true === $response ) {
3015
			exit;
3016
		}
3017
3018
		die( json_encode( (object) $response ) );
3019
	}
3020
3021
	function upload_handler() {
3022
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3023
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3024
		}
3025
3026
		$user = wp_authenticate( '', '' );
3027
		if ( ! $user || is_wp_error( $user ) ) {
3028
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3029
		}
3030
3031
		wp_set_current_user( $user->ID );
3032
3033
		if ( ! current_user_can( 'upload_files' ) ) {
3034
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3035
		}
3036
3037
		if ( empty( $_FILES ) ) {
3038
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3039
		}
3040
3041
		foreach ( array_keys( $_FILES ) as $files_key ) {
3042
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3043
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3044
			}
3045
		}
3046
3047
		$media_keys = array_keys( $_FILES['media'] );
3048
3049
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3050
		if ( ! $token || is_wp_error( $token ) ) {
3051
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3052
		}
3053
3054
		$uploaded_files = array();
3055
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3056
		unset( $GLOBALS['post'] );
3057
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3058
			$file = array();
3059
			foreach ( $media_keys as $media_key ) {
3060
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3061
			}
3062
3063
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3064
3065
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3066
			if ( $hmac_provided !== $hmac_file ) {
3067
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3068
				continue;
3069
			}
3070
3071
			$_FILES['.jetpack.upload.'] = $file;
3072
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3073
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3074
				$post_id = 0;
3075
			}
3076
			$attachment_id = media_handle_upload(
3077
				'.jetpack.upload.',
3078
				$post_id,
3079
				array(),
3080
				array(
3081
					'action' => 'jetpack_upload_file',
3082
				)
3083
			);
3084
3085
			if ( ! $attachment_id ) {
3086
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3087
			} elseif ( is_wp_error( $attachment_id ) ) {
3088
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3089
			} else {
3090
				$attachment = get_post( $attachment_id );
3091
				$uploaded_files[$index] = (object) array(
3092
					'id'   => (string) $attachment_id,
3093
					'file' => $attachment->post_title,
3094
					'url'  => wp_get_attachment_url( $attachment_id ),
3095
					'type' => $attachment->post_mime_type,
3096
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3097
				);
3098
			}
3099
		}
3100
		if ( ! is_null( $global_post ) ) {
3101
			$GLOBALS['post'] = $global_post;
3102
		}
3103
3104
		return $uploaded_files;
3105
	}
3106
3107
	/**
3108
	 * Add help to the Jetpack page
3109
	 *
3110
	 * @since Jetpack (1.2.3)
3111
	 * @return false if not the Jetpack page
3112
	 */
3113
	function admin_help() {
3114
		$current_screen = get_current_screen();
3115
3116
		// Overview
3117
		$current_screen->add_help_tab(
3118
			array(
3119
				'id'		=> 'home',
3120
				'title'		=> __( 'Home', 'jetpack' ),
3121
				'content'	=>
3122
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3123
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3124
					'<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>',
3125
			)
3126
		);
3127
3128
		// Screen Content
3129
		if ( current_user_can( 'manage_options' ) ) {
3130
			$current_screen->add_help_tab(
3131
				array(
3132
					'id'		=> 'settings',
3133
					'title'		=> __( 'Settings', 'jetpack' ),
3134
					'content'	=>
3135
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3136
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3137
						'<ol>' .
3138
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3139
							'<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>' .
3140
						'</ol>' .
3141
						'<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>'
3142
				)
3143
			);
3144
		}
3145
3146
		// Help Sidebar
3147
		$current_screen->set_help_sidebar(
3148
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3149
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3150
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3151
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3152
		);
3153
	}
3154
3155
	function admin_menu_css() {
3156
		wp_enqueue_style( 'jetpack-icons' );
3157
	}
3158
3159
	function admin_menu_order() {
3160
		return true;
3161
	}
3162
3163 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3164
		$jp_menu_order = array();
3165
3166
		foreach ( $menu_order as $index => $item ) {
3167
			if ( $item != 'jetpack' ) {
3168
				$jp_menu_order[] = $item;
3169
			}
3170
3171
			if ( $index == 0 ) {
3172
				$jp_menu_order[] = 'jetpack';
3173
			}
3174
		}
3175
3176
		return $jp_menu_order;
3177
	}
3178
3179
	function admin_head() {
3180 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3181
			/** This action is documented in class.jetpack-admin-page.php */
3182
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3183
	}
3184
3185 View Code Duplication
	function admin_banner_styles() {
3186
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3187
3188
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3189
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3190
		wp_style_add_data( 'jetpack', 'suffix', $min );
3191
	}
3192
3193
	function plugin_action_links( $actions ) {
3194
3195
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3196
3197
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3198
			return array_merge(
3199
				$jetpack_home,
3200
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3201
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3202
				$actions
3203
				);
3204
			}
3205
3206
		return array_merge( $jetpack_home, $actions );
3207
	}
3208
3209
	function admin_connect_notice() {
3210
		// Don't show the connect notice anywhere but the plugins.php after activating
3211
		$current = get_current_screen();
3212
		if ( 'plugins' !== $current->parent_base )
3213
			return;
3214
3215
		if ( ! current_user_can( 'jetpack_connect' ) )
3216
			return;
3217
3218
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3219
		?>
3220
		<div id="message" class="updated jp-banner">
3221
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3222
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3223
					<div class="jp-banner__description-container">
3224
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3225
						<p class="jp-banner__description"><?php _e( 'Please connect to or create a WordPress.com account to enable Jetpack, including powerful security, traffic, and customization services.', 'jetpack' ); ?></p>
3226
						<p class="jp-banner__button-container">
3227
							<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3228
							<a href="<?php echo Jetpack::admin_url( 'admin.php?page=jetpack' ) ?>" class="button" title="<?php esc_attr_e( 'Learn about the benefits you receive when you connect Jetpack to WordPress.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3229
						</p>
3230
					</div>
3231
			<?php else : ?>
3232
				<div class="jp-banner__content">
3233
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3234
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3235
				</div>
3236
				<div class="jp-banner__action-container">
3237
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3238
				</div>
3239
			<?php endif; ?>
3240
		</div>
3241
3242
		<?php
3243
	}
3244
3245
	/**
3246
	 * This is the first banner
3247
	 * It should be visible only to user that can update the option
3248
	 * Are not connected
3249
	 *
3250
	 * @return null
3251
	 */
3252
	function admin_jetpack_manage_notice() {
3253
		$screen = get_current_screen();
3254
3255
		// Don't show the connect notice on the jetpack settings page.
3256
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3257
			return;
3258
3259
		// Only show it if don't have the managment option set.
3260
		// And not dismissed it already.
3261
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3262
			return;
3263
		}
3264
3265
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3266
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3267
		/**
3268
		 * I think it would be great to have different wordsing depending on where you are
3269
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3270
		 * etc..
3271
		 */
3272
3273
		?>
3274
		<div id="message" class="updated jp-banner">
3275
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3276
				<div class="jp-banner__description-container">
3277
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3278
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3279
					<p class="jp-banner__button-container">
3280
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3281
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3282
					</p>
3283
				</div>
3284
		</div>
3285
		<?php
3286
	}
3287
3288
	/**
3289
	 * Returns the url that the user clicks to remove the notice for the big banner
3290
	 * @return (string)
3291
	 */
3292
	function opt_out_jetpack_manage_url() {
3293
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3294
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3295
	}
3296
	/**
3297
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3298
	 * @return (string)
3299
	 */
3300
	function opt_in_jetpack_manage_url() {
3301
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3302
	}
3303
3304
	function opt_in_jetpack_manage_notice() {
3305
		?>
3306
		<div class="wrap">
3307
			<div id="message" class="jetpack-message is-opt-in">
3308
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'https://jetpack.com/support/site-management' ); ?>
3309
			</div>
3310
		</div>
3311
		<?php
3312
3313
	}
3314
	/**
3315
	 * Determines whether to show the notice of not true = display notice
3316
	 * @return (bool)
3317
	 */
3318
	function can_display_jetpack_manage_notice() {
3319
		// never display the notice to users that can't do anything about it anyways
3320
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3321
			return false;
3322
3323
		// don't display if we are in development more
3324
		if( Jetpack::is_development_mode() ) {
3325
			return false;
3326
		}
3327
		// don't display if the site is private
3328
		if(  ! Jetpack_Options::get_option( 'public' ) )
3329
			return false;
3330
3331
		/**
3332
		 * Should the Jetpack Remote Site Management notice be displayed.
3333
		 *
3334
		 * @since 3.3.0
3335
		 *
3336
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3337
		 */
3338
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3339
	}
3340
3341
	function network_connect_notice() {
3342
		?>
3343
		<div id="message" class="updated jetpack-message">
3344
			<div class="squeezer">
3345
				<h2><?php _e( '<strong>Jetpack is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'jetpack' ) ?></h2>
3346
			</div>
3347
		</div>
3348
		<?php
3349
	}
3350
3351
	/*
3352
	 * Registration flow:
3353
	 * 1 - ::admin_page_load() action=register
3354
	 * 2 - ::try_registration()
3355
	 * 3 - ::register()
3356
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3357
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3358
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3359
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3360
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3361
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3362
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3363
	 *       jetpack_id, jetpack_secret, jetpack_public
3364
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3365
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3366
	 * 5 - user logs in with WP.com account
3367
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3368
	 *		- Jetpack_Client_Server::authorize()
3369
	 *		- Jetpack_Client_Server::get_token()
3370
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3371
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3372
	 *			- which responds with access_token, token_type, scope
3373
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3374
	 *		- Jetpack::activate_default_modules()
3375
	 *     		- Deactivates deprecated plugins
3376
	 *     		- Activates all default modules
3377
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3378
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3379
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3380
	 *     Done!
3381
	 */
3382
3383
	/**
3384
	 * Handles the page load events for the Jetpack admin page
3385
	 */
3386
	function admin_page_load() {
3387
		$error = false;
3388
3389
		// Make sure we have the right body class to hook stylings for subpages off of.
3390
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3391
3392
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3393
			// Should only be used in intermediate redirects to preserve state across redirects
3394
			Jetpack::restate();
3395
		}
3396
3397
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3398
			// User clicked in the iframe to link their accounts
3399
			if ( ! Jetpack::is_user_connected() ) {
3400
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3401
				if ( isset( $_GET['notes_iframe'] ) )
3402
					$connect_url .= '&notes_iframe';
3403
				wp_redirect( $connect_url );
3404
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3405
			} else {
3406
				if ( ! isset( $_GET['calypso_env'] ) ) {
3407
					Jetpack::state( 'message', 'already_authorized' );
3408
					wp_safe_redirect( Jetpack::admin_url() );
3409
				} else {
3410
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3411
					$connect_url .= '&already_authorized=true';
3412
					wp_redirect( $connect_url );
3413
				}
3414
			}
3415
		}
3416
3417
3418
		if ( isset( $_GET['action'] ) ) {
3419
			switch ( $_GET['action'] ) {
3420
			case 'authorize':
3421
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3422
					Jetpack::state( 'message', 'already_authorized' );
3423
					wp_safe_redirect( Jetpack::admin_url() );
3424
					exit;
3425
				}
3426
				Jetpack::log( 'authorize' );
3427
				$client_server = new Jetpack_Client_Server;
3428
				$client_server->client_authorize();
3429
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3430
			case 'register' :
3431
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3432
					$error = 'cheatin';
3433
					break;
3434
				}
3435
				check_admin_referer( 'jetpack-register' );
3436
				Jetpack::log( 'register' );
3437
				Jetpack::maybe_set_version_option();
3438
				$registered = Jetpack::try_registration();
3439
				if ( is_wp_error( $registered ) ) {
3440
					$error = $registered->get_error_code();
3441
					Jetpack::state( 'error', $error );
3442
					Jetpack::state( 'error', $registered->get_error_message() );
3443
					break;
3444
				}
3445
3446
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3447
3448
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3449
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3450
			case 'activate' :
3451
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3452
					$error = 'cheatin';
3453
					break;
3454
				}
3455
3456
				$module = stripslashes( $_GET['module'] );
3457
				check_admin_referer( "jetpack_activate-$module" );
3458
				Jetpack::log( 'activate', $module );
3459
				Jetpack::activate_module( $module );
3460
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3461
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3462
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3463
			case 'activate_default_modules' :
3464
				check_admin_referer( 'activate_default_modules' );
3465
				Jetpack::log( 'activate_default_modules' );
3466
				Jetpack::restate();
3467
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3468
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3469
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3470
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3471
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3472
				exit;
3473
			case 'disconnect' :
3474
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3475
					$error = 'cheatin';
3476
					break;
3477
				}
3478
3479
				check_admin_referer( 'jetpack-disconnect' );
3480
				Jetpack::log( 'disconnect' );
3481
				Jetpack::disconnect();
3482
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3483
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3484
			case 'reconnect' :
3485
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3486
					$error = 'cheatin';
3487
					break;
3488
				}
3489
3490
				check_admin_referer( 'jetpack-reconnect' );
3491
				Jetpack::log( 'reconnect' );
3492
				$this->disconnect();
3493
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3494
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3495 View Code Duplication
			case 'deactivate' :
3496
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3497
					$error = 'cheatin';
3498
					break;
3499
				}
3500
3501
				$modules = stripslashes( $_GET['module'] );
3502
				check_admin_referer( "jetpack_deactivate-$modules" );
3503
				foreach ( explode( ',', $modules ) as $module ) {
3504
					Jetpack::log( 'deactivate', $module );
3505
					Jetpack::deactivate_module( $module );
3506
					Jetpack::state( 'message', 'module_deactivated' );
3507
				}
3508
				Jetpack::state( 'module', $modules );
3509
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3510
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3511
			case 'unlink' :
3512
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3513
				check_admin_referer( 'jetpack-unlink' );
3514
				Jetpack::log( 'unlink' );
3515
				$this->unlink_user();
3516
				Jetpack::state( 'message', 'unlinked' );
3517
				if ( 'sub-unlink' == $redirect ) {
3518
					wp_safe_redirect( admin_url() );
3519
				} else {
3520
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3521
				}
3522
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3523
			default:
3524
				/**
3525
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3526
				 *
3527
				 * @since 2.6.0
3528
				 *
3529
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3530
				 */
3531
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3532
			}
3533
		}
3534
3535
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3536
			self::activate_new_modules( true );
3537
		}
3538
3539
		$message_code = Jetpack::state( 'message' );
3540
		if ( Jetpack::state( 'optin-manage' ) ) {
3541
			$activated_manage = $message_code;
3542
			$message_code = 'jetpack-manage';
3543
		}
3544
3545
		switch ( $message_code ) {
3546
		case 'jetpack-manage':
3547
			$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
3548
			if ( $activated_manage ) {
3549
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3550
			}
3551
			break;
3552
3553
		}
3554
3555
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3556
3557
		if ( ! empty( $deactivated_plugins ) ) {
3558
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3559
			$deactivated_titles  = array();
3560
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3561
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3562
					continue;
3563
				}
3564
3565
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3566
			}
3567
3568
			if ( $deactivated_titles ) {
3569
				if ( $this->message ) {
3570
					$this->message .= "<br /><br />\n";
3571
				}
3572
3573
				$this->message .= wp_sprintf(
3574
					_n(
3575
						'Jetpack contains the most recent version of the old %l plugin.',
3576
						'Jetpack contains the most recent versions of the old %l plugins.',
3577
						count( $deactivated_titles ),
3578
						'jetpack'
3579
					),
3580
					$deactivated_titles
3581
				);
3582
3583
				$this->message .= "<br />\n";
3584
3585
				$this->message .= _n(
3586
					'The old version has been deactivated and can be removed from your site.',
3587
					'The old versions have been deactivated and can be removed from your site.',
3588
					count( $deactivated_titles ),
3589
					'jetpack'
3590
				);
3591
			}
3592
		}
3593
3594
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3595
3596
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3597
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3598
		}
3599
3600 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3601
			/**
3602
			 * Fires when a module configuration page is loaded.
3603
			 * The dynamic part of the hook is the configure parameter from the URL.
3604
			 *
3605
			 * @since 1.1.0
3606
			 */
3607
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3608
		}
3609
3610
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3611
	}
3612
3613
	function admin_notices() {
3614
3615
		if ( $this->error ) {
3616
?>
3617
<div id="message" class="jetpack-message jetpack-err">
3618
	<div class="squeezer">
3619
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3620
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3621
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3622
<?php	endif; ?>
3623
	</div>
3624
</div>
3625
<?php
3626
		}
3627
3628
		if ( $this->message ) {
3629
?>
3630
<div id="message" class="jetpack-message">
3631
	<div class="squeezer">
3632
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3633
	</div>
3634
</div>
3635
<?php
3636
		}
3637
3638
		if ( $this->privacy_checks ) :
3639
			$module_names = $module_slugs = array();
3640
3641
			$privacy_checks = explode( ',', $this->privacy_checks );
3642
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3643
			foreach ( $privacy_checks as $module_slug ) {
3644
				$module = Jetpack::get_module( $module_slug );
3645
				if ( ! $module ) {
3646
					continue;
3647
				}
3648
3649
				$module_slugs[] = $module_slug;
3650
				$module_names[] = "<strong>{$module['name']}</strong>";
3651
			}
3652
3653
			$module_slugs = join( ',', $module_slugs );
3654
?>
3655
<div id="message" class="jetpack-message jetpack-err">
3656
	<div class="squeezer">
3657
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3658
		<p><?php
3659
			echo wp_kses(
3660
				wptexturize(
3661
					wp_sprintf(
3662
						_nx(
3663
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3664
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3665
							count( $privacy_checks ),
3666
							'%l = list of Jetpack module/feature names',
3667
							'jetpack'
3668
						),
3669
						$module_names
3670
					)
3671
				),
3672
				array( 'strong' => true )
3673
			);
3674
3675
			echo "\n<br />\n";
3676
3677
			echo wp_kses(
3678
				sprintf(
3679
					_nx(
3680
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3681
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3682
						count( $privacy_checks ),
3683
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3684
						'jetpack'
3685
					),
3686
					wp_nonce_url(
3687
						Jetpack::admin_url(
3688
							array(
3689
								'page'   => 'jetpack',
3690
								'action' => 'deactivate',
3691
								'module' => urlencode( $module_slugs ),
3692
							)
3693
						),
3694
						"jetpack_deactivate-$module_slugs"
3695
					),
3696
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3697
				),
3698
				array( 'a' => array( 'href' => true, 'title' => true ) )
3699
			);
3700
		?></p>
3701
	</div>
3702
</div>
3703
<?php endif;
3704
	// only display the notice if the other stuff is not there
3705
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3706
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3707
			$this->opt_in_jetpack_manage_notice();
3708
		}
3709
	}
3710
3711
	/**
3712
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3713
	 */
3714
	function stat( $group, $detail ) {
3715
		if ( ! isset( $this->stats[ $group ] ) )
3716
			$this->stats[ $group ] = array();
3717
		$this->stats[ $group ][] = $detail;
3718
	}
3719
3720
	/**
3721
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3722
	 */
3723
	function do_stats( $method = '' ) {
3724
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3725
			foreach ( $this->stats as $group => $stats ) {
3726
				if ( is_array( $stats ) && count( $stats ) ) {
3727
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3728
					if ( 'server_side' === $method ) {
3729
						self::do_server_side_stat( $args );
3730
					} else {
3731
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3732
					}
3733
				}
3734
				unset( $this->stats[ $group ] );
3735
			}
3736
		}
3737
	}
3738
3739
	/**
3740
	 * Runs stats code for a one-off, server-side.
3741
	 *
3742
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3743
	 *
3744
	 * @return bool If it worked.
3745
	 */
3746
	static function do_server_side_stat( $args ) {
3747
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3748
		if ( is_wp_error( $response ) )
3749
			return false;
3750
3751
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3752
			return false;
3753
3754
		return true;
3755
	}
3756
3757
	/**
3758
	 * Builds the stats url.
3759
	 *
3760
	 * @param $args array|string The arguments to append to the URL.
3761
	 *
3762
	 * @return string The URL to be pinged.
3763
	 */
3764
	static function build_stats_url( $args ) {
3765
		$defaults = array(
3766
			'v'    => 'wpcom2',
3767
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3768
		);
3769
		$args     = wp_parse_args( $args, $defaults );
3770
		/**
3771
		 * Filter the URL used as the Stats tracking pixel.
3772
		 *
3773
		 * @since 2.3.2
3774
		 *
3775
		 * @param string $url Base URL used as the Stats tracking pixel.
3776
		 */
3777
		$base_url = apply_filters(
3778
			'jetpack_stats_base_url',
3779
			'https://pixel.wp.com/g.gif'
3780
		);
3781
		$url      = add_query_arg( $args, $base_url );
3782
		return $url;
3783
	}
3784
3785
	static function translate_current_user_to_role() {
3786
		foreach ( self::$capability_translations as $role => $cap ) {
3787
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3788
				return $role;
3789
			}
3790
		}
3791
3792
		return false;
3793
	}
3794
3795
	static function translate_role_to_cap( $role ) {
3796
		if ( ! isset( self::$capability_translations[$role] ) ) {
3797
			return false;
3798
		}
3799
3800
		return self::$capability_translations[$role];
3801
	}
3802
3803
	static function sign_role( $role ) {
3804
		if ( ! $user_id = (int) get_current_user_id() ) {
3805
			return false;
3806
		}
3807
3808
		$token = Jetpack_Data::get_access_token();
3809
		if ( ! $token || is_wp_error( $token ) ) {
3810
			return false;
3811
		}
3812
3813
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3814
	}
3815
3816
3817
	/**
3818
	 * Builds a URL to the Jetpack connection auth page
3819
	 *
3820
	 * @since 3.9.5
3821
	 *
3822
	 * @param bool $raw If true, URL will not be escaped.
3823
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3824
	 *                              If string, will be a custom redirect.
3825
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3826
	 *
3827
	 * @return string Connect URL
3828
	 */
3829
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
3830
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
3831
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3832
			if( is_network_admin() ) {
3833
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3834
			}
3835
		} else {
3836
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3837
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3838
			}
3839
3840
			$role = self::translate_current_user_to_role();
3841
			$signed_role = self::sign_role( $role );
3842
3843
			$user = wp_get_current_user();
3844
3845
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3846
			$redirect = $redirect
3847
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3848
				: $jetpack_admin_page;
3849
3850
			if( isset( $_REQUEST['is_multisite'] ) ) {
3851
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3852
			}
3853
3854
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
3855
			@list( $secret ) = explode( ':', $secrets );
3856
3857
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3858
				? get_site_icon_url()
3859
				: false;
3860
3861
			/**
3862
			 * Filter the type of authorization.
3863
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
3864
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3865
			 *
3866
			 * @since 4.3.3
3867
			 *
3868
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3869
			 */
3870
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3871
3872
			$args = urlencode_deep(
3873
				array(
3874
					'response_type' => 'code',
3875
					'client_id'     => Jetpack_Options::get_option( 'id' ),
3876
					'redirect_uri'  => add_query_arg(
3877
						array(
3878
							'action'   => 'authorize',
3879
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3880
							'redirect' => urlencode( $redirect ),
3881
						),
3882
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
3883
					),
3884
					'state'         => $user->ID,
3885
					'scope'         => $signed_role,
3886
					'user_email'    => $user->user_email,
3887
					'user_login'    => $user->user_login,
3888
					'is_active'     => Jetpack::is_active(),
3889
					'jp_version'    => JETPACK__VERSION,
3890
					'auth_type'     => $auth_type,
3891
					'secret'        => $secret,
3892
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
3893
					'blogname'      => get_option( 'blogname' ),
3894
					'site_url'      => site_url(),
3895
					'home_url'      => home_url(),
3896
					'site_icon'     => $site_icon,
3897
				)
3898
			);
3899
3900
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
3901
		}
3902
3903
		if ( $from ) {
3904
			$url = add_query_arg( 'from', $from, $url );
3905
		}
3906
3907
		if ( isset( $_GET['calypso_env'] ) ) {
3908
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
3909
		}
3910
3911
		return $raw ? $url : esc_url( $url );
3912
	}
3913
3914
	function build_reconnect_url( $raw = false ) {
3915
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
3916
		return $raw ? $url : esc_url( $url );
3917
	}
3918
3919
	public static function admin_url( $args = null ) {
3920
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
3921
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
3922
		return $url;
3923
	}
3924
3925
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
3926
		$actionurl = str_replace( '&amp;', '&', $actionurl );
3927
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
3928
	}
3929
3930
	function dismiss_jetpack_notice() {
3931
3932
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
3933
			return;
3934
		}
3935
3936
		switch( $_GET['jetpack-notice'] ) {
3937
			case 'dismiss':
3938
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
3939
3940
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
3941
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
3942
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
3943
				}
3944
				break;
3945 View Code Duplication
			case 'jetpack-manage-opt-out':
3946
3947
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
3948
					// Don't show the banner again
3949
3950
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
3951
					// redirect back to the page that had the notice
3952
					if ( wp_get_referer() ) {
3953
						wp_safe_redirect( wp_get_referer() );
3954
					} else {
3955
						// Take me to Jetpack
3956
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3957
					}
3958
				}
3959
				break;
3960 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
3961
3962
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
3963
					// Don't show the banner again
3964
3965
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
3966
					// redirect back to the page that had the notice
3967
					if ( wp_get_referer() ) {
3968
						wp_safe_redirect( wp_get_referer() );
3969
					} else {
3970
						// Take me to Jetpack
3971
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3972
					}
3973
				}
3974
				break;
3975
			case 'jetpack-manage-opt-in':
3976
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
3977
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
3978
3979
					$redirection_url = Jetpack::admin_url();
3980
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3981
3982
					// Don't redirect form the Jetpack Setting Page
3983
					$referer_parsed = parse_url ( wp_get_referer() );
3984
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
3985
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
3986
						// Take the user to Jetpack home except when on the setting page
3987
						$redirection_url = wp_get_referer();
3988
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3989
					}
3990
					// Also update the JSON API FULL MANAGEMENT Option
3991
					Jetpack::activate_module( 'manage', false, false );
3992
3993
					// Special Message when option in.
3994
					Jetpack::state( 'optin-manage', 'true' );
3995
					// Activate the Module if not activated already
3996
3997
					// Redirect properly
3998
					wp_safe_redirect( $redirection_url );
3999
4000
				}
4001
				break;
4002
		}
4003
	}
4004
4005
	function debugger_page() {
4006
		nocache_headers();
4007
		if ( ! current_user_can( 'manage_options' ) ) {
4008
			die( '-1' );
4009
		}
4010
		Jetpack_Debugger::jetpack_debug_display_handler();
4011
		exit;
4012
	}
4013
4014
	public static function admin_screen_configure_module( $module_id ) {
4015
4016
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4017
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4018
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4019
				/**
4020
				 * Fires to diplay a custom module activation screen.
4021
				 *
4022
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4023
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4024
				 *
4025
				 * @module manage
4026
				 *
4027
				 * @since 3.8.0
4028
				 *
4029
				 * @param int $module_id Module ID.
4030
				 */
4031
				do_action( 'display_activate_module_setting_' . $module_id );
4032
			} else {
4033
				self::display_activate_module_link( $module_id );
4034
			}
4035
4036
			return false;
4037
		} ?>
4038
4039
		<div id="jp-settings-screen" style="position: relative">
4040
			<h3>
4041
			<?php
4042
				$module = Jetpack::get_module( $module_id );
4043
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4044
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4045
			?>
4046
			</h3>
4047
			<?php
4048
				/**
4049
				 * Fires within the displayed message when a feature configuation is updated.
4050
				 *
4051
				 * @since 3.4.0
4052
				 *
4053
				 * @param int $module_id Module ID.
4054
				 */
4055
				do_action( 'jetpack_notices_update_settings', $module_id );
4056
				/**
4057
				 * Fires when a feature configuation screen is loaded.
4058
				 * The dynamic part of the hook, $module_id, is the module ID.
4059
				 *
4060
				 * @since 1.1.0
4061
				 */
4062
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4063
			?>
4064
		</div><?php
4065
	}
4066
4067
	/**
4068
	 * Display link to activate the module to see the settings screen.
4069
	 * @param  string $module_id
4070
	 * @return null
4071
	 */
4072
	public static function display_activate_module_link( $module_id ) {
4073
4074
		$info =  Jetpack::get_module( $module_id );
4075
		$extra = '';
4076
		$activate_url = wp_nonce_url(
4077
				Jetpack::admin_url(
4078
					array(
4079
						'page'   => 'jetpack',
4080
						'action' => 'activate',
4081
						'module' => $module_id,
4082
					)
4083
				),
4084
				"jetpack_activate-$module_id"
4085
			);
4086
4087
		?>
4088
4089
		<div class="wrap configure-module">
4090
			<div id="jp-settings-screen">
4091
				<?php
4092
				if ( $module_id == 'json-api' ) {
4093
4094
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4095
4096
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4097
4098
					$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' );
4099
4100
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4101
				} ?>
4102
4103
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4104
				<div class="narrow">
4105
					<p><?php echo  $info['description']; ?></p>
4106
					<?php if( $extra ) { ?>
4107
					<p><?php echo esc_html( $extra ); ?></p>
4108
					<?php } ?>
4109
					<p>
4110
						<?php
4111
						if( wp_get_referer() ) {
4112
							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() );
4113
						} else {
4114
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4115
						} ?>
4116
					</p>
4117
				</div>
4118
4119
			</div>
4120
		</div>
4121
4122
		<?php
4123
	}
4124
4125
	public static function sort_modules( $a, $b ) {
4126
		if ( $a['sort'] == $b['sort'] )
4127
			return 0;
4128
4129
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4130
	}
4131
4132
	function ajax_recheck_ssl() {
4133
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4134
		$result = Jetpack::permit_ssl( true );
4135
		wp_send_json( array(
4136
			'enabled' => $result,
4137
			'message' => get_transient( 'jetpack_https_test_message' )
4138
		) );
4139
	}
4140
4141
/* Client API */
4142
4143
	/**
4144
	 * Returns the requested Jetpack API URL
4145
	 *
4146
	 * @return string
4147
	 */
4148
	public static function api_url( $relative_url ) {
4149
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4150
	}
4151
4152
	/**
4153
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4154
	 */
4155
	public static function fix_url_for_bad_hosts( $url ) {
4156
		if ( 0 !== strpos( $url, 'https://' ) ) {
4157
			return $url;
4158
		}
4159
4160
		switch ( JETPACK_CLIENT__HTTPS ) {
4161
			case 'ALWAYS' :
4162
				return $url;
4163
			case 'NEVER' :
4164
				return set_url_scheme( $url, 'http' );
4165
			// default : case 'AUTO' :
4166
		}
4167
4168
		// we now return the unmodified SSL URL by default, as a security precaution
4169
		return $url;
4170
	}
4171
4172
	/**
4173
	 * Checks to see if the URL is using SSL to connect with Jetpack
4174
	 *
4175
	 * @since 2.3.3
4176
	 * @return boolean
4177
	 */
4178
	public static function permit_ssl( $force_recheck = false ) {
4179
		// Do some fancy tests to see if ssl is being supported
4180
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4181
			$message = '';
4182
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4183
				$ssl = 0;
4184
			} else {
4185
				switch ( JETPACK_CLIENT__HTTPS ) {
4186
					case 'NEVER':
4187
						$ssl = 0;
4188
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4189
						break;
4190
					case 'ALWAYS':
4191
					case 'AUTO':
4192
					default:
4193
						$ssl = 1;
4194
						break;
4195
				}
4196
4197
				// If it's not 'NEVER', test to see
4198
				if ( $ssl ) {
4199
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4200
						$ssl = 0;
4201
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4202
					} else {
4203
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4204
						if ( is_wp_error( $response ) ) {
4205
							$ssl = 0;
4206
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4207
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4208
							$ssl = 0;
4209
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4210
						}
4211
					}
4212
				}
4213
			}
4214
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4215
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4216
		}
4217
4218
		return (bool) $ssl;
4219
	}
4220
4221
	/*
4222
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4223
	 */
4224
	public function alert_auto_ssl_fail() {
4225
		if ( ! current_user_can( 'manage_options' ) )
4226
			return;
4227
4228
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4229
		?>
4230
4231
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4232
			<div class="jp-banner__content">
4233
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4234
				<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>
4235
				<p>
4236
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4237
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4238
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4239
				</p>
4240
				<p>
4241
					<?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' ),
4242
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4243
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4244
				</p>
4245
			</div>
4246
		</div>
4247
		<style>
4248
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4249
		</style>
4250
		<script type="text/javascript">
4251
			jQuery( document ).ready( function( $ ) {
4252
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4253
					var $this = $( this );
4254
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4255
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4256
					e.preventDefault();
4257
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4258
					$.post( ajaxurl, data )
4259
					  .done( function( response ) {
4260
					  	if ( response.enabled ) {
4261
					  		$( '#jetpack-ssl-warning' ).hide();
4262
					  	} else {
4263
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4264
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4265
					  	}
4266
					  }.bind( $this ) );
4267
				} );
4268
			} );
4269
		</script>
4270
4271
		<?php
4272
	}
4273
4274
	/**
4275
	 * Returns the Jetpack XML-RPC API
4276
	 *
4277
	 * @return string
4278
	 */
4279
	public static function xmlrpc_api_url() {
4280
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4281
		return untrailingslashit( $base ) . '/xmlrpc.php';
4282
	}
4283
4284
	/**
4285
	 * Creates two secret tokens and the end of life timestamp for them.
4286
	 *
4287
	 * Note these tokens are unique per call, NOT static per site for connecting.
4288
	 *
4289
	 * @since 2.6
4290
	 * @return array
4291
	 */
4292
	public function generate_secrets( $action, $exp = 600 ) {
4293
	    $secret = wp_generate_password( 32, false ) // secret_1
4294
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4295
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4296
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4297
		Jetpack_Options::update_option( $action, $secret );
4298
	    return Jetpack_Options::get_option( $action );
4299
	}
4300
4301
	/**
4302
	 * Builds the timeout limit for queries talking with the wpcom servers.
4303
	 *
4304
	 * Based on local php max_execution_time in php.ini
4305
	 *
4306
	 * @since 2.6
4307
	 * @return int
4308
	 **/
4309
	public function get_remote_query_timeout_limit() {
4310
	    $timeout = (int) ini_get( 'max_execution_time' );
4311
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4312
		$timeout = 30;
4313
	    return intval( $timeout / 2 );
4314
	}
4315
4316
4317
	/**
4318
	 * Takes the response from the Jetpack register new site endpoint and
4319
	 * verifies it worked properly.
4320
	 *
4321
	 * @since 2.6
4322
	 * @return true or Jetpack_Error
4323
	 **/
4324
	public function validate_remote_register_response( $response ) {
4325
	    	if ( is_wp_error( $response ) ) {
4326
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4327
		}
4328
4329
		$code   = wp_remote_retrieve_response_code( $response );
4330
		$entity = wp_remote_retrieve_body( $response );
4331
		if ( $entity )
4332
			$json = json_decode( $entity );
4333
		else
4334
			$json = false;
4335
4336
		$code_type = intval( $code / 100 );
4337
		if ( 5 == $code_type ) {
4338
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4339
		} elseif ( 408 == $code ) {
4340
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4341
		} elseif ( ! empty( $json->error ) ) {
4342
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4343
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4344
		} elseif ( 200 != $code ) {
4345
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4346
		}
4347
4348
		// Jetpack ID error block
4349
		if ( empty( $json->jetpack_id ) ) {
4350
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4351
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4352
			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 );
4353
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4354
			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 );
4355
		}
4356
4357
	    return true;
4358
	}
4359
	/**
4360
	 * @return bool|WP_Error
4361
	 */
4362
	public static function register() {
4363
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4364
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4365
4366
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
4367 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4368
			return new Jetpack_Error( 'missing_secrets' );
4369
		}
4370
4371
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4372
4373
		$gmt_offset = get_option( 'gmt_offset' );
4374
		if ( ! $gmt_offset ) {
4375
			$gmt_offset = 0;
4376
		}
4377
4378
		$stats_options = get_option( 'stats_options' );
4379
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4380
4381
		$args = array(
4382
			'method'  => 'POST',
4383
			'body'    => array(
4384
				'siteurl'         => site_url(),
4385
				'home'            => home_url(),
4386
				'gmt_offset'      => $gmt_offset,
4387
				'timezone_string' => (string) get_option( 'timezone_string' ),
4388
				'site_name'       => (string) get_option( 'blogname' ),
4389
				'secret_1'        => $secret_1,
4390
				'secret_2'        => $secret_2,
4391
				'site_lang'       => get_locale(),
4392
				'timeout'         => $timeout,
4393
				'stats_id'        => $stats_id,
4394
				'state'           => get_current_user_id(),
4395
			),
4396
			'headers' => array(
4397
				'Accept' => 'application/json',
4398
			),
4399
			'timeout' => $timeout,
4400
		);
4401
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4402
4403
4404
		// Make sure the response is valid and does not contain any Jetpack errors
4405
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
4406
		if( is_wp_error( $valid_response ) || !$valid_response ) {
4407
		    return $valid_response;
4408
		}
4409
4410
		// Grab the response values to work with
4411
		$code   = wp_remote_retrieve_response_code( $response );
4412
		$entity = wp_remote_retrieve_body( $response );
4413
4414
		if ( $entity )
4415
			$json = json_decode( $entity );
4416
		else
4417
			$json = false;
4418
4419 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4420
			return new Jetpack_Error( 'jetpack_secret', '', $code );
4421
4422
		if ( isset( $json->jetpack_public ) ) {
4423
			$jetpack_public = (int) $json->jetpack_public;
4424
		} else {
4425
			$jetpack_public = false;
4426
		}
4427
4428
		Jetpack_Options::update_options(
4429
			array(
4430
				'id'         => (int)    $json->jetpack_id,
4431
				'blog_token' => (string) $json->jetpack_secret,
4432
				'public'     => $jetpack_public,
4433
			)
4434
		);
4435
4436
		/**
4437
		 * Fires when a site is registered on WordPress.com.
4438
		 *
4439
		 * @since 3.7.0
4440
		 *
4441
		 * @param int $json->jetpack_id Jetpack Blog ID.
4442
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4443
		 * @param int|bool $jetpack_public Is the site public.
4444
		 */
4445
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
4446
4447
		// Initialize Jump Start for the first and only time.
4448
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4449
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4450
4451
			$jetpack = Jetpack::init();
4452
4453
			$jetpack->stat( 'jumpstart', 'unique-views' );
4454
			$jetpack->do_stats( 'server_side' );
4455
		};
4456
4457
		return true;
4458
	}
4459
4460
	/**
4461
	 * If the db version is showing something other that what we've got now, bump it to current.
4462
	 *
4463
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4464
	 */
4465
	public static function maybe_set_version_option() {
4466
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4467
		if ( JETPACK__VERSION != $version ) {
4468
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4469
4470
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4471
				/** This action is documented in class.jetpack.php */
4472
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4473
			}
4474
4475
			return true;
4476
		}
4477
		return false;
4478
	}
4479
4480
/* Client Server API */
4481
4482
	/**
4483
	 * Loads the Jetpack XML-RPC client
4484
	 */
4485
	public static function load_xml_rpc_client() {
4486
		require_once ABSPATH . WPINC . '/class-IXR.php';
4487
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4488
	}
4489
4490
	function verify_xml_rpc_signature() {
4491
		if ( $this->xmlrpc_verification ) {
4492
			return $this->xmlrpc_verification;
4493
		}
4494
4495
		// It's not for us
4496
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4497
			return false;
4498
		}
4499
4500
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
4501
		if (
4502
			empty( $token_key )
4503
		||
4504
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4505
		) {
4506
			return false;
4507
		}
4508
4509
		if ( '0' === $user_id ) {
4510
			$token_type = 'blog';
4511
			$user_id = 0;
4512
		} else {
4513
			$token_type = 'user';
4514
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4515
				return false;
4516
			}
4517
			$user_id = (int) $user_id;
4518
4519
			$user = new WP_User( $user_id );
4520
			if ( ! $user || ! $user->exists() ) {
4521
				return false;
4522
			}
4523
		}
4524
4525
		$token = Jetpack_Data::get_access_token( $user_id );
4526
		if ( ! $token ) {
4527
			return false;
4528
		}
4529
4530
		$token_check = "$token_key.";
4531
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4532
			return false;
4533
		}
4534
4535
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4536
4537
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4538
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4539
			$post_data   = $_POST;
4540
			$file_hashes = array();
4541
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4542
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4543
					continue;
4544
				}
4545
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4546
				$file_hashes[$post_data_key] = $post_data_value;
4547
			}
4548
4549
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4550
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4551
				$post_data[$post_data_key] = $post_data_value;
4552
			}
4553
4554
			ksort( $post_data );
4555
4556
			$body = http_build_query( stripslashes_deep( $post_data ) );
4557
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4558
			$body = file_get_contents( 'php://input' );
4559
		} else {
4560
			$body = null;
4561
		}
4562
		$signature = $jetpack_signature->sign_current_request(
4563
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4564
		);
4565
4566
		if ( ! $signature ) {
4567
			return false;
4568
		} else if ( is_wp_error( $signature ) ) {
4569
			return $signature;
4570
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4571
			return false;
4572
		}
4573
4574
		$timestamp = (int) $_GET['timestamp'];
4575
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4576
4577
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4578
			return false;
4579
		}
4580
4581
		$this->xmlrpc_verification = array(
4582
			'type'    => $token_type,
4583
			'user_id' => $token->external_user_id,
4584
		);
4585
4586
		return $this->xmlrpc_verification;
4587
	}
4588
4589
	/**
4590
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4591
	 */
4592
	function authenticate_jetpack( $user, $username, $password ) {
4593
		if ( is_a( $user, 'WP_User' ) ) {
4594
			return $user;
4595
		}
4596
4597
		$token_details = $this->verify_xml_rpc_signature();
4598
4599
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4600
			return $user;
4601
		}
4602
4603
		if ( 'user' !== $token_details['type'] ) {
4604
			return $user;
4605
		}
4606
4607
		if ( ! $token_details['user_id'] ) {
4608
			return $user;
4609
		}
4610
4611
		nocache_headers();
4612
4613
		return new WP_User( $token_details['user_id'] );
4614
	}
4615
4616
	function add_nonce( $timestamp, $nonce ) {
4617
		global $wpdb;
4618
		static $nonces_used_this_request = array();
4619
4620
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4621
			return $nonces_used_this_request["$timestamp:$nonce"];
4622
		}
4623
4624
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4625
		$timestamp = (int) $timestamp;
4626
		$nonce     = esc_sql( $nonce );
4627
4628
		// Raw query so we can avoid races: add_option will also update
4629
		$show_errors = $wpdb->show_errors( false );
4630
4631
		$old_nonce = $wpdb->get_row(
4632
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4633
		);
4634
4635
		if ( is_null( $old_nonce ) ) {
4636
			$return = $wpdb->query(
4637
				$wpdb->prepare(
4638
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4639
					"jetpack_nonce_{$timestamp}_{$nonce}",
4640
					time(),
4641
					'no'
4642
				)
4643
			);
4644
		} else {
4645
			$return = false;
4646
		}
4647
4648
		$wpdb->show_errors( $show_errors );
4649
4650
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4651
4652
		return $return;
4653
	}
4654
4655
	/**
4656
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4657
	 * Capture it here so we can verify the signature later.
4658
	 */
4659
	function xmlrpc_methods( $methods ) {
4660
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4661
		return $methods;
4662
	}
4663
4664
	function public_xmlrpc_methods( $methods ) {
4665
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4666
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4667
		}
4668
		return $methods;
4669
	}
4670
4671
	function jetpack_getOptions( $args ) {
4672
		global $wp_xmlrpc_server;
4673
4674
		$wp_xmlrpc_server->escape( $args );
4675
4676
		$username	= $args[1];
4677
		$password	= $args[2];
4678
4679
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4680
			return $wp_xmlrpc_server->error;
4681
		}
4682
4683
		$options = array();
4684
		$user_data = $this->get_connected_user_data();
4685
		if ( is_array( $user_data ) ) {
4686
			$options['jetpack_user_id'] = array(
4687
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4688
				'readonly'      => true,
4689
				'value'         => $user_data['ID'],
4690
			);
4691
			$options['jetpack_user_login'] = array(
4692
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4693
				'readonly'      => true,
4694
				'value'         => $user_data['login'],
4695
			);
4696
			$options['jetpack_user_email'] = array(
4697
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4698
				'readonly'      => true,
4699
				'value'         => $user_data['email'],
4700
			);
4701
			$options['jetpack_user_site_count'] = array(
4702
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4703
				'readonly'      => true,
4704
				'value'         => $user_data['site_count'],
4705
			);
4706
		}
4707
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4708
		$args = stripslashes_deep( $args );
4709
		return $wp_xmlrpc_server->wp_getOptions( $args );
4710
	}
4711
4712
	function xmlrpc_options( $options ) {
4713
		$jetpack_client_id = false;
4714
		if ( self::is_active() ) {
4715
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4716
		}
4717
		$options['jetpack_version'] = array(
4718
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4719
				'readonly'      => true,
4720
				'value'         => JETPACK__VERSION,
4721
		);
4722
4723
		$options['jetpack_client_id'] = array(
4724
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4725
				'readonly'      => true,
4726
				'value'         => $jetpack_client_id,
4727
		);
4728
		return $options;
4729
	}
4730
4731
	public static function clean_nonces( $all = false ) {
4732
		global $wpdb;
4733
4734
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4735
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4736
4737
		if ( true !== $all ) {
4738
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4739
			$sql_args[] = time() - 3600;
4740
		}
4741
4742
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4743
4744
		$sql = $wpdb->prepare( $sql, $sql_args );
4745
4746
		for ( $i = 0; $i < 1000; $i++ ) {
4747
			if ( ! $wpdb->query( $sql ) ) {
4748
				break;
4749
			}
4750
		}
4751
	}
4752
4753
	/**
4754
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4755
	 * SET: state( $key, $value );
4756
	 * GET: $value = state( $key );
4757
	 *
4758
	 * @param string $key
4759
	 * @param string $value
4760
	 * @param bool $restate private
4761
	 */
4762
	public static function state( $key = null, $value = null, $restate = false ) {
4763
		static $state = array();
4764
		static $path, $domain;
4765
		if ( ! isset( $path ) ) {
4766
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4767
			$admin_url = Jetpack::admin_url();
4768
			$bits      = parse_url( $admin_url );
4769
4770
			if ( is_array( $bits ) ) {
4771
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4772
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4773
			} else {
4774
				$path = $domain = null;
4775
			}
4776
		}
4777
4778
		// Extract state from cookies and delete cookies
4779
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4780
			$yum = $_COOKIE[ 'jetpackState' ];
4781
			unset( $_COOKIE[ 'jetpackState' ] );
4782
			foreach ( $yum as $k => $v ) {
4783
				if ( strlen( $v ) )
4784
					$state[ $k ] = $v;
4785
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4786
			}
4787
		}
4788
4789
		if ( $restate ) {
4790
			foreach ( $state as $k => $v ) {
4791
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4792
			}
4793
			return;
4794
		}
4795
4796
		// Get a state variable
4797
		if ( isset( $key ) && ! isset( $value ) ) {
4798
			if ( array_key_exists( $key, $state ) )
4799
				return $state[ $key ];
4800
			return null;
4801
		}
4802
4803
		// Set a state variable
4804
		if ( isset ( $key ) && isset( $value ) ) {
4805
			if( is_array( $value ) && isset( $value[0] ) ) {
4806
				$value = $value[0];
4807
			}
4808
			$state[ $key ] = $value;
4809
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4810
		}
4811
	}
4812
4813
	public static function restate() {
4814
		Jetpack::state( null, null, true );
4815
	}
4816
4817
	public static function check_privacy( $file ) {
4818
		static $is_site_publicly_accessible = null;
4819
4820
		if ( is_null( $is_site_publicly_accessible ) ) {
4821
			$is_site_publicly_accessible = false;
4822
4823
			Jetpack::load_xml_rpc_client();
4824
			$rpc = new Jetpack_IXR_Client();
4825
4826
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4827
			if ( $success ) {
4828
				$response = $rpc->getResponse();
4829
				if ( $response ) {
4830
					$is_site_publicly_accessible = true;
4831
				}
4832
			}
4833
4834
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4835
		}
4836
4837
		if ( $is_site_publicly_accessible ) {
4838
			return;
4839
		}
4840
4841
		$module_slug = self::get_module_slug( $file );
4842
4843
		$privacy_checks = Jetpack::state( 'privacy_checks' );
4844
		if ( ! $privacy_checks ) {
4845
			$privacy_checks = $module_slug;
4846
		} else {
4847
			$privacy_checks .= ",$module_slug";
4848
		}
4849
4850
		Jetpack::state( 'privacy_checks', $privacy_checks );
4851
	}
4852
4853
	/**
4854
	 * Helper method for multicall XMLRPC.
4855
	 */
4856
	public static function xmlrpc_async_call() {
4857
		global $blog_id;
4858
		static $clients = array();
4859
4860
		$client_blog_id = is_multisite() ? $blog_id : 0;
4861
4862
		if ( ! isset( $clients[$client_blog_id] ) ) {
4863
			Jetpack::load_xml_rpc_client();
4864
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
4865
			if ( function_exists( 'ignore_user_abort' ) ) {
4866
				ignore_user_abort( true );
4867
			}
4868
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
4869
		}
4870
4871
		$args = func_get_args();
4872
4873
		if ( ! empty( $args[0] ) ) {
4874
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
4875
		} elseif ( is_multisite() ) {
4876
			foreach ( $clients as $client_blog_id => $client ) {
4877
				if ( ! $client_blog_id || empty( $client->calls ) ) {
4878
					continue;
4879
				}
4880
4881
				$switch_success = switch_to_blog( $client_blog_id, true );
4882
				if ( ! $switch_success ) {
4883
					continue;
4884
				}
4885
4886
				flush();
4887
				$client->query();
4888
4889
				restore_current_blog();
4890
			}
4891
		} else {
4892
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
4893
				flush();
4894
				$clients[0]->query();
4895
			}
4896
		}
4897
	}
4898
4899
	public static function staticize_subdomain( $url ) {
4900
4901
		// Extract hostname from URL
4902
		$host = parse_url( $url, PHP_URL_HOST );
4903
4904
		// Explode hostname on '.'
4905
		$exploded_host = explode( '.', $host );
4906
4907
		// Retrieve the name and TLD
4908
		if ( count( $exploded_host ) > 1 ) {
4909
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
4910
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
4911
			// Rebuild domain excluding subdomains
4912
			$domain = $name . '.' . $tld;
4913
		} else {
4914
			$domain = $host;
4915
		}
4916
		// Array of Automattic domains
4917
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
4918
4919
		// Return $url if not an Automattic domain
4920
		if ( ! in_array( $domain, $domain_whitelist ) ) {
4921
			return $url;
4922
		}
4923
4924
		if ( is_ssl() ) {
4925
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
4926
		}
4927
4928
		srand( crc32( basename( $url ) ) );
4929
		$static_counter = rand( 0, 2 );
4930
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
4931
4932
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
4933
	}
4934
4935
/* JSON API Authorization */
4936
4937
	/**
4938
	 * Handles the login action for Authorizing the JSON API
4939
	 */
4940
	function login_form_json_api_authorization() {
4941
		$this->verify_json_api_authorization_request();
4942
4943
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
4944
4945
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
4946
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
4947
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
4948
	}
4949
4950
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
4951
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
4952
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
4953
			return $url;
4954
		}
4955
4956
		$parsed_url = parse_url( $url );
4957
		$url = strtok( $url, '?' );
4958
		$url = "$url?{$_SERVER['QUERY_STRING']}";
4959
		if ( ! empty( $parsed_url['query'] ) )
4960
			$url .= "&{$parsed_url['query']}";
4961
4962
		return $url;
4963
	}
4964
4965
	// Make sure the POSTed request is handled by the same action
4966
	function preserve_action_in_login_form_for_json_api_authorization() {
4967
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
4968
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
4969
	}
4970
4971
	// If someone logs in to approve API access, store the Access Code in usermeta
4972
	function store_json_api_authorization_token( $user_login, $user ) {
4973
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
4974
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
4975
		$token = wp_generate_password( 32, false );
4976
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
4977
	}
4978
4979
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
4980
	function allow_wpcom_public_api_domain( $domains ) {
4981
		$domains[] = 'public-api.wordpress.com';
4982
		return $domains;
4983
	}
4984
4985
	// Add the Access Code details to the public-api.wordpress.com redirect
4986
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
4987
		return add_query_arg(
4988
			urlencode_deep(
4989
				array(
4990
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
4991
					'jetpack-user-id' => (int) $user->ID,
4992
					'jetpack-state'   => $this->json_api_authorization_request['state'],
4993
				)
4994
			),
4995
			$redirect_to
4996
		);
4997
	}
4998
4999
	// Verifies the request by checking the signature
5000
	function verify_json_api_authorization_request() {
5001
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5002
5003
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5004
		if ( ! $token || empty( $token->secret ) ) {
5005
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5006
		}
5007
5008
		$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' );
5009
5010
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5011
5012
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5013
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5014
		} else {
5015
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5016
		}
5017
5018
		if ( ! $signature ) {
5019
			wp_die( $die_error );
5020
		} else if ( is_wp_error( $signature ) ) {
5021
			wp_die( $die_error );
5022
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5023
			if ( is_ssl() ) {
5024
				// 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
5025
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5026
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $_GET['signature'] ) ) {
5027
					wp_die( $die_error );
5028
				}
5029
			} else {
5030
				wp_die( $die_error );
5031
			}
5032
		}
5033
5034
		$timestamp = (int) $_GET['timestamp'];
5035
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5036
5037
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5038
			// De-nonce the nonce, at least for 5 minutes.
5039
			// 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)
5040
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5041
			if ( $old_nonce_time < time() - 300 ) {
5042
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5043
			}
5044
		}
5045
5046
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5047
		$data_filters = array(
5048
			'state'        => 'opaque',
5049
			'client_id'    => 'int',
5050
			'client_title' => 'string',
5051
			'client_image' => 'url',
5052
		);
5053
5054
		foreach ( $data_filters as $key => $sanitation ) {
5055
			if ( ! isset( $data->$key ) ) {
5056
				wp_die( $die_error );
5057
			}
5058
5059
			switch ( $sanitation ) {
5060
			case 'int' :
5061
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5062
				break;
5063
			case 'opaque' :
5064
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5065
				break;
5066
			case 'string' :
5067
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5068
				break;
5069
			case 'url' :
5070
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5071
				break;
5072
			}
5073
		}
5074
5075
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5076
			wp_die( $die_error );
5077
		}
5078
	}
5079
5080
	function login_message_json_api_authorization( $message ) {
5081
		return '<p class="message">' . sprintf(
5082
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5083
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5084
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5085
	}
5086
5087
	/**
5088
	 * Get $content_width, but with a <s>twist</s> filter.
5089
	 */
5090
	public static function get_content_width() {
5091
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5092
		/**
5093
		 * Filter the Content Width value.
5094
		 *
5095
		 * @since 2.2.3
5096
		 *
5097
		 * @param string $content_width Content Width value.
5098
		 */
5099
		return apply_filters( 'jetpack_content_width', $content_width );
5100
	}
5101
5102
	/**
5103
	 * Centralize the function here until it gets added to core.
5104
	 *
5105
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5106
	 * @param int $size Size of the avatar image
5107
	 * @param string $default URL to a default image to use if no avatar is available
5108
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5109
	 *
5110
	 * @return array First element is the URL, second is the class.
5111
	 */
5112
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5113
		// Don't bother adding the __return_true filter if it's already there.
5114
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5115
5116
		if ( $force_display && ! $has_filter )
5117
			add_filter( 'pre_option_show_avatars', '__return_true' );
5118
5119
		$avatar = get_avatar( $id_or_email, $size, $default );
5120
5121
		if ( $force_display && ! $has_filter )
5122
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5123
5124
		// If no data, fail out.
5125
		if ( is_wp_error( $avatar ) || ! $avatar )
5126
			return array( null, null );
5127
5128
		// Pull out the URL.  If it's not there, fail out.
5129
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5130
			return array( null, null );
5131
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5132
5133
		// Pull out the class, but it's not a big deal if it's missing.
5134
		$class = '';
5135
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5136
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5137
5138
		return array( $url, $class );
5139
	}
5140
5141
	/**
5142
	 * Pings the WordPress.com Mirror Site for the specified options.
5143
	 *
5144
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5145
	 *
5146
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5147
	 */
5148
	public function get_cloud_site_options( $option_names ) {
5149
		$option_names = array_filter( (array) $option_names, 'is_string' );
5150
5151
		Jetpack::load_xml_rpc_client();
5152
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5153
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5154
		if ( $xml->isError() ) {
5155
			return array(
5156
				'error_code' => $xml->getErrorCode(),
5157
				'error_msg'  => $xml->getErrorMessage(),
5158
			);
5159
		}
5160
		$cloud_site_options = $xml->getResponse();
5161
5162
		return $cloud_site_options;
5163
	}
5164
5165
	/**
5166
	 * Checks if the site is currently in an identity crisis.
5167
	 *
5168
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5169
	 */
5170
	public static function check_identity_crisis() {
5171
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5172
			return false;
5173
		}
5174
5175
		return Jetpack_Options::get_option( 'sync_error_idc' );
5176
	}
5177
5178
	/**
5179
	 * Checks whether the home and siteurl specifically are whitelisted
5180
	 * Written so that we don't have re-check $key and $value params every time
5181
	 * we want to check if this site is whitelisted, for example in footer.php
5182
	 *
5183
	 * @since  3.8.0
5184
	 * @return bool True = already whitelisted False = not whitelisted
5185
	 */
5186
	public static function is_staging_site() {
5187
		$is_staging = false;
5188
5189
		$known_staging = array(
5190
			'urls' => array(
5191
				'#\.staging\.wpengine\.com$#i', // WP Engine
5192
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5193
				),
5194
			'constants' => array(
5195
				'IS_WPE_SNAPSHOT',      // WP Engine
5196
				'KINSTA_DEV_ENV',       // Kinsta.com
5197
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5198
				'JETPACK_STAGING_MODE', // Generic
5199
				)
5200
			);
5201
		/**
5202
		 * Filters the flags of known staging sites.
5203
		 *
5204
		 * @since 3.9.0
5205
		 *
5206
		 * @param array $known_staging {
5207
		 *     An array of arrays that each are used to check if the current site is staging.
5208
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5209
		 *     @type array $constants PHP constants of known staging/developement environments.
5210
		 *  }
5211
		 */
5212
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5213
5214
		if ( isset( $known_staging['urls'] ) ) {
5215
			foreach ( $known_staging['urls'] as $url ){
5216
				if ( preg_match( $url, site_url() ) ) {
5217
					$is_staging = true;
5218
					break;
5219
				}
5220
			}
5221
		}
5222
5223
		if ( isset( $known_staging['constants'] ) ) {
5224
			foreach ( $known_staging['constants'] as $constant ) {
5225
				if ( defined( $constant ) && constant( $constant ) ) {
5226
					$is_staging = true;
5227
				}
5228
			}
5229
		}
5230
5231
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5232
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5233
			$is_staging = true;
5234
		}
5235
5236
		/**
5237
		 * Filters is_staging_site check.
5238
		 *
5239
		 * @since 3.9.0
5240
		 *
5241
		 * @param bool $is_staging If the current site is a staging site.
5242
		 */
5243
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5244
	}
5245
5246
	/**
5247
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5248
	 *
5249
	 * @return bool
5250
	 */
5251
	public static function validate_sync_error_idc_option() {
5252
		$is_valid = false;
5253
5254
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5255
		if ( false === $idc_allowed ) {
5256
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5257
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5258
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5259
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5260
				$transient_duration = HOUR_IN_SECONDS;
5261
			} else {
5262
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5263
				$idc_allowed = '1';
5264
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5265
			}
5266
5267
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5268
		}
5269
5270
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5271
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5272
		$local_options = self::get_sync_error_idc_option();
5273
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5274
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5275
				$is_valid = true;
5276
			}
5277
		}
5278
5279
		/**
5280
		 * Filters whether the sync_error_idc option is valid.
5281
		 *
5282
		 * @since 4.4.0
5283
		 *
5284
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5285
		 */
5286
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5287
5288
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5289
			// Since the option exists, and did not validate, delete it
5290
			Jetpack_Options::delete_option( 'sync_error_idc' );
5291
		}
5292
5293
		return $is_valid;
5294
	}
5295
5296
	/**
5297
	 * Normalizes a url by doing three things:
5298
	 *  - Strips protocol
5299
	 *  - Strips www
5300
	 *  - Adds a trailing slash
5301
	 *
5302
	 * @since 4.4.0
5303
	 * @param string $url
5304
	 * @return WP_Error|string
5305
	 */
5306
	public static function normalize_url_protocol_agnostic( $url ) {
5307
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5308
		if ( ! $parsed_url ) {
5309
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5310
		}
5311
5312
		// Strip www and protocols
5313
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5314
		return $url;
5315
	}
5316
5317
	/**
5318
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5319
	 *
5320
	 * @since 4.4.0
5321
	 *
5322
	 * @param array $response
5323
	 * @return array Array of the local urls, wpcom urls, and error code
5324
	 */
5325
	public static function get_sync_error_idc_option( $response = array() ) {
5326
		$local_options = array(
5327
			'home' => get_home_url(),
5328
			'siteurl' => get_site_url(),
5329
		);
5330
5331
		$options = array_merge( $local_options, $response );
5332
5333
		$returned_values = array();
5334
		foreach( $options as $key => $option ) {
5335
			if ( 'error_code' === $key ) {
5336
				$returned_values[ $key ] = $option;
5337
				continue;
5338
			}
5339
5340
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5341
				continue;
5342
			}
5343
5344
			$returned_values[ $key ] = $normalized_url;
5345
		}
5346
5347
		return $returned_values;
5348
	}
5349
5350
	/**
5351
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5352
	 * If set to true, the site will be put into staging mode.
5353
	 *
5354
	 * @since 4.3.2
5355
	 * @return bool
5356
	 */
5357
	public static function sync_idc_optin() {
5358
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5359
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5360
		} else {
5361
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5362
		}
5363
5364
		/**
5365
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5366
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5367
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5368
		 *
5369
		 * @since 4.3.2
5370
		 *
5371
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5372
		 */
5373
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5374
	}
5375
5376
	/**
5377
	 * Maybe Use a .min.css stylesheet, maybe not.
5378
	 *
5379
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5380
	 */
5381
	public static function maybe_min_asset( $url, $path, $plugin ) {
5382
		// Short out on things trying to find actual paths.
5383
		if ( ! $path || empty( $plugin ) ) {
5384
			return $url;
5385
		}
5386
5387
		// Strip out the abspath.
5388
		$base = dirname( plugin_basename( $plugin ) );
5389
5390
		// Short out on non-Jetpack assets.
5391
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5392
			return $url;
5393
		}
5394
5395
		// File name parsing.
5396
		$file              = "{$base}/{$path}";
5397
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5398
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5399
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5400
		$extension         = array_shift( $file_name_parts_r );
5401
5402
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5403
			// Already pointing at the minified version.
5404
			if ( 'min' === $file_name_parts_r[0] ) {
5405
				return $url;
5406
			}
5407
5408
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5409
			if ( file_exists( $min_full_path ) ) {
5410
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5411
			}
5412
		}
5413
5414
		return $url;
5415
	}
5416
5417
	/**
5418
	 * Maybe inlines a stylesheet.
5419
	 *
5420
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5421
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5422
	 *
5423
	 * Attached to `style_loader_tag` filter.
5424
	 *
5425
	 * @param string $tag The tag that would link to the external asset.
5426
	 * @param string $handle The registered handle of the script in question.
5427
	 *
5428
	 * @return string
5429
	 */
5430
	public static function maybe_inline_style( $tag, $handle ) {
5431
		global $wp_styles;
5432
		$item = $wp_styles->registered[ $handle ];
5433
5434
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5435
			return $tag;
5436
		}
5437
5438
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5439
			$href = $matches[1];
5440
			// Strip off query string
5441
			if ( $pos = strpos( $href, '?' ) ) {
5442
				$href = substr( $href, 0, $pos );
5443
			}
5444
			// Strip off fragment
5445
			if ( $pos = strpos( $href, '#' ) ) {
5446
				$href = substr( $href, 0, $pos );
5447
			}
5448
		} else {
5449
			return $tag;
5450
		}
5451
5452
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5453
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5454
			return $tag;
5455
		}
5456
5457
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5458
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5459
			// And this isn't the pass that actually deals with the RTL version...
5460
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5461
				// Short out, as the RTL version will deal with it in a moment.
5462
				return $tag;
5463
			}
5464
		}
5465
5466
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5467
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5468
		if ( $css ) {
5469
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5470
			if ( empty( $item->extra['after'] ) ) {
5471
				wp_add_inline_style( $handle, $css );
5472
			} else {
5473
				array_unshift( $item->extra['after'], $css );
5474
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5475
			}
5476
		}
5477
5478
		return $tag;
5479
	}
5480
5481
	/**
5482
	 * Loads a view file from the views
5483
	 *
5484
	 * Data passed in with the $data parameter will be available in the
5485
	 * template file as $data['value']
5486
	 *
5487
	 * @param string $template - Template file to load
5488
	 * @param array $data - Any data to pass along to the template
5489
	 * @return boolean - If template file was found
5490
	 **/
5491
	public function load_view( $template, $data = array() ) {
5492
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5493
5494
		if( file_exists( $views_dir . $template ) ) {
5495
			require_once( $views_dir . $template );
5496
			return true;
5497
		}
5498
5499
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5500
		return false;
5501
	}
5502
5503
	/**
5504
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5505
	 */
5506
	public function deprecated_hooks() {
5507
		global $wp_filter;
5508
5509
		/*
5510
		 * Format:
5511
		 * deprecated_filter_name => replacement_name
5512
		 *
5513
		 * If there is no replacement us null for replacement_name
5514
		 */
5515
		$deprecated_list = array(
5516
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5517
			'wpl_sharing_2014_1'                                     => null,
5518
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5519
			'jetpack_identity_crisis_options_to_check'               => null,
5520
			'update_option_jetpack_single_user_site'                 => null,
5521
			'audio_player_default_colors'                            => null,
5522
			'add_option_jetpack_featured_images_enabled'             => null,
5523
			'add_option_jetpack_update_details'                      => null,
5524
			'add_option_jetpack_updates'                             => null,
5525
			'add_option_jetpack_network_name'                        => null,
5526
			'add_option_jetpack_network_allow_new_registrations'     => null,
5527
			'add_option_jetpack_network_add_new_users'               => null,
5528
			'add_option_jetpack_network_site_upload_space'           => null,
5529
			'add_option_jetpack_network_upload_file_types'           => null,
5530
			'add_option_jetpack_network_enable_administration_menus' => null,
5531
			'add_option_jetpack_is_multi_site'                       => null,
5532
			'add_option_jetpack_is_main_network'                     => null,
5533
			'add_option_jetpack_main_network_site'                   => null,
5534
			'jetpack_sync_all_registered_options'                    => null,
5535
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5536
		);
5537
5538
		// This is a silly loop depth. Better way?
5539
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5540
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
5541
				foreach( $wp_filter[$hook] AS $func => $values ) {
5542
					foreach( $values AS $hooked ) {
5543
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
5544
					}
5545
				}
5546
			}
5547
		}
5548
	}
5549
5550
	/**
5551
	 * Converts any url in a stylesheet, to the correct absolute url.
5552
	 *
5553
	 * Considerations:
5554
	 *  - Normal, relative URLs     `feh.png`
5555
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5556
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5557
	 *  - Absolute URLs             `http://domain.com/feh.png`
5558
	 *  - Domain root relative URLs `/feh.png`
5559
	 *
5560
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5561
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5562
	 *
5563
	 * @return mixed|string
5564
	 */
5565
	public static function absolutize_css_urls( $css, $css_file_url ) {
5566
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5567
		$css_dir = dirname( $css_file_url );
5568
		$p       = parse_url( $css_dir );
5569
		$domain  = sprintf(
5570
					'%1$s//%2$s%3$s%4$s',
5571
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5572
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5573
					$p['host'],
5574
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5575
				);
5576
5577
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5578
			$find = $replace = array();
5579
			foreach ( $matches as $match ) {
5580
				$url = trim( $match['path'], "'\" \t" );
5581
5582
				// If this is a data url, we don't want to mess with it.
5583
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5584
					continue;
5585
				}
5586
5587
				// If this is an absolute or protocol-agnostic url,
5588
				// we don't want to mess with it.
5589
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5590
					continue;
5591
				}
5592
5593
				switch ( substr( $url, 0, 1 ) ) {
5594
					case '/':
5595
						$absolute = $domain . $url;
5596
						break;
5597
					default:
5598
						$absolute = $css_dir . '/' . $url;
5599
				}
5600
5601
				$find[]    = $match[0];
5602
				$replace[] = sprintf( 'url("%s")', $absolute );
5603
			}
5604
			$css = str_replace( $find, $replace, $css );
5605
		}
5606
5607
		return $css;
5608
	}
5609
5610
	/**
5611
	 * This methods removes all of the registered css files on the front end
5612
	 * from Jetpack in favor of using a single file. In effect "imploding"
5613
	 * all the files into one file.
5614
	 *
5615
	 * Pros:
5616
	 * - Uses only ONE css asset connection instead of 15
5617
	 * - Saves a minimum of 56k
5618
	 * - Reduces server load
5619
	 * - Reduces time to first painted byte
5620
	 *
5621
	 * Cons:
5622
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5623
	 *		should not cause any issues with themes.
5624
	 * - Plugins/themes dequeuing styles no longer do anything. See
5625
	 *		jetpack_implode_frontend_css filter for a workaround
5626
	 *
5627
	 * For some situations developers may wish to disable css imploding and
5628
	 * instead operate in legacy mode where each file loads seperately and
5629
	 * can be edited individually or dequeued. This can be accomplished with
5630
	 * the following line:
5631
	 *
5632
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5633
	 *
5634
	 * @since 3.2
5635
	 **/
5636
	public function implode_frontend_css( $travis_test = false ) {
5637
		$do_implode = true;
5638
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5639
			$do_implode = false;
5640
		}
5641
5642
		/**
5643
		 * Allow CSS to be concatenated into a single jetpack.css file.
5644
		 *
5645
		 * @since 3.2.0
5646
		 *
5647
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5648
		 */
5649
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5650
5651
		// Do not use the imploded file when default behaviour was altered through the filter
5652
		if ( ! $do_implode ) {
5653
			return;
5654
		}
5655
5656
		// We do not want to use the imploded file in dev mode, or if not connected
5657
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5658
			if ( ! $travis_test ) {
5659
				return;
5660
			}
5661
		}
5662
5663
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5664
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5665
			return;
5666
		}
5667
5668
		/*
5669
		 * Now we assume Jetpack is connected and able to serve the single
5670
		 * file.
5671
		 *
5672
		 * In the future there will be a check here to serve the file locally
5673
		 * or potentially from the Jetpack CDN
5674
		 *
5675
		 * For now:
5676
		 * - Enqueue a single imploded css file
5677
		 * - Zero out the style_loader_tag for the bundled ones
5678
		 * - Be happy, drink scotch
5679
		 */
5680
5681
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5682
5683
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5684
5685
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5686
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5687
	}
5688
5689
	function concat_remove_style_loader_tag( $tag, $handle ) {
5690
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5691
			$tag = '';
5692
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5693
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5694
			}
5695
		}
5696
5697
		return $tag;
5698
	}
5699
5700
	/*
5701
	 * Check the heartbeat data
5702
	 *
5703
	 * Organizes the heartbeat data by severity.  For example, if the site
5704
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5705
	 *
5706
	 * Data will be added to "caution" array, if it either:
5707
	 *  - Out of date Jetpack version
5708
	 *  - Out of date WP version
5709
	 *  - Out of date PHP version
5710
	 *
5711
	 * $return array $filtered_data
5712
	 */
5713
	public static function jetpack_check_heartbeat_data() {
5714
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5715
5716
		$good    = array();
5717
		$caution = array();
5718
		$bad     = array();
5719
5720
		foreach ( $raw_data as $stat => $value ) {
5721
5722
			// Check jetpack version
5723
			if ( 'version' == $stat ) {
5724
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5725
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5726
					continue;
5727
				}
5728
			}
5729
5730
			// Check WP version
5731
			if ( 'wp-version' == $stat ) {
5732
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5733
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5734
					continue;
5735
				}
5736
			}
5737
5738
			// Check PHP version
5739
			if ( 'php-version' == $stat ) {
5740
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5741
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5742
					continue;
5743
				}
5744
			}
5745
5746
			// Check ID crisis
5747
			if ( 'identitycrisis' == $stat ) {
5748
				if ( 'yes' == $value ) {
5749
					$bad[ $stat ] = $value;
5750
					continue;
5751
				}
5752
			}
5753
5754
			// The rest are good :)
5755
			$good[ $stat ] = $value;
5756
		}
5757
5758
		$filtered_data = array(
5759
			'good'    => $good,
5760
			'caution' => $caution,
5761
			'bad'     => $bad
5762
		);
5763
5764
		return $filtered_data;
5765
	}
5766
5767
5768
	/*
5769
	 * This method is used to organize all options that can be reset
5770
	 * without disconnecting Jetpack.
5771
	 *
5772
	 * It is used in class.jetpack-cli.php to reset options
5773
	 *
5774
	 * @return array of options to delete.
5775
	 */
5776
	public static function get_jetpack_options_for_reset() {
5777
		$jetpack_options            = Jetpack_Options::get_option_names();
5778
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
5779
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
5780
5781
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
5782
5783
		// A manual build of the wp options
5784
		$wp_options = array(
5785
			'sharing-options',
5786
			'disabled_likes',
5787
			'disabled_reblogs',
5788
			'jetpack_comments_likes_enabled',
5789
			'wp_mobile_excerpt',
5790
			'wp_mobile_featured_images',
5791
			'wp_mobile_app_promos',
5792
			'stats_options',
5793
			'stats_dashboard_widget',
5794
			'safecss_preview_rev',
5795
			'safecss_rev',
5796
			'safecss_revision_migrated',
5797
			'nova_menu_order',
5798
			'jetpack_portfolio',
5799
			'jetpack_portfolio_posts_per_page',
5800
			'jetpack_testimonial',
5801
			'jetpack_testimonial_posts_per_page',
5802
			'wp_mobile_custom_css',
5803
			'sharedaddy_disable_resources',
5804
			'sharing-options',
5805
			'sharing-services',
5806
			'site_icon_temp_data',
5807
			'featured-content',
5808
			'site_logo',
5809
			'jetpack_dismissed_notices',
5810
		);
5811
5812
		// Flag some Jetpack options as unsafe
5813
		$unsafe_options = array(
5814
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
5815
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
5816
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
5817
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
5818
5819
			// non_compact
5820
			'activated',
5821
5822
			// private
5823
			'register',
5824
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
5825
			'user_token',                  // (string) The User Token of this site. (deprecated)
5826
			'user_tokens'
5827
		);
5828
5829
		// Remove the unsafe Jetpack options
5830
		foreach ( $unsafe_options as $unsafe_option ) {
5831
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
5832
				unset( $all_jp_options[ $key ] );
5833
			}
5834
		}
5835
5836
		$options = array(
5837
			'jp_options' => $all_jp_options,
5838
			'wp_options' => $wp_options
5839
		);
5840
5841
		return $options;
5842
	}
5843
5844
	/**
5845
	 * Check if an option of a Jetpack module has been updated.
5846
	 *
5847
	 * If any module option has been updated before Jump Start has been dismissed,
5848
	 * update the 'jumpstart' option so we can hide Jump Start.
5849
	 *
5850
	 * @param string $option_name
5851
	 *
5852
	 * @return bool
5853
	 */
5854
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5855
		// Bail if Jump Start has already been dismissed
5856
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
5857
			return false;
5858
		}
5859
5860
		$jetpack = Jetpack::init();
5861
5862
		// Manual build of module options
5863
		$option_names = self::get_jetpack_options_for_reset();
5864
5865
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5866
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5867
5868
			//Jump start is being dismissed send data to MC Stats
5869
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5870
5871
			$jetpack->do_stats( 'server_side' );
5872
		}
5873
5874
	}
5875
5876
	/*
5877
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
5878
	 * so we can bring them directly to their site in calypso.
5879
	 *
5880
	 * @param string | url
5881
	 * @return string | url without the guff
5882
	 */
5883
	public static function build_raw_urls( $url ) {
5884
		$strip_http = '/.*?:\/\//i';
5885
		$url = preg_replace( $strip_http, '', $url  );
5886
		$url = str_replace( '/', '::', $url );
5887
		return $url;
5888
	}
5889
5890
	/**
5891
	 * Stores and prints out domains to prefetch for page speed optimization.
5892
	 *
5893
	 * @param mixed $new_urls
5894
	 */
5895
	public static function dns_prefetch( $new_urls = null ) {
5896
		static $prefetch_urls = array();
5897
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
5898
			echo "\r\n";
5899
			foreach ( $prefetch_urls as $this_prefetch_url ) {
5900
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
5901
			}
5902
		} elseif ( ! empty( $new_urls ) ) {
5903
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
5904
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
5905
			}
5906
			foreach ( (array) $new_urls as $this_new_url ) {
5907
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
5908
			}
5909
			$prefetch_urls = array_unique( $prefetch_urls );
5910
		}
5911
	}
5912
5913
	public function wp_dashboard_setup() {
5914
		if ( self::is_active() ) {
5915
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
5916
			$widget_title = __( 'Site Stats', 'jetpack' );
5917
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
5918
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
5919
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
5920
		}
5921
5922
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
5923
			wp_add_dashboard_widget(
5924
				'jetpack_summary_widget',
5925
				$widget_title,
5926
				array( __CLASS__, 'dashboard_widget' )
5927
			);
5928
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
5929
5930
			// If we're inactive and not in development mode, sort our box to the top.
5931
			if ( ! self::is_active() && ! self::is_development_mode() ) {
5932
				global $wp_meta_boxes;
5933
5934
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
5935
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
5936
5937
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
5938
			}
5939
		}
5940
	}
5941
5942
	/**
5943
	 * @param mixed $result Value for the user's option
5944
	 * @return mixed
5945
	 */
5946
	function get_user_option_meta_box_order_dashboard( $sorted ) {
5947
		if ( ! is_array( $sorted ) ) {
5948
			return $sorted;
5949
		}
5950
5951
		foreach ( $sorted as $box_context => $ids ) {
5952
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
5953
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
5954
				continue;
5955
			}
5956
5957
			$ids_array = explode( ',', $ids );
5958
			$key = array_search( 'dashboard_stats', $ids_array );
5959
5960
			if ( false !== $key ) {
5961
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
5962
				$ids_array[ $key ] = 'jetpack_summary_widget';
5963
				$sorted[ $box_context ] = implode( ',', $ids_array );
5964
				// We've found it, stop searching, and just return.
5965
				break;
5966
			}
5967
		}
5968
5969
		return $sorted;
5970
	}
5971
5972
	public static function dashboard_widget() {
5973
		/**
5974
		 * Fires when the dashboard is loaded.
5975
		 *
5976
		 * @since 3.4.0
5977
		 */
5978
		do_action( 'jetpack_dashboard_widget' );
5979
	}
5980
5981
	public static function dashboard_widget_footer() {
5982
		?>
5983
		<footer>
5984
5985
		<div class="protect">
5986
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
5987
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
5988
				<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>
5989
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
5990
				<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' ); ?>">
5991
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
5992
				</a>
5993
			<?php else : ?>
5994
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
5995
			<?php endif; ?>
5996
		</div>
5997
5998
		<div class="akismet">
5999
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6000
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6001
				<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>
6002
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6003
				<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">
6004
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6005
				</a>
6006
			<?php else : ?>
6007
				<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>
6008
			<?php endif; ?>
6009
		</div>
6010
6011
		</footer>
6012
		<?php
6013
	}
6014
6015
	public function dashboard_widget_connect_to_wpcom() {
6016
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6017
			return;
6018
		}
6019
		?>
6020
		<div class="wpcom-connect">
6021
			<div class="jp-emblem">
6022
			<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">
6023
				<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"/>
6024
			</svg>
6025
			</div>
6026
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6027
			<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>
6028
6029
			<div class="actions">
6030
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6031
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6032
				</a>
6033
			</div>
6034
		</div>
6035
		<?php
6036
	}
6037
6038
	/*
6039
	 * A graceful transition to using Core's site icon.
6040
	 *
6041
	 * All of the hard work has already been done with the image
6042
	 * in all_done_page(). All that needs to be done now is update
6043
	 * the option and display proper messaging.
6044
	 *
6045
	 * @todo remove when WP 4.3 is minimum
6046
	 *
6047
	 * @since 3.6.1
6048
	 *
6049
	 * @return bool false = Core's icon not available || true = Core's icon is available
6050
	 */
6051
	public static function jetpack_site_icon_available_in_core() {
6052
		global $wp_version;
6053
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
6054
6055
		if ( ! $core_icon_available ) {
6056
			return false;
6057
		}
6058
6059
		// No need for Jetpack's site icon anymore if core's is already set
6060
		if ( has_site_icon() ) {
6061
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
6062
				Jetpack::log( 'deactivate', 'site-icon' );
6063
				Jetpack::deactivate_module( 'site-icon' );
6064
			}
6065
			return true;
6066
		}
6067
6068
		// Transfer Jetpack's site icon to use core.
6069
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
6070
		if ( $site_icon_id ) {
6071
			// Update core's site icon
6072
			update_option( 'site_icon', $site_icon_id );
6073
6074
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
6075
			delete_option( 'site_icon_id' );
6076
		}
6077
6078
		// No need for Jetpack's site icon anymore
6079
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
6080
			Jetpack::log( 'deactivate', 'site-icon' );
6081
			Jetpack::deactivate_module( 'site-icon' );
6082
		}
6083
6084
		return true;
6085
	}
6086
6087
	/**
6088
	 * Return string containing the Jetpack logo.
6089
	 *
6090
	 * @since 3.9.0
6091
	 *
6092
	 * @return string
6093
	 */
6094
	public static function get_jp_emblem() {
6095
		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>';
6096
	}
6097
6098
	/*
6099
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6100
	 */
6101
	function jetpack_icon_user_connected( $columns ) {
6102
		$columns['user_jetpack'] = '';
6103
		return $columns;
6104
	}
6105
6106
	/*
6107
	 * Show Jetpack icon if the user is linked.
6108
	 */
6109
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6110
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6111
			$emblem_html = sprintf(
6112
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6113
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6114
				Jetpack::get_jp_emblem()
6115
			);
6116
			return $emblem_html;
6117
		}
6118
6119
		return $val;
6120
	}
6121
6122
	/*
6123
	 * Style the Jetpack user column
6124
	 */
6125
	function jetpack_user_col_style() {
6126
		global $current_screen;
6127
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6128
			<style>
6129
				.fixed .column-user_jetpack {
6130
					width: 21px;
6131
				}
6132
				.jp-emblem-user-admin path {
6133
					fill: #8cc258;
6134
				}
6135
			</style>
6136
		<?php }
6137
	}
6138
6139
}
6140