Completed
Push — try/user_token-auth-for-rest-a... ( 422660...ea5d0d )
by
unknown
08:47
created

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