Completed
Push — try/alt-xmlrpc ( e08316...b11532 )
by
unknown
64:36 queued 54:32
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
		'eu-cookie-law-style',
60
		'flickr-widget-style',
61
	);
62
63
	public $plugins_to_deactivate = array(
64
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
65
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
66
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
67
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
68
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
69
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
70
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
71
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
72
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
73
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
74
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
75
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
76
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
77
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
78
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
79
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
80
	);
81
82
	static $capability_translations = array(
83
		'administrator' => 'manage_options',
84
		'editor'        => 'edit_others_posts',
85
		'author'        => 'publish_posts',
86
		'contributor'   => 'edit_posts',
87
		'subscriber'    => 'read',
88
	);
89
90
	/**
91
	 * Map of modules that have conflicts with plugins and should not be auto-activated
92
	 * if the plugins are active.  Used by filter_default_modules
93
	 *
94
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
95
	 * change `module-slug` and add this to your plugin:
96
	 *
97
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
98
	 * function my_jetpack_get_default_modules( $modules ) {
99
	 *     return array_diff( $modules, array( 'module-slug' ) );
100
	 * }
101
	 *
102
	 * @var array
103
	 */
104
	private $conflicting_plugins = array(
105
		'comments'          => array(
106
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
107
			'Disqus'                               => 'disqus-comment-system/disqus.php',
108
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
109
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
110
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
111
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
112
		),
113
		'contact-form'      => array(
114
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
115
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
116
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
117
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
118
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
119
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
120
		),
121
		'minileven'         => array(
122
			'WPtouch'                              => 'wptouch/wptouch.php',
123
		),
124
		'latex'             => array(
125
			'LaTeX for WordPress'                  => 'latex/latex.php',
126
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
127
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
128
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
129
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
130
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
131
		),
132
		'protect'           => array(
133
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
134
			'Captcha'                              => 'captcha/captcha.php',
135
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
136
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
137
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
138
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
139
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
140
			'Security-protection'                  => 'security-protection/security-protection.php',
141
			'Login Security'                       => 'login-security/login-security.php',
142
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
143
			'Wordfence Security'                   => 'wordfence/wordfence.php',
144
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
145
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
146
		),
147
		'random-redirect'   => array(
148
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
149
		),
150
		'related-posts'     => array(
151
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
152
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
153
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
154
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
155
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
156
			'outbrain'                             => 'outbrain/outbrain.php',
157
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
158
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
159
		),
160
		'sharedaddy'        => array(
161
			'AddThis'                              => 'addthis/addthis_social_widget.php',
162
			'Add To Any'                           => 'add-to-any/add-to-any.php',
163
			'ShareThis'                            => 'share-this/sharethis.php',
164
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
165
		),
166
		'seo-tools' => array(
167
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
168
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
169
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
170
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
171
		),
172
		'verification-tools' => array(
173
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
174
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
175
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
176
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
177
		),
178
		'widget-visibility' => array(
179
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
180
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
181
		),
182
		'sitemaps' => array(
183
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
184
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
185
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
186
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
187
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
188
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
189
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
190
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
191
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
192
			'Sitemap'                              => 'sitemap/sitemap.php',
193
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
194
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
195
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
196
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
197
		),
198
	);
199
200
	/**
201
	 * Plugins for which we turn off our Facebook OG Tags implementation.
202
	 *
203
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
204
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
205
	 *
206
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
207
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
208
	 */
209
	private $open_graph_conflicting_plugins = array(
210
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
211
		                                                         // 2 Click Social Media Buttons
212
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
213
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
214
		'autodescription/autodescription.php',                   // The SEO Framework
215
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
216
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
217
		                                                         // Open Graph Meta Tags by Heateor
218
		'facebook/facebook.php',                                 // Facebook (official plugin)
219
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
220
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
221
		                                                         // Facebook Featured Image & OG Meta Tags
222
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
223
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
224
		                                                         // Facebook Open Graph Meta Tags for WordPress
225
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
226
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
227
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
228
		                                                         // Fedmich's Facebook Open Graph Meta
229
		'network-publisher/networkpub.php',                      // Network Publisher
230
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
231
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
232
		                                                         // NextScripts SNAP
233
		'og-tags/og-tags.php',                                   // OG Tags
234
		'opengraph/opengraph.php',                               // Open Graph
235
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
236
		                                                         // Open Graph Protocol Framework
237
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
238
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
239
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
240
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
241
		'sharepress/sharepress.php',                             // SharePress
242
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
243
		'social-discussions/social-discussions.php',             // Social Discussions
244
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
245
		'socialize/socialize.php',                               // Socialize
246
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
247
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
248
		                                                         // Tweet, Like, Google +1 and Share
249
		'wordbooker/wordbooker.php',                             // Wordbooker
250
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
251
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
252
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
253
		                                                         // WP Facebook Like Send & Open Graph Meta
254
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
255
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
256
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
257
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
258
	);
259
260
	/**
261
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
262
	 */
263
	private $twitter_cards_conflicting_plugins = array(
264
	//	'twitter/twitter.php',                       // The official one handles this on its own.
265
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
266
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
267
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
268
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
269
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
270
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
271
		'twitter-cards/twitter-cards.php',           // Twitter Cards
272
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
273
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
274
	);
275
276
	/**
277
	 * Message to display in admin_notice
278
	 * @var string
279
	 */
280
	public $message = '';
281
282
	/**
283
	 * Error to display in admin_notice
284
	 * @var string
285
	 */
286
	public $error = '';
287
288
	/**
289
	 * Modules that need more privacy description.
290
	 * @var string
291
	 */
292
	public $privacy_checks = '';
293
294
	/**
295
	 * Stats to record once the page loads
296
	 *
297
	 * @var array
298
	 */
299
	public $stats = array();
300
301
	/**
302
	 * Jetpack_Sync object
303
	 */
304
	public $sync;
305
306
	/**
307
	 * Verified data for JSON authorization request
308
	 */
309
	public $json_api_authorization_request = array();
310
311
	/**
312
	 * Holds the singleton instance of this class
313
	 * @since 2.3.3
314
	 * @var Jetpack
315
	 */
316
	static $instance = false;
317
318
	/**
319
	 * Singleton
320
	 * @static
321
	 */
322
	public static function init() {
323
		if ( ! self::$instance ) {
324
			self::$instance = new Jetpack;
325
326
			self::$instance->plugin_upgrade();
327
		}
328
329
		return self::$instance;
330
	}
331
332
	/**
333
	 * Must never be called statically
334
	 */
335
	function plugin_upgrade() {
336
		if ( Jetpack::is_active() ) {
337
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
338
			if ( JETPACK__VERSION != $version ) {
339
340
				// check which active modules actually exist and remove others from active_modules list
341
				$unfiltered_modules = Jetpack::get_active_modules();
342
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
343
				if ( array_diff( $unfiltered_modules, $modules ) ) {
344
					Jetpack::update_active_modules( $modules );
345
				}
346
347
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
348
349
				// Upgrade to 4.3.0
350
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
351
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
352
				}
353
354
				// Make sure Markdown for posts gets turned back on
355
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
356
					update_option( 'wpcom_publish_posts_with_markdown', true );
357
				}
358
359
				if ( did_action( 'wp_loaded' ) ) {
360
					self::upgrade_on_load();
361
				} else {
362
					add_action(
363
						'wp_loaded',
364
						array( __CLASS__, 'upgrade_on_load' )
365
					);
366
				}
367
			}
368
		}
369
	}
370
371
	/**
372
	 * Runs upgrade routines that need to have modules loaded.
373
	 */
374
	static function upgrade_on_load() {
375
376
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
377
		// This can happen in case Jetpack has been just upgraded and is
378
		// being initialized late during the page load. In this case we wait
379
		// until the next proper admin page load with Jetpack active.
380
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
381
			return;
382
		}
383
384
		Jetpack::maybe_set_version_option();
385
386
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
387
			Jetpack_Widget_Conditions::migrate_post_type_rules();
388
		}
389
	}
390
391
	static function activate_manage( ) {
392
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
393
			self::activate_module( 'manage', false, false );
394
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
395
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
396
		}
397
	}
398
399
	static function update_active_modules( $modules ) {
400
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
401
402
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
403
404
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
405
			$new_active_modules = array_diff( $modules, $current_modules );
406
			foreach( $new_active_modules as $module ) {
407
				/**
408
				 * Fires when a specific module is activated.
409
				 *
410
				 * @since 1.9.0
411
				 *
412
				 * @param string $module Module slug.
413
				 * @param boolean $success whether the module was activated. @since 4.2
414
				 */
415
				do_action( 'jetpack_activate_module', $module, $success );
416
417
				/**
418
				 * Fires when a module is activated.
419
				 * The dynamic part of the filter, $module, is the module slug.
420
				 *
421
				 * @since 1.9.0
422
				 *
423
				 * @param string $module Module slug.
424
				 */
425
				do_action( "jetpack_activate_module_$module", $module );
426
			}
427
428
			$new_deactive_modules = array_diff( $current_modules, $modules );
429
			foreach( $new_deactive_modules as $module ) {
430
				/**
431
				 * Fired after a module has been deactivated.
432
				 *
433
				 * @since 4.2.0
434
				 *
435
				 * @param string $module Module slug.
436
				 * @param boolean $success whether the module was deactivated.
437
				 */
438
				do_action( 'jetpack_deactivate_module', $module, $success );
439
				/**
440
				 * Fires when a module is deactivated.
441
				 * The dynamic part of the filter, $module, is the module slug.
442
				 *
443
				 * @since 1.9.0
444
				 *
445
				 * @param string $module Module slug.
446
				 */
447
				do_action( "jetpack_deactivate_module_$module", $module );
448
			}
449
		}
450
451
		return $success;
452
	}
453
454
	static function delete_active_modules() {
455
		self::update_active_modules( array() );
456
	}
457
458
	/**
459
	 * Constructor.  Initializes WordPress hooks
460
	 */
461
	private function __construct() {
462
		/*
463
		 * Check for and alert any deprecated hooks
464
		 */
465
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
466
467
		/*
468
		 * Load things that should only be in Network Admin.
469
		 *
470
		 * For now blow away everything else until a more full
471
		 * understanding of what is needed at the network level is
472
		 * available
473
		 */
474
		if ( is_multisite() ) {
475
			Jetpack_Network::init();
476
		}
477
478
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
479
480
		// Unlink user before deleting the user from .com
481
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
482
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
483
484
485
		// Alternate XML-RPC, via ?jetpack=comms
486
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] ) {
487
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
488
				define( 'XMLRPC_REQUEST', true );
489
			}
490
491
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
492
		}
493
494
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
495
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

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