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