Completed
Push — add/widget-visibility-migratio... ( 2b9941...dab2ba )
by
unknown
14:37 queued 04:53
created

class.jetpack.php (17 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
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
	);
60
61
	public $plugins_to_deactivate = array(
62
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
63
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
64
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
65
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
66
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
67
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
68
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
69
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
70
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
71
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
72
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
73
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
74
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
75
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
76
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
77
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
78
	);
79
80
	static $capability_translations = array(
81
		'administrator' => 'manage_options',
82
		'editor'        => 'edit_others_posts',
83
		'author'        => 'publish_posts',
84
		'contributor'   => 'edit_posts',
85
		'subscriber'    => 'read',
86
	);
87
88
	/**
89
	 * Map of modules that have conflicts with plugins and should not be auto-activated
90
	 * if the plugins are active.  Used by filter_default_modules
91
	 *
92
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
93
	 * change `module-slug` and add this to your plugin:
94
	 *
95
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
96
	 * function my_jetpack_get_default_modules( $modules ) {
97
	 *     return array_diff( $modules, array( 'module-slug' ) );
98
	 * }
99
	 *
100
	 * @var array
101
	 */
102
	private $conflicting_plugins = array(
103
		'comments'          => array(
104
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
105
			'Disqus'                               => 'disqus-comment-system/disqus.php',
106
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
107
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
108
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
109
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
110
		),
111
		'contact-form'      => array(
112
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
113
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
114
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
115
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
116
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
117
		),
118
		'minileven'         => array(
119
			'WPtouch'                              => 'wptouch/wptouch.php',
120
		),
121
		'latex'             => array(
122
			'LaTeX for WordPress'                  => 'latex/latex.php',
123
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
124
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
125
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
126
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
127
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
128
		),
129
		'protect'           => array(
130
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
131
			'Captcha'                              => 'captcha/captcha.php',
132
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
133
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
134
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
135
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
136
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
137
			'Security-protection'                  => 'security-protection/security-protection.php',
138
			'Login Security'                       => 'login-security/login-security.php',
139
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
140
			'Wordfence Security'                   => 'wordfence/wordfence.php',
141
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
142
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
143
		),
144
		'random-redirect'   => array(
145
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
146
		),
147
		'related-posts'     => array(
148
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
149
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
150
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
151
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
152
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
153
			'outbrain'                             => 'outbrain/outbrain.php',
154
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
155
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
156
		),
157
		'sharedaddy'        => array(
158
			'AddThis'                              => 'addthis/addthis_social_widget.php',
159
			'Add To Any'                           => 'add-to-any/add-to-any.php',
160
			'ShareThis'                            => 'share-this/sharethis.php',
161
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
162
		),
163
		'seo-tools' => array(
164
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
165
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
166
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
167
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
168
		),
169
		'verification-tools' => array(
170
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
171
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
172
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
173
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
174
		),
175
		'widget-visibility' => array(
176
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
177
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
178
		),
179
		'sitemaps' => array(
180
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
181
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
182
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
183
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
184
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
185
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
186
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
187
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
188
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
189
			'Sitemap'                              => 'sitemap/sitemap.php',
190
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
191
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
192
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
193
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
194
		),
195
	);
196
197
	/**
198
	 * Plugins for which we turn off our Facebook OG Tags implementation.
199
	 *
200
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
201
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
202
	 *
203
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
204
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
205
	 */
206
	private $open_graph_conflicting_plugins = array(
207
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
208
		                                                         // 2 Click Social Media Buttons
209
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
210
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
211
		'autodescription/autodescription.php',                   // The SEO Framework
212
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
213
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
214
		                                                         // Open Graph Meta Tags by Heateor
215
		'facebook/facebook.php',                                 // Facebook (official plugin)
216
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
217
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
218
		                                                         // Facebook Featured Image & OG Meta Tags
219
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
220
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
221
		                                                         // Facebook Open Graph Meta Tags for WordPress
222
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
223
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
224
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
225
		                                                         // Fedmich's Facebook Open Graph Meta
226
		'header-footer/plugin.php',                              // Header and Footer
227
		'network-publisher/networkpub.php',                      // Network Publisher
228
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
229
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
230
		                                                         // NextScripts SNAP
231
		'og-tags/og-tags.php',                                   // OG Tags
232
		'opengraph/opengraph.php',                               // Open Graph
233
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
234
		                                                         // Open Graph Protocol Framework
235
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
236
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
237
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
238
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
239
		'sharepress/sharepress.php',                             // SharePress
240
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
241
		'social-discussions/social-discussions.php',             // Social Discussions
242
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
243
		'socialize/socialize.php',                               // Socialize
244
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
245
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
246
		                                                         // Tweet, Like, Google +1 and Share
247
		'wordbooker/wordbooker.php',                             // Wordbooker
248
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
249
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
250
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
251
		                                                         // WP Facebook Like Send & Open Graph Meta
252
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
253
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
254
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
255
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
256
	);
257
258
	/**
259
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
260
	 */
261
	private $twitter_cards_conflicting_plugins = array(
262
	//	'twitter/twitter.php',                       // The official one handles this on its own.
263
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
264
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
265
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
266
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
267
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
268
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
269
		'twitter-cards/twitter-cards.php',           // Twitter Cards
270
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
271
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
272
	);
273
274
	/**
275
	 * Message to display in admin_notice
276
	 * @var string
277
	 */
278
	public $message = '';
279
280
	/**
281
	 * Error to display in admin_notice
282
	 * @var string
283
	 */
284
	public $error = '';
285
286
	/**
287
	 * Modules that need more privacy description.
288
	 * @var string
289
	 */
290
	public $privacy_checks = '';
291
292
	/**
293
	 * Stats to record once the page loads
294
	 *
295
	 * @var array
296
	 */
297
	public $stats = array();
298
299
	/**
300
	 * Jetpack_Sync object
301
	 */
302
	public $sync;
303
304
	/**
305
	 * Verified data for JSON authorization request
306
	 */
307
	public $json_api_authorization_request = array();
308
309
	/**
310
	 * Holds the singleton instance of this class
311
	 * @since 2.3.3
312
	 * @var Jetpack
313
	 */
314
	static $instance = false;
315
316
	/**
317
	 * Singleton
318
	 * @static
319
	 */
320
	public static function init() {
321
		if ( ! self::$instance ) {
322
			self::$instance = new Jetpack;
323
324
			self::$instance->plugin_upgrade();
325
		}
326
327
		return self::$instance;
328
	}
329
330
	/**
331
	 * Must never be called statically
332
	 */
333
	function plugin_upgrade() {
334
		if ( Jetpack::is_active() ) {
335
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
336
			if ( JETPACK__VERSION != $version ) {
337
338
				// Check which active modules actually exist and remove others from active_modules list
339
				$unfiltered_modules = Jetpack::get_active_modules();
340
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
341
				if ( array_diff( $unfiltered_modules, $modules ) ) {
342
					Jetpack::update_active_modules( $modules );
343
				}
344
345
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
346
347
				// Upgrade to 4.3.0
348
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
349
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
350
				}
351
352
				Jetpack::maybe_set_version_option();
353
354
				add_action( 'wp_loaded', array( __CLASS__, 'migrate_widget_visibility' ) );
355
			}
356
		}
357
	}
358
359
	/**
360
	 * Upgrade routine to go through all widgets and move the Post Type
361
	 * setting to its newer location.
362
	 *
363
	 * @since 4.7.1
364
	 *
365
	 */
366
	static function migrate_widget_visibility() {
367
		global $wp_registered_widgets;
368
369
		$sidebars_widgets = get_option( 'sidebars_widgets' );
370
371
		// Going through all sidebars and through inactive and orphaned widgets
372
		foreach ( $sidebars_widgets as $s => $sidebar ) {
373
			if ( ! is_array( $sidebar ) ) {
374
				continue;
375
			}
376
377
			foreach ( $sidebar as $w => $widget ) {
378
				// $widget is the id of the widget
379
				if ( empty( $wp_registered_widgets[$widget] ) ) {
380
					continue;
381
				}
382
383
				$opts = $wp_registered_widgets[$widget];
384
				$instances = get_option( $opts['callback'][0]->option_name );
385
386
				// Going through each instance of the widget
387
				foreach( $instances as $number => $instance ) {
388
					if (
389
						! is_array( $instance ) ||
390
						empty( $instance['conditions'] ) ||
391
						empty( $instance['conditions']['rules'] )
392
					) {
393
						continue;
394
					}
395
396
					// Going through all visibility rules
397
					foreach( $instance['conditions']['rules'] as $index => $rule ) {
398
399
						// We only need Post Type rules
400
						if ( 'post_type' !== $rule['major'] ) {
401
							continue;
402
						}
403
404
						$post_type = false;
405
406
						// Post type archive rule
407 View Code Duplication
						if ( 0 === strpos( $rule['minor'], 'post_type_archive' ) ) {
408
							$post_type = substr(
409
								$rule['minor'], strlen( 'post_type_archive' ) + 1
410
							);
411
						}
412
413
						// Post type archive rule
414 View Code Duplication
						if ( 0 === strpos( $rule['minor'], 'post_type' ) ) {
415
							$post_type = substr(
416
								$rule['minor'], strlen( 'post_type' ) + 1
417
							);
418
						}
419
420
						if ( $post_type ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $post_type of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
421
							$rule['minor'] = 'post_type-' . $post_type;
422
							$rule['major'] = 'page';
423
424
							$instances[ $number ]['conditions']['rules'][ $index ] = $rule;
425
						}
426
					}
427
				}
428
429
				update_option( $opts['callback'][0]->option_name, $instances );
430
			}
431
		}
432
433
		$sidebars_widgets = get_option( 'sidebars_widgets' );
0 ignored issues
show
$sidebars_widgets is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
434
	}
435
436
	static function activate_manage( ) {
437
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
438
			self::activate_module( 'manage', false, false );
439
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
440
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
441
		}
442
	}
443
444
	static function update_active_modules( $modules ) {
445
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
446
447
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
448
449
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
450
			$new_active_modules = array_diff( $modules, $current_modules );
451
			foreach( $new_active_modules as $module ) {
452
				/**
453
				 * Fires when a specific module is activated.
454
				 *
455
				 * @since 1.9.0
456
				 *
457
				 * @param string $module Module slug.
458
				 * @param boolean $success whether the module was activated. @since 4.2
459
				 */
460
				do_action( 'jetpack_activate_module', $module, $success );
461
462
				/**
463
				 * Fires when a module is activated.
464
				 * The dynamic part of the filter, $module, is the module slug.
465
				 *
466
				 * @since 1.9.0
467
				 *
468
				 * @param string $module Module slug.
469
				 */
470
				do_action( "jetpack_activate_module_$module", $module );
471
			}
472
473
			$new_deactive_modules = array_diff( $current_modules, $modules );
474
			foreach( $new_deactive_modules as $module ) {
475
				/**
476
				 * Fired after a module has been deactivated.
477
				 *
478
				 * @since 4.2.0
479
				 *
480
				 * @param string $module Module slug.
481
				 * @param boolean $success whether the module was deactivated.
482
				 */
483
				do_action( 'jetpack_deactivate_module', $module, $success );
484
				/**
485
				 * Fires when a module is deactivated.
486
				 * The dynamic part of the filter, $module, is the module slug.
487
				 *
488
				 * @since 1.9.0
489
				 *
490
				 * @param string $module Module slug.
491
				 */
492
				do_action( "jetpack_deactivate_module_$module", $module );
493
			}
494
		}
495
496
		return $success;
497
	}
498
499
	static function delete_active_modules() {
500
		self::update_active_modules( array() );
501
	}
502
503
	/**
504
	 * Constructor.  Initializes WordPress hooks
505
	 */
506
	private function __construct() {
507
		/*
508
		 * Check for and alert any deprecated hooks
509
		 */
510
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
511
512
		/*
513
		 * Load things that should only be in Network Admin.
514
		 *
515
		 * For now blow away everything else until a more full
516
		 * understanding of what is needed at the network level is
517
		 * available
518
		 */
519
		if( is_multisite() ) {
520
			Jetpack_Network::init();
521
		}
522
523
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
524
525
		// Unlink user before deleting the user from .com
526
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
527
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
528
529
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
530
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
531
532
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
533
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
534
535
			$this->require_jetpack_authentication();
536
537
			if ( Jetpack::is_active() ) {
538
				// Hack to preserve $HTTP_RAW_POST_DATA
539
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
540
541
				$signed = $this->verify_xml_rpc_signature();
542
				if ( $signed && ! is_wp_error( $signed ) ) {
543
					// The actual API methods.
544
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
545
				} else {
546
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
547
					// active Jetpack connection, so that additional users can link their account.
548
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
549
				}
550
			} else {
551
				// The bootstrap API methods.
552
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
553
			}
554
555
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
556
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
557
		} elseif (
558
			is_admin() &&
559
			isset( $_POST['action'] ) && (
560
				'jetpack_upload_file' == $_POST['action'] ||
561
				'jetpack_update_file' == $_POST['action']
562
			)
563
		) {
564
			$this->require_jetpack_authentication();
565
			$this->add_remote_request_handlers();
566
		} else {
567
			if ( Jetpack::is_active() ) {
568
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
569
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
570
			}
571
		}
572
573
		if ( Jetpack::is_active() ) {
574
			Jetpack_Heartbeat::init();
575
		}
576
577
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
578
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
579
580
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
581
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
582
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
583
		}
584
585
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
586
587
		add_action( 'admin_init', array( $this, 'admin_init' ) );
588
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
589
590
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
591
592
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
593
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
594
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
595
596
		// returns HTTPS support status
597
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
598
599
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
600
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
601
602
		// JITM AJAX callback function
603
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
604
605
		// Universal ajax callback for all tracking events triggered via js
606
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
607
608
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
609
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
610
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
611
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
612
613
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
614
615
		/**
616
		 * These actions run checks to load additional files.
617
		 * They check for external files or plugins, so they need to run as late as possible.
618
		 */
619
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
620
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
621
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
622
623
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
624
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
625
626
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
627
628
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
629
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
630
631
		// A filter to control all just in time messages
632
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
633
634
		// Update the Jetpack plan from API on heartbeats
635
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
636
637
		/**
638
		 * This is the hack to concatinate all css files into one.
639
		 * For description and reasoning see the implode_frontend_css method
640
		 *
641
		 * Super late priority so we catch all the registered styles
642
		 */
643
		if( !is_admin() ) {
644
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
645
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
646
		}
647
	}
648
649
	function jetpack_admin_ajax_tracks_callback() {
650
		// Check for nonce
651
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
652
			wp_die( 'Permissions check failed.' );
653
		}
654
655
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
656
			wp_die( 'No valid event name or type.' );
657
		}
658
659
		$tracks_data = array();
660
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
661
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
662
		}
663
664
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
665
		wp_send_json_success();
666
		wp_die();
667
	}
668
669
	/**
670
	 * The callback for the JITM ajax requests.
671
	 */
672
	function jetpack_jitm_ajax_callback() {
673
		// Check for nonce
674
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
675
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
676
		}
677
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
678
			$module_slug = $_REQUEST['jitmModule'];
679
			Jetpack::log( 'activate', $module_slug );
680
			Jetpack::activate_module( $module_slug, false, false );
681
			Jetpack::state( 'message', 'no_message' );
682
683
			//A Jetpack module is being activated through a JITM, track it
684
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
685
			$this->do_stats( 'server_side' );
686
687
			wp_send_json_success();
688
		}
689
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
690
			// get the hide_jitm options array
691
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
692
			$module_slug = $_REQUEST['jitmModule'];
693
694
			if( ! $jetpack_hide_jitm ) {
695
				$jetpack_hide_jitm = array(
696
					$module_slug => 'hide'
697
				);
698
			} else {
699
				$jetpack_hide_jitm[$module_slug] = 'hide';
700
			}
701
702
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
703
704
			//jitm is being dismissed forever, track it
705
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
706
			$this->do_stats( 'server_side' );
707
708
			wp_send_json_success();
709
		}
710 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
711
			$module_slug = $_REQUEST['jitmModule'];
712
713
			// User went to WordPress.com, track this
714
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
715
			$this->do_stats( 'server_side' );
716
717
			wp_send_json_success();
718
		}
719 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
720
			$track = $_REQUEST['jitmModule'];
721
722
			// User is viewing JITM, track it.
723
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
724
			$this->do_stats( 'server_side' );
725
726
			wp_send_json_success();
727
		}
728
	}
729
730
	/**
731
	 * If there are any stats that need to be pushed, but haven't been, push them now.
732
	 */
733
	function __destruct() {
734
		if ( ! empty( $this->stats ) ) {
735
			$this->do_stats( 'server_side' );
736
		}
737
	}
738
739
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
740
		switch( $cap ) {
741
			case 'jetpack_connect' :
742
			case 'jetpack_reconnect' :
743
				if ( Jetpack::is_development_mode() ) {
744
					$caps = array( 'do_not_allow' );
745
					break;
746
				}
747
				/**
748
				 * Pass through. If it's not development mode, these should match disconnect.
749
				 * Let users disconnect if it's development mode, just in case things glitch.
750
				 */
751
			case 'jetpack_disconnect' :
752
				/**
753
				 * In multisite, can individual site admins manage their own connection?
754
				 *
755
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
756
				 */
757
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
758
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
759
						/**
760
						 * We need to update the option name -- it's terribly unclear which
761
						 * direction the override goes.
762
						 *
763
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
764
						 */
765
						$caps = array( 'do_not_allow' );
766
						break;
767
					}
768
				}
769
770
				$caps = array( 'manage_options' );
771
				break;
772
			case 'jetpack_manage_modules' :
773
			case 'jetpack_activate_modules' :
774
			case 'jetpack_deactivate_modules' :
775
				$caps = array( 'manage_options' );
776
				break;
777
			case 'jetpack_configure_modules' :
778
				$caps = array( 'manage_options' );
779
				break;
780
			case 'jetpack_network_admin_page':
781
			case 'jetpack_network_settings_page':
782
				$caps = array( 'manage_network_plugins' );
783
				break;
784
			case 'jetpack_network_sites_page':
785
				$caps = array( 'manage_sites' );
786
				break;
787
			case 'jetpack_admin_page' :
788
				if ( Jetpack::is_development_mode() ) {
789
					$caps = array( 'manage_options' );
790
					break;
791
				} else {
792
					$caps = array( 'read' );
793
				}
794
				break;
795
			case 'jetpack_connect_user' :
796
				if ( Jetpack::is_development_mode() ) {
797
					$caps = array( 'do_not_allow' );
798
					break;
799
				}
800
				$caps = array( 'read' );
801
				break;
802
		}
803
		return $caps;
804
	}
805
806
	function require_jetpack_authentication() {
807
		// Don't let anyone authenticate
808
		$_COOKIE = array();
809
		remove_all_filters( 'authenticate' );
810
		remove_all_actions( 'wp_login_failed' );
811
812
		if ( Jetpack::is_active() ) {
813
			// Allow Jetpack authentication
814
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
815
		}
816
	}
817
818
	/**
819
	 * Load language files
820
	 * @action plugins_loaded
821
	 */
822
	public static function plugin_textdomain() {
823
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
824
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
825
	}
826
827
	/**
828
	 * Register assets for use in various modules and the Jetpack admin page.
829
	 *
830
	 * @uses wp_script_is, wp_register_script, plugins_url
831
	 * @action wp_loaded
832
	 * @return null
833
	 */
834
	public function register_assets() {
835
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
836
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
837
		}
838
839 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
840
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
841
		}
842
843 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
844
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
845
		}
846
847 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
848
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
849
		}
850
851
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
852
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
853
854
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
855
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
856
			if ( ! is_numeric( $fb_app_id ) ) {
857
				$fb_app_id = '';
858
			}
859
			wp_localize_script(
860
				'jetpack-facebook-embed',
861
				'jpfbembed',
862
				array(
863
					'appid' => $fb_app_id,
864
					'locale' => $this->get_locale(),
865
				)
866
			);
867
		}
868
869
		/**
870
		 * As jetpack_register_genericons is by default fired off a hook,
871
		 * the hook may have already fired by this point.
872
		 * So, let's just trigger it manually.
873
		 */
874
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
875
		jetpack_register_genericons();
876
877
		/**
878
		 * Register the social logos
879
		 */
880
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
881
		jetpack_register_social_logos();
882
883 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
884
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
885
	}
886
887
	/**
888
	 * Guess locale from language code.
889
	 *
890
	 * @param string $lang Language code.
891
	 * @return string|bool
892
	 */
893 View Code Duplication
	function guess_locale_from_lang( $lang ) {
894
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
895
			return 'en_US';
896
		}
897
898
		if ( ! class_exists( 'GP_Locales' ) ) {
899
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
900
				return false;
901
			}
902
903
			require JETPACK__GLOTPRESS_LOCALES_PATH;
904
		}
905
906
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
907
			// WP.com: get_locale() returns 'it'
908
			$locale = GP_Locales::by_slug( $lang );
909
		} else {
910
			// Jetpack: get_locale() returns 'it_IT';
911
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
912
		}
913
914
		if ( ! $locale ) {
915
			return false;
916
		}
917
918
		if ( empty( $locale->facebook_locale ) ) {
919
			if ( empty( $locale->wp_locale ) ) {
920
				return false;
921
			} else {
922
				// Facebook SDK is smart enough to fall back to en_US if a
923
				// locale isn't supported. Since supported Facebook locales
924
				// can fall out of sync, we'll attempt to use the known
925
				// wp_locale value and rely on said fallback.
926
				return $locale->wp_locale;
927
			}
928
		}
929
930
		return $locale->facebook_locale;
931
	}
932
933
	/**
934
	 * Get the locale.
935
	 *
936
	 * @return string|bool
937
	 */
938
	function get_locale() {
939
		$locale = $this->guess_locale_from_lang( get_locale() );
940
941
		if ( ! $locale ) {
942
			$locale = 'en_US';
943
		}
944
945
		return $locale;
946
	}
947
948
	/**
949
	 * Device Pixels support
950
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
951
	 */
952
	function devicepx() {
953
		if ( Jetpack::is_active() ) {
954
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
955
		}
956
	}
957
958
	/**
959
	 * Return the network_site_url so that .com knows what network this site is a part of.
960
	 * @param  bool $option
961
	 * @return string
962
	 */
963
	public function jetpack_main_network_site_option( $option ) {
964
		return network_site_url();
965
	}
966
	/**
967
	 * Network Name.
968
	 */
969
	static function network_name( $option = null ) {
970
		global $current_site;
971
		return $current_site->site_name;
972
	}
973
	/**
974
	 * Does the network allow new user and site registrations.
975
	 * @return string
976
	 */
977
	static function network_allow_new_registrations( $option = null ) {
978
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
979
	}
980
	/**
981
	 * Does the network allow admins to add new users.
982
	 * @return boolian
983
	 */
984
	static function network_add_new_users( $option = null ) {
985
		return (bool) get_site_option( 'add_new_users' );
986
	}
987
	/**
988
	 * File upload psace left per site in MB.
989
	 *  -1 means NO LIMIT.
990
	 * @return number
991
	 */
992
	static function network_site_upload_space( $option = null ) {
993
		// value in MB
994
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
995
	}
996
997
	/**
998
	 * Network allowed file types.
999
	 * @return string
1000
	 */
1001
	static function network_upload_file_types( $option = null ) {
1002
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1003
	}
1004
1005
	/**
1006
	 * Maximum file upload size set by the network.
1007
	 * @return number
1008
	 */
1009
	static function network_max_upload_file_size( $option = null ) {
1010
		// value in KB
1011
		return get_site_option( 'fileupload_maxk', 300 );
1012
	}
1013
1014
	/**
1015
	 * Lets us know if a site allows admins to manage the network.
1016
	 * @return array
1017
	 */
1018
	static function network_enable_administration_menus( $option = null ) {
1019
		return get_site_option( 'menu_items' );
1020
	}
1021
1022
	/**
1023
	 * If a user has been promoted to or demoted from admin, we need to clear the
1024
	 * jetpack_other_linked_admins transient.
1025
	 *
1026
	 * @since 4.3.2
1027
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1028
	 *
1029
	 * @param int    $user_id   The user ID whose role changed.
1030
	 * @param string $role      The new role.
1031
	 * @param array  $old_roles An array of the user's previous roles.
1032
	 */
1033
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1034
		if ( 'administrator' == $role
1035
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1036
			|| is_null( $old_roles )
1037
		) {
1038
			delete_transient( 'jetpack_other_linked_admins' );
1039
		}
1040
	}
1041
1042
	/**
1043
	 * Checks to see if there are any other users available to become primary
1044
	 * Users must both:
1045
	 * - Be linked to wpcom
1046
	 * - Be an admin
1047
	 *
1048
	 * @return mixed False if no other users are linked, Int if there are.
1049
	 */
1050
	static function get_other_linked_admins() {
1051
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1052
1053
		if ( false === $other_linked_users ) {
1054
			$admins = get_users( array( 'role' => 'administrator' ) );
1055
			if ( count( $admins ) > 1 ) {
1056
				$available = array();
1057
				foreach ( $admins as $admin ) {
1058
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1059
						$available[] = $admin->ID;
1060
					}
1061
				}
1062
1063
				$count_connected_admins = count( $available );
1064
				if ( count( $available ) > 1 ) {
1065
					$other_linked_users = $count_connected_admins;
1066
				} else {
1067
					$other_linked_users = 0;
1068
				}
1069
			} else {
1070
				$other_linked_users = 0;
1071
			}
1072
1073
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1074
		}
1075
1076
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1077
	}
1078
1079
	/**
1080
	 * Return whether we are dealing with a multi network setup or not.
1081
	 * The reason we are type casting this is because we want to avoid the situation where
1082
	 * the result is false since when is_main_network_option return false it cases
1083
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1084
	 * database which could be set to anything as opposed to what this function returns.
1085
	 * @param  bool  $option
1086
	 *
1087
	 * @return boolean
1088
	 */
1089
	public function is_main_network_option( $option ) {
1090
		// return '1' or ''
1091
		return (string) (bool) Jetpack::is_multi_network();
1092
	}
1093
1094
	/**
1095
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1096
	 *
1097
	 * @param  string  $option
1098
	 * @return boolean
1099
	 */
1100
	public function is_multisite( $option ) {
1101
		return (string) (bool) is_multisite();
1102
	}
1103
1104
	/**
1105
	 * Implemented since there is no core is multi network function
1106
	 * Right now there is no way to tell if we which network is the dominant network on the system
1107
	 *
1108
	 * @since  3.3
1109
	 * @return boolean
1110
	 */
1111
	public static function is_multi_network() {
1112
		global  $wpdb;
1113
1114
		// if we don't have a multi site setup no need to do any more
1115
		if ( ! is_multisite() ) {
1116
			return false;
1117
		}
1118
1119
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1120
		if ( $num_sites > 1 ) {
1121
			return true;
1122
		} else {
1123
			return false;
1124
		}
1125
	}
1126
1127
	/**
1128
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1129
	 * @return null
1130
	 */
1131
	function update_jetpack_main_network_site_option() {
1132
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1133
	}
1134
	/**
1135
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1136
	 *
1137
	 */
1138
	function update_jetpack_network_settings() {
1139
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1140
		// Only sync this info for the main network site.
1141
	}
1142
1143
	/**
1144
	 * Get back if the current site is single user site.
1145
	 *
1146
	 * @return bool
1147
	 */
1148
	public static function is_single_user_site() {
1149
		global $wpdb;
1150
1151 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1152
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1153
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1154
		}
1155
		return 1 === (int) $some_users;
1156
	}
1157
1158
	/**
1159
	 * Returns true if the site has file write access false otherwise.
1160
	 * @return string ( '1' | '0' )
1161
	 **/
1162
	public static function file_system_write_access() {
1163
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1164
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1165
		}
1166
1167
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1168
1169
		$filesystem_method = get_filesystem_method();
1170
		if ( $filesystem_method === 'direct' ) {
1171
			return 1;
1172
		}
1173
1174
		ob_start();
1175
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1176
		ob_end_clean();
1177
		if ( $filesystem_credentials_are_stored ) {
1178
			return 1;
1179
		}
1180
		return 0;
1181
	}
1182
1183
	/**
1184
	 * Finds out if a site is using a version control system.
1185
	 * @return string ( '1' | '0' )
1186
	 **/
1187
	public static function is_version_controlled() {
1188
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1189
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1190
	}
1191
1192
	/**
1193
	 * Determines whether the current theme supports featured images or not.
1194
	 * @return string ( '1' | '0' )
1195
	 */
1196
	public static function featured_images_enabled() {
1197
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1198
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1199
	}
1200
1201
	/**
1202
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1203
	 *
1204
	 * @deprecated 4.7 use get_avatar_url instead.
1205
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1206
	 * @param int $size Size of the avatar image
1207
	 * @param string $default URL to a default image to use if no avatar is available
1208
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1209
	 *
1210
	 * @return array
1211
	 */
1212
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1213
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1214
		return get_avatar_url( $id_or_email, array(
1215
			'size' => $size,
1216
			'default' => $default,
1217
			'force_default' => $force_display,
1218
		) );
1219
	}
1220
1221
	/**
1222
	 * jetpack_updates is saved in the following schema:
1223
	 *
1224
	 * array (
1225
	 *      'plugins'                       => (int) Number of plugin updates available.
1226
	 *      'themes'                        => (int) Number of theme updates available.
1227
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1228
	 *      'translations'                  => (int) Number of translation updates available.
1229
	 *      'total'                         => (int) Total of all available updates.
1230
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1231
	 * )
1232
	 * @return array
1233
	 */
1234
	public static function get_updates() {
1235
		$update_data = wp_get_update_data();
1236
1237
		// Stores the individual update counts as well as the total count.
1238
		if ( isset( $update_data['counts'] ) ) {
1239
			$updates = $update_data['counts'];
1240
		}
1241
1242
		// If we need to update WordPress core, let's find the latest version number.
1243 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1244
			$cur = get_preferred_from_update_core();
1245
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1246
				$updates['wp_update_version'] = $cur->current;
1247
			}
1248
		}
1249
		return isset( $updates ) ? $updates : array();
1250
	}
1251
1252
	public static function get_update_details() {
1253
		$update_details = array(
1254
			'update_core' => get_site_transient( 'update_core' ),
1255
			'update_plugins' => get_site_transient( 'update_plugins' ),
1256
			'update_themes' => get_site_transient( 'update_themes' ),
1257
		);
1258
		return $update_details;
1259
	}
1260
1261
	public static function refresh_update_data() {
1262
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1263
1264
	}
1265
1266
	public static function refresh_theme_data() {
1267
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1268
	}
1269
1270
	/**
1271
	 * Is Jetpack active?
1272
	 */
1273
	public static function is_active() {
1274
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1275
	}
1276
1277
	/**
1278
	 * Make an API call to WordPress.com for plan status
1279
	 *
1280
	 * @uses Jetpack_Options::get_option()
1281
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1282
	 * @uses update_option()
1283
	 *
1284
	 * @access public
1285
	 * @static
1286
	 *
1287
	 * @return bool True if plan is updated, false if no update
1288
	 */
1289
	public static function refresh_active_plan_from_wpcom() {
1290
		// Make the API request
1291
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1292
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1293
1294
		// Bail if there was an error or malformed response
1295
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1296
			return false;
1297
		}
1298
1299
		// Decode the results
1300
		$results = json_decode( $response['body'], true );
1301
1302
		// Bail if there were no results or plan details returned
1303
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1304
			return false;
1305
		}
1306
1307
		// Store the option and return true if updated
1308
		return update_option( 'jetpack_active_plan', $results['plan'] );
1309
	}
1310
1311
	/**
1312
	 * Get the plan that this Jetpack site is currently using
1313
	 *
1314
	 * @uses get_option()
1315
	 *
1316
	 * @access public
1317
	 * @static
1318
	 *
1319
	 * @return array Active Jetpack plan details
1320
	 */
1321
	public static function get_active_plan() {
1322
		$plan = get_option( 'jetpack_active_plan' );
1323
1324
		// Set the default options
1325
		if ( ! $plan ) {
1326
			$plan = array(
1327
				'product_slug' => 'jetpack_free',
1328
				'supports'     => array(),
1329
				'class'        => 'free',
1330
			);
1331
		}
1332
1333
		// Define what paid modules are supported by personal plans
1334
		$personal_plans = array(
1335
			'jetpack_personal',
1336
			'jetpack_personal_monthly',
1337
		);
1338
1339
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1340
			$plan['supports'] = array(
1341
				'akismet',
1342
			);
1343
			$plan['class'] = 'personal';
1344
		}
1345
1346
		// Define what paid modules are supported by premium plans
1347
		$premium_plans = array(
1348
			'jetpack_premium',
1349
			'jetpack_premium_monthly',
1350
		);
1351
1352 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1353
			$plan['supports'] = array(
1354
				'videopress',
1355
				'akismet',
1356
				'vaultpress',
1357
				'wordads',
1358
			);
1359
			$plan['class'] = 'premium';
1360
		}
1361
1362
		// Define what paid modules are supported by professional plans
1363
		$business_plans = array(
1364
			'jetpack_business',
1365
			'jetpack_business_monthly',
1366
		);
1367
1368 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1369
			$plan['supports'] = array(
1370
				'videopress',
1371
				'akismet',
1372
				'vaultpress',
1373
				'seo-tools',
1374
				'google-analytics',
1375
				'wordads',
1376
			);
1377
			$plan['class'] = 'business';
1378
		}
1379
1380
		// Make sure we have an array here in the event database data is stale
1381
		if ( ! isset( $plan['supports'] ) ) {
1382
			$plan['supports'] = array();
1383
		}
1384
1385
		return $plan;
1386
	}
1387
1388
	/**
1389
	 * Determine whether the active plan supports a particular feature
1390
	 *
1391
	 * @uses Jetpack::get_active_plan()
1392
	 *
1393
	 * @access public
1394
	 * @static
1395
	 *
1396
	 * @return bool True if plan supports feature, false if not
1397
	 */
1398
	public static function active_plan_supports( $feature ) {
1399
		$plan = Jetpack::get_active_plan();
1400
1401
		if ( in_array( $feature, $plan['supports'] ) ) {
1402
			return true;
1403
		}
1404
1405
		return false;
1406
	}
1407
1408
	/**
1409
	 * Is Jetpack in development (offline) mode?
1410
	 */
1411
	public static function is_development_mode() {
1412
		$development_mode = false;
1413
1414
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1415
			$development_mode = JETPACK_DEV_DEBUG;
1416
		} elseif ( $site_url = site_url() ) {
1417
			$development_mode = false === strpos( $site_url, '.' );
1418
		}
1419
1420
		/**
1421
		 * Filters Jetpack's development mode.
1422
		 *
1423
		 * @see https://jetpack.com/support/development-mode/
1424
		 *
1425
		 * @since 2.2.1
1426
		 *
1427
		 * @param bool $development_mode Is Jetpack's development mode active.
1428
		 */
1429
		return apply_filters( 'jetpack_development_mode', $development_mode );
1430
	}
1431
1432
	/**
1433
	* Get Jetpack development mode notice text and notice class.
1434
	*
1435
	* Mirrors the checks made in Jetpack::is_development_mode
1436
	*
1437
	*/
1438
	public static function show_development_mode_notice() {
1439
		if ( Jetpack::is_development_mode() ) {
1440
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1441
				$notice = sprintf(
1442
					/* translators: %s is a URL */
1443
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1444
					'https://jetpack.com/support/development-mode/'
1445
				);
1446
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1447
				$notice = sprintf(
1448
					/* translators: %s is a URL */
1449
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1450
					'https://jetpack.com/support/development-mode/'
1451
				);
1452
			} else {
1453
				$notice = sprintf(
1454
					/* translators: %s is a URL */
1455
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1456
					'https://jetpack.com/support/development-mode/'
1457
				);
1458
			}
1459
1460
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1461
		}
1462
1463
		// Throw up a notice if using a development version and as for feedback.
1464
		if ( Jetpack::is_development_version() ) {
1465
			/* translators: %s is a URL */
1466
			$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/' );
1467
1468
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1469
		}
1470
		// Throw up a notice if using staging mode
1471
		if ( Jetpack::is_staging_site() ) {
1472
			/* translators: %s is a URL */
1473
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1474
1475
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1476
		}
1477
	}
1478
1479
	/**
1480
	 * Whether Jetpack's version maps to a public release, or a development version.
1481
	 */
1482
	public static function is_development_version() {
1483
		/**
1484
		 * Allows filtering whether this is a development version of Jetpack.
1485
		 *
1486
		 * This filter is especially useful for tests.
1487
		 *
1488
		 * @since 4.3.0
1489
		 *
1490
		 * @param bool $development_version Is this a develoment version of Jetpack?
1491
		 */
1492
		return (bool) apply_filters(
1493
			'jetpack_development_version',
1494
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1495
		);
1496
	}
1497
1498
	/**
1499
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1500
	 */
1501
	public static function is_user_connected( $user_id = false ) {
1502
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1503
		if ( ! $user_id ) {
1504
			return false;
1505
		}
1506
1507
		return (bool) Jetpack_Data::get_access_token( $user_id );
1508
	}
1509
1510
	/**
1511
	 * Get the wpcom user data of the current|specified connected user.
1512
	 */
1513
	public static function get_connected_user_data( $user_id = null ) {
1514
		if ( ! $user_id ) {
1515
			$user_id = get_current_user_id();
1516
		}
1517
1518
		$transient_key = "jetpack_connected_user_data_$user_id";
1519
1520
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1521
			return $cached_user_data;
1522
		}
1523
1524
		Jetpack::load_xml_rpc_client();
1525
		$xml = new Jetpack_IXR_Client( array(
1526
			'user_id' => $user_id,
1527
		) );
1528
		$xml->query( 'wpcom.getUser' );
1529
		if ( ! $xml->isError() ) {
1530
			$user_data = $xml->getResponse();
1531
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1532
			return $user_data;
1533
		}
1534
1535
		return false;
1536
	}
1537
1538
	/**
1539
	 * Get the wpcom email of the current|specified connected user.
1540
	 */
1541 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1542
		if ( ! $user_id ) {
1543
			$user_id = get_current_user_id();
1544
		}
1545
		Jetpack::load_xml_rpc_client();
1546
		$xml = new Jetpack_IXR_Client( array(
1547
			'user_id' => $user_id,
1548
		) );
1549
		$xml->query( 'wpcom.getUserEmail' );
1550
		if ( ! $xml->isError() ) {
1551
			return $xml->getResponse();
1552
		}
1553
		return false;
1554
	}
1555
1556
	/**
1557
	 * Get the wpcom email of the master user.
1558
	 */
1559
	public static function get_master_user_email() {
1560
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1561
		if ( $master_user_id ) {
1562
			return self::get_connected_user_email( $master_user_id );
1563
		}
1564
		return '';
1565
	}
1566
1567
	function current_user_is_connection_owner() {
1568
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1569
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1570
	}
1571
1572
	/**
1573
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1574
	 */
1575
	function extra_oembed_providers() {
1576
		// Cloudup: https://dev.cloudup.com/#oembed
1577
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1578
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1579
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1580
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1581
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1582
	}
1583
1584
	/**
1585
	 * Synchronize connected user role changes
1586
	 */
1587
	function user_role_change( $user_id ) {
1588
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1589
		Jetpack_Sync_Users::user_role_change( $user_id );
1590
	}
1591
1592
	/**
1593
	 * Loads the currently active modules.
1594
	 */
1595
	public static function load_modules() {
1596
		if ( ! self::is_active() && !self::is_development_mode() ) {
1597
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1598
				return;
1599
			}
1600
		}
1601
1602
		$version = Jetpack_Options::get_option( 'version' );
1603 View Code Duplication
		if ( ! $version ) {
1604
			$version = $old_version = JETPACK__VERSION . ':' . time();
1605
			/** This action is documented in class.jetpack.php */
1606
			do_action( 'updating_jetpack_version', $version, false );
1607
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1608
		}
1609
		list( $version ) = explode( ':', $version );
1610
1611
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1612
1613
		$modules_data = array();
1614
1615
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1616
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1617
			$updated_modules = array();
1618
			foreach ( $modules as $module ) {
1619
				$modules_data[ $module ] = Jetpack::get_module( $module );
1620
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1621
					continue;
1622
				}
1623
1624
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1625
					continue;
1626
				}
1627
1628
				$updated_modules[] = $module;
1629
			}
1630
1631
			$modules = array_diff( $modules, $updated_modules );
1632
		}
1633
1634
		$is_development_mode = Jetpack::is_development_mode();
1635
1636
		foreach ( $modules as $index => $module ) {
1637
			// If we're in dev mode, disable modules requiring a connection
1638
			if ( $is_development_mode ) {
1639
				// Prime the pump if we need to
1640
				if ( empty( $modules_data[ $module ] ) ) {
1641
					$modules_data[ $module ] = Jetpack::get_module( $module );
1642
				}
1643
				// If the module requires a connection, but we're in local mode, don't include it.
1644
				if ( $modules_data[ $module ]['requires_connection'] ) {
1645
					continue;
1646
				}
1647
			}
1648
1649
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1650
				continue;
1651
			}
1652
1653
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1654
				unset( $modules[ $index ] );
1655
				self::update_active_modules( array_values( $modules ) );
1656
				continue;
1657
			}
1658
1659
			/**
1660
			 * Fires when a specific module is loaded.
1661
			 * The dynamic part of the hook, $module, is the module slug.
1662
			 *
1663
			 * @since 1.1.0
1664
			 */
1665
			do_action( 'jetpack_module_loaded_' . $module );
1666
		}
1667
1668
		/**
1669
		 * Fires when all the modules are loaded.
1670
		 *
1671
		 * @since 1.1.0
1672
		 */
1673
		do_action( 'jetpack_modules_loaded' );
1674
1675
		// 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.
1676
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1677
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1678
	}
1679
1680
	/**
1681
	 * Check if Jetpack's REST API compat file should be included
1682
	 * @action plugins_loaded
1683
	 * @return null
1684
	 */
1685
	public function check_rest_api_compat() {
1686
		/**
1687
		 * Filters the list of REST API compat files to be included.
1688
		 *
1689
		 * @since 2.2.5
1690
		 *
1691
		 * @param array $args Array of REST API compat files to include.
1692
		 */
1693
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1694
1695
		if ( function_exists( 'bbpress' ) )
1696
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1697
1698
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1699
			require_once $_jetpack_rest_api_compat_include;
1700
	}
1701
1702
	/**
1703
	 * Gets all plugins currently active in values, regardless of whether they're
1704
	 * traditionally activated or network activated.
1705
	 *
1706
	 * @todo Store the result in core's object cache maybe?
1707
	 */
1708
	public static function get_active_plugins() {
1709
		$active_plugins = (array) get_option( 'active_plugins', array() );
1710
1711
		if ( is_multisite() ) {
1712
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1713
			// whereas active_plugins stores them in the values.
1714
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1715
			if ( $network_plugins ) {
1716
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1717
			}
1718
		}
1719
1720
		sort( $active_plugins );
1721
1722
		return array_unique( $active_plugins );
1723
	}
1724
1725
	/**
1726
	 * Gets and parses additional plugin data to send with the heartbeat data
1727
	 *
1728
	 * @since 3.8.1
1729
	 *
1730
	 * @return array Array of plugin data
1731
	 */
1732
	public static function get_parsed_plugin_data() {
1733
		if ( ! function_exists( 'get_plugins' ) ) {
1734
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1735
		}
1736
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1737
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1738
		$active_plugins = Jetpack::get_active_plugins();
1739
1740
		$plugins = array();
1741
		foreach ( $all_plugins as $path => $plugin_data ) {
1742
			$plugins[ $path ] = array(
1743
					'is_active' => in_array( $path, $active_plugins ),
1744
					'file'      => $path,
1745
					'name'      => $plugin_data['Name'],
1746
					'version'   => $plugin_data['Version'],
1747
					'author'    => $plugin_data['Author'],
1748
			);
1749
		}
1750
1751
		return $plugins;
1752
	}
1753
1754
	/**
1755
	 * Gets and parses theme data to send with the heartbeat data
1756
	 *
1757
	 * @since 3.8.1
1758
	 *
1759
	 * @return array Array of theme data
1760
	 */
1761
	public static function get_parsed_theme_data() {
1762
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1763
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1764
1765
		$themes = array();
1766
		foreach ( $all_themes as $slug => $theme_data ) {
1767
			$theme_headers = array();
1768
			foreach ( $header_keys as $header_key ) {
1769
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1770
			}
1771
1772
			$themes[ $slug ] = array(
1773
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1774
					'slug' => $slug,
1775
					'theme_root' => $theme_data->get_theme_root_uri(),
1776
					'parent' => $theme_data->parent(),
1777
					'headers' => $theme_headers
1778
			);
1779
		}
1780
1781
		return $themes;
1782
	}
1783
1784
	/**
1785
	 * Checks whether a specific plugin is active.
1786
	 *
1787
	 * We don't want to store these in a static variable, in case
1788
	 * there are switch_to_blog() calls involved.
1789
	 */
1790
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1791
		return in_array( $plugin, self::get_active_plugins() );
1792
	}
1793
1794
	/**
1795
	 * Check if Jetpack's Open Graph tags should be used.
1796
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1797
	 *
1798
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1799
	 * @action plugins_loaded
1800
	 * @return null
1801
	 */
1802
	public function check_open_graph() {
1803
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1804
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1805
		}
1806
1807
		$active_plugins = self::get_active_plugins();
1808
1809
		if ( ! empty( $active_plugins ) ) {
1810
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1811
				if ( in_array( $plugin, $active_plugins ) ) {
1812
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1813
					break;
1814
				}
1815
			}
1816
		}
1817
1818
		/**
1819
		 * Allow the addition of Open Graph Meta Tags to all pages.
1820
		 *
1821
		 * @since 2.0.3
1822
		 *
1823
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1824
		 */
1825
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1826
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1827
		}
1828
	}
1829
1830
	/**
1831
	 * Check if Jetpack's Twitter tags should be used.
1832
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1833
	 *
1834
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1835
	 * @action plugins_loaded
1836
	 * @return null
1837
	 */
1838
	public function check_twitter_tags() {
1839
1840
		$active_plugins = self::get_active_plugins();
1841
1842
		if ( ! empty( $active_plugins ) ) {
1843
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1844
				if ( in_array( $plugin, $active_plugins ) ) {
1845
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1846
					break;
1847
				}
1848
			}
1849
		}
1850
1851
		/**
1852
		 * Allow Twitter Card Meta tags to be disabled.
1853
		 *
1854
		 * @since 2.6.0
1855
		 *
1856
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1857
		 */
1858
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1859
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1860
		}
1861
	}
1862
1863
	/**
1864
	 * Allows plugins to submit security reports.
1865
 	 *
1866
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1867
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1868
	 * @param array   $args         See definitions above
1869
	 */
1870
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1871
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1872
	}
1873
1874
/* Jetpack Options API */
1875
1876
	public static function get_option_names( $type = 'compact' ) {
1877
		return Jetpack_Options::get_option_names( $type );
1878
	}
1879
1880
	/**
1881
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1882
 	 *
1883
	 * @param string $name    Option name
1884
	 * @param mixed  $default (optional)
1885
	 */
1886
	public static function get_option( $name, $default = false ) {
1887
		return Jetpack_Options::get_option( $name, $default );
1888
	}
1889
1890
	/**
1891
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1892
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1893
	* $name must be a registered option name.
1894
	*/
1895
	public static function create_nonce( $name ) {
1896
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1897
1898
		Jetpack_Options::update_option( $name, $secret );
1899
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1900
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1901
			return new Jetpack_Error( 'missing_secrets' );
1902
1903
		return array(
1904
			'secret_1' => $secret_1,
1905
			'secret_2' => $secret_2,
1906
			'eol'      => $eol,
1907
		);
1908
	}
1909
1910
	/**
1911
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1912
 	 *
1913
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1914
	 * @param string $name  Option name
1915
	 * @param mixed  $value Option value
1916
	 */
1917
	public static function update_option( $name, $value ) {
1918
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1919
		return Jetpack_Options::update_option( $name, $value );
1920
	}
1921
1922
	/**
1923
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1924
 	 *
1925
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1926
	 * @param array $array array( option name => option value, ... )
1927
	 */
1928
	public static function update_options( $array ) {
1929
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1930
		return Jetpack_Options::update_options( $array );
1931
	}
1932
1933
	/**
1934
	 * Deletes the given option.  May be passed multiple option names as an array.
1935
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1936
	 *
1937
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1938
	 * @param string|array $names
1939
	 */
1940
	public static function delete_option( $names ) {
1941
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1942
		return Jetpack_Options::delete_option( $names );
1943
	}
1944
1945
	/**
1946
	 * Enters a user token into the user_tokens option
1947
	 *
1948
	 * @param int $user_id
1949
	 * @param string $token
1950
	 * return bool
1951
	 */
1952
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1953
		// not designed for concurrent updates
1954
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1955
		if ( ! is_array( $user_tokens ) )
1956
			$user_tokens = array();
1957
		$user_tokens[$user_id] = $token;
1958
		if ( $is_master_user ) {
1959
			$master_user = $user_id;
1960
			$options     = compact( 'user_tokens', 'master_user' );
1961
		} else {
1962
			$options = compact( 'user_tokens' );
1963
		}
1964
		return Jetpack_Options::update_options( $options );
1965
	}
1966
1967
	/**
1968
	 * Returns an array of all PHP files in the specified absolute path.
1969
	 * Equivalent to glob( "$absolute_path/*.php" ).
1970
	 *
1971
	 * @param string $absolute_path The absolute path of the directory to search.
1972
	 * @return array Array of absolute paths to the PHP files.
1973
	 */
1974
	public static function glob_php( $absolute_path ) {
1975
		if ( function_exists( 'glob' ) ) {
1976
			return glob( "$absolute_path/*.php" );
1977
		}
1978
1979
		$absolute_path = untrailingslashit( $absolute_path );
1980
		$files = array();
1981
		if ( ! $dir = @opendir( $absolute_path ) ) {
1982
			return $files;
1983
		}
1984
1985
		while ( false !== $file = readdir( $dir ) ) {
1986
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1987
				continue;
1988
			}
1989
1990
			$file = "$absolute_path/$file";
1991
1992
			if ( ! is_file( $file ) ) {
1993
				continue;
1994
			}
1995
1996
			$files[] = $file;
1997
		}
1998
1999
		closedir( $dir );
2000
2001
		return $files;
2002
	}
2003
2004
	public static function activate_new_modules( $redirect = false ) {
2005
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2006
			return;
2007
		}
2008
2009
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2010 View Code Duplication
		if ( ! $jetpack_old_version ) {
2011
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2012
			/** This action is documented in class.jetpack.php */
2013
			do_action( 'updating_jetpack_version', $version, false );
2014
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2015
		}
2016
2017
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2018
2019
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2020
			return;
2021
		}
2022
2023
		$active_modules     = Jetpack::get_active_modules();
2024
		$reactivate_modules = array();
2025
		foreach ( $active_modules as $active_module ) {
2026
			$module = Jetpack::get_module( $active_module );
2027
			if ( ! isset( $module['changed'] ) ) {
2028
				continue;
2029
			}
2030
2031
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2032
				continue;
2033
			}
2034
2035
			$reactivate_modules[] = $active_module;
2036
			Jetpack::deactivate_module( $active_module );
2037
		}
2038
2039
		$new_version = JETPACK__VERSION . ':' . time();
2040
		/** This action is documented in class.jetpack.php */
2041
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2042
		Jetpack_Options::update_options(
2043
			array(
2044
				'version'     => $new_version,
2045
				'old_version' => $jetpack_old_version,
2046
			)
2047
		);
2048
2049
		Jetpack::state( 'message', 'modules_activated' );
2050
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2051
2052
		if ( $redirect ) {
2053
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2054
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2055
				$page = $_GET['page'];
2056
			}
2057
2058
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2059
			exit;
2060
		}
2061
	}
2062
2063
	/**
2064
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2065
	 * Make sure to tuck away module "library" files in a sub-directory.
2066
	 */
2067
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2068
		static $modules = null;
2069
2070
		if ( ! isset( $modules ) ) {
2071
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2072
			// Use the cache if we're on the front-end and it's available...
2073
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2074
				$modules = $available_modules_option[ JETPACK__VERSION ];
2075
			} else {
2076
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2077
2078
				$modules = array();
2079
2080
				foreach ( $files as $file ) {
2081
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2082
						continue;
2083
					}
2084
2085
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2086
				}
2087
2088
				Jetpack_Options::update_option( 'available_modules', array(
2089
					JETPACK__VERSION => $modules,
2090
				) );
2091
			}
2092
		}
2093
2094
		/**
2095
		 * Filters the array of modules available to be activated.
2096
		 *
2097
		 * @since 2.4.0
2098
		 *
2099
		 * @param array $modules Array of available modules.
2100
		 * @param string $min_version Minimum version number required to use modules.
2101
		 * @param string $max_version Maximum version number required to use modules.
2102
		 */
2103
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2104
2105
		if ( ! $min_version && ! $max_version ) {
2106
			return array_keys( $mods );
2107
		}
2108
2109
		$r = array();
2110
		foreach ( $mods as $slug => $introduced ) {
2111
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2112
				continue;
2113
			}
2114
2115
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2116
				continue;
2117
			}
2118
2119
			$r[] = $slug;
2120
		}
2121
2122
		return $r;
2123
	}
2124
2125
	/**
2126
	 * Default modules loaded on activation.
2127
	 */
2128
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2129
		$return = array();
2130
2131
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2132
			$module_data = Jetpack::get_module( $module );
2133
2134
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2135
				case 'yes' :
2136
					$return[] = $module;
2137
					break;
2138
				case 'public' :
2139
					if ( Jetpack_Options::get_option( 'public' ) ) {
2140
						$return[] = $module;
2141
					}
2142
					break;
2143
				case 'no' :
2144
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2145
					break;
2146
			}
2147
		}
2148
		/**
2149
		 * Filters the array of default modules.
2150
		 *
2151
		 * @since 2.5.0
2152
		 *
2153
		 * @param array $return Array of default modules.
2154
		 * @param string $min_version Minimum version number required to use modules.
2155
		 * @param string $max_version Maximum version number required to use modules.
2156
		 */
2157
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2158
	}
2159
2160
	/**
2161
	 * Checks activated modules during auto-activation to determine
2162
	 * if any of those modules are being deprecated.  If so, close
2163
	 * them out, and add any replacement modules.
2164
	 *
2165
	 * Runs at priority 99 by default.
2166
	 *
2167
	 * This is run late, so that it can still activate a module if
2168
	 * the new module is a replacement for another that the user
2169
	 * currently has active, even if something at the normal priority
2170
	 * would kibosh everything.
2171
	 *
2172
	 * @since 2.6
2173
	 * @uses jetpack_get_default_modules filter
2174
	 * @param array $modules
2175
	 * @return array
2176
	 */
2177
	function handle_deprecated_modules( $modules ) {
2178
		$deprecated_modules = array(
2179
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2180
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2181
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2182
		);
2183
2184
		// Don't activate SSO if they never completed activating WPCC.
2185
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2186
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2187
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2188
				$deprecated_modules['wpcc'] = null;
2189
			}
2190
		}
2191
2192
		foreach ( $deprecated_modules as $module => $replacement ) {
2193
			if ( Jetpack::is_module_active( $module ) ) {
2194
				self::deactivate_module( $module );
2195
				if ( $replacement ) {
2196
					$modules[] = $replacement;
2197
				}
2198
			}
2199
		}
2200
2201
		return array_unique( $modules );
2202
	}
2203
2204
	/**
2205
	 * Checks activated plugins during auto-activation to determine
2206
	 * if any of those plugins are in the list with a corresponding module
2207
	 * that is not compatible with the plugin. The module will not be allowed
2208
	 * to auto-activate.
2209
	 *
2210
	 * @since 2.6
2211
	 * @uses jetpack_get_default_modules filter
2212
	 * @param array $modules
2213
	 * @return array
2214
	 */
2215
	function filter_default_modules( $modules ) {
2216
2217
		$active_plugins = self::get_active_plugins();
2218
2219
		if ( ! empty( $active_plugins ) ) {
2220
2221
			// For each module we'd like to auto-activate...
2222
			foreach ( $modules as $key => $module ) {
2223
				// If there are potential conflicts for it...
2224
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2225
					// For each potential conflict...
2226
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2227
						// If that conflicting plugin is active...
2228
						if ( in_array( $plugin, $active_plugins ) ) {
2229
							// Remove that item from being auto-activated.
2230
							unset( $modules[ $key ] );
2231
						}
2232
					}
2233
				}
2234
			}
2235
		}
2236
2237
		return $modules;
2238
	}
2239
2240
	/**
2241
	 * Extract a module's slug from its full path.
2242
	 */
2243
	public static function get_module_slug( $file ) {
2244
		return str_replace( '.php', '', basename( $file ) );
2245
	}
2246
2247
	/**
2248
	 * Generate a module's path from its slug.
2249
	 */
2250
	public static function get_module_path( $slug ) {
2251
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2252
	}
2253
2254
	/**
2255
	 * Load module data from module file. Headers differ from WordPress
2256
	 * plugin headers to avoid them being identified as standalone
2257
	 * plugins on the WordPress plugins page.
2258
	 */
2259
	public static function get_module( $module ) {
2260
		$headers = array(
2261
			'name'                      => 'Module Name',
2262
			'description'               => 'Module Description',
2263
			'jumpstart_desc'            => 'Jumpstart Description',
2264
			'sort'                      => 'Sort Order',
2265
			'recommendation_order'      => 'Recommendation Order',
2266
			'introduced'                => 'First Introduced',
2267
			'changed'                   => 'Major Changes In',
2268
			'deactivate'                => 'Deactivate',
2269
			'free'                      => 'Free',
2270
			'requires_connection'       => 'Requires Connection',
2271
			'auto_activate'             => 'Auto Activate',
2272
			'module_tags'               => 'Module Tags',
2273
			'feature'                   => 'Feature',
2274
			'additional_search_queries' => 'Additional Search Queries',
2275
		);
2276
2277
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2278
2279
		$mod = Jetpack::get_file_data( $file, $headers );
2280
		if ( empty( $mod['name'] ) ) {
2281
			return false;
2282
		}
2283
2284
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2285
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2286
		$mod['deactivate']              = empty( $mod['deactivate'] );
2287
		$mod['free']                    = empty( $mod['free'] );
2288
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2289
2290
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2291
			$mod['auto_activate'] = 'No';
2292
		} else {
2293
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2294
		}
2295
2296
		if ( $mod['module_tags'] ) {
2297
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2298
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2299
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2300
		} else {
2301
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2302
		}
2303
2304
		if ( $mod['feature'] ) {
2305
			$mod['feature'] = explode( ',', $mod['feature'] );
2306
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2307
		} else {
2308
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2309
		}
2310
2311
		/**
2312
		 * Filters the feature array on a module.
2313
		 *
2314
		 * This filter allows you to control where each module is filtered: Recommended,
2315
		 * Jumpstart, and the default "Other" listing.
2316
		 *
2317
		 * @since 3.5.0
2318
		 *
2319
		 * @param array   $mod['feature'] The areas to feature this module:
2320
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2321
		 *     'Recommended' shows on the main Jetpack admin screen.
2322
		 *     'Other' should be the default if no other value is in the array.
2323
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2324
		 * @param array   $mod All the currently assembled module data.
2325
		 */
2326
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2327
2328
		/**
2329
		 * Filter the returned data about a module.
2330
		 *
2331
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2332
		 * so please be careful.
2333
		 *
2334
		 * @since 3.6.0
2335
		 *
2336
		 * @param array   $mod    The details of the requested module.
2337
		 * @param string  $module The slug of the module, e.g. sharedaddy
2338
		 * @param string  $file   The path to the module source file.
2339
		 */
2340
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2341
	}
2342
2343
	/**
2344
	 * Like core's get_file_data implementation, but caches the result.
2345
	 */
2346
	public static function get_file_data( $file, $headers ) {
2347
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2348
		$file_name = basename( $file );
2349
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2350
		$key              = md5( $file_name . serialize( $headers ) );
2351
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2352
2353
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2354
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2355
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2356
		}
2357
2358
		$data = get_file_data( $file, $headers );
2359
2360
		// Strip out any old Jetpack versions that are cluttering the option.
2361
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2362
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2363
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2364
2365
		return $data;
2366
	}
2367
2368
	/**
2369
	 * Return translated module tag.
2370
	 *
2371
	 * @param string $tag Tag as it appears in each module heading.
2372
	 *
2373
	 * @return mixed
2374
	 */
2375
	public static function translate_module_tag( $tag ) {
2376
		return jetpack_get_module_i18n_tag( $tag );
2377
	}
2378
2379
	/**
2380
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2381
	 *
2382
	 * @since 3.9.2
2383
	 *
2384
	 * @param array $modules
2385
	 *
2386
	 * @return string|void
2387
	 */
2388
	public static function get_translated_modules( $modules ) {
2389
		foreach ( $modules as $index => $module ) {
2390
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2391
			if ( isset( $module['name'] ) ) {
2392
				$modules[ $index ]['name'] = $i18n_module['name'];
2393
			}
2394
			if ( isset( $module['description'] ) ) {
2395
				$modules[ $index ]['description'] = $i18n_module['description'];
2396
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2397
			}
2398
		}
2399
		return $modules;
2400
	}
2401
2402
	/**
2403
	 * Get a list of activated modules as an array of module slugs.
2404
	 */
2405
	public static function get_active_modules() {
2406
		$active = Jetpack_Options::get_option( 'active_modules' );
2407
2408
		if ( ! is_array( $active ) ) {
2409
			$active = array();
2410
		}
2411
2412
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2413
			$active[] = 'vaultpress';
2414
		} else {
2415
			$active = array_diff( $active, array( 'vaultpress' ) );
2416
		}
2417
2418
		//If protect is active on the main site of a multisite, it should be active on all sites.
2419
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2420
			$active[] = 'protect';
2421
		}
2422
2423
		return array_unique( $active );
2424
	}
2425
2426
	/**
2427
	 * Check whether or not a Jetpack module is active.
2428
	 *
2429
	 * @param string $module The slug of a Jetpack module.
2430
	 * @return bool
2431
	 *
2432
	 * @static
2433
	 */
2434
	public static function is_module_active( $module ) {
2435
		return in_array( $module, self::get_active_modules() );
2436
	}
2437
2438
	public static function is_module( $module ) {
2439
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2440
	}
2441
2442
	/**
2443
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2444
	 *
2445
	 * @param bool $catch True to start catching, False to stop.
2446
	 *
2447
	 * @static
2448
	 */
2449
	public static function catch_errors( $catch ) {
2450
		static $display_errors, $error_reporting;
2451
2452
		if ( $catch ) {
2453
			$display_errors  = @ini_set( 'display_errors', 1 );
2454
			$error_reporting = @error_reporting( E_ALL );
2455
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2456
		} else {
2457
			@ini_set( 'display_errors', $display_errors );
2458
			@error_reporting( $error_reporting );
2459
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2460
		}
2461
	}
2462
2463
	/**
2464
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2465
	 */
2466
	public static function catch_errors_on_shutdown() {
2467
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2468
	}
2469
2470
	/**
2471
	 * Rewrite any string to make paths easier to read.
2472
	 *
2473
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2474
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2475
	 *
2476
	 * @param $string
2477
	 * @return mixed
2478
	 */
2479
	public static function alias_directories( $string ) {
2480
		// ABSPATH has a trailing slash.
2481
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2482
		// WP_CONTENT_DIR does not have a trailing slash.
2483
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2484
2485
		return $string;
2486
	}
2487
2488
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2489
		$jetpack = Jetpack::init();
2490
2491
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2492
		$modules = array_merge( $other_modules, $modules );
2493
2494
		// Look for standalone plugins and disable if active.
2495
2496
		$to_deactivate = array();
2497
		foreach ( $modules as $module ) {
2498
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2499
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2500
			}
2501
		}
2502
2503
		$deactivated = array();
2504
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2505
			list( $probable_file, $probable_title ) = $deactivate_me;
2506
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2507
				$deactivated[] = $module;
2508
			}
2509
		}
2510
2511
		if ( $deactivated && $redirect ) {
2512
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2513
2514
			$url = add_query_arg(
2515
				array(
2516
					'action'   => 'activate_default_modules',
2517
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2518
				),
2519
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2520
			);
2521
			wp_safe_redirect( $url );
2522
			exit;
2523
		}
2524
2525
		/**
2526
		 * Fires before default modules are activated.
2527
		 *
2528
		 * @since 1.9.0
2529
		 *
2530
		 * @param string $min_version Minimum version number required to use modules.
2531
		 * @param string $max_version Maximum version number required to use modules.
2532
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2533
		 */
2534
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2535
2536
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2537
		Jetpack::restate();
2538
		Jetpack::catch_errors( true );
2539
2540
		$active = Jetpack::get_active_modules();
2541
2542
		foreach ( $modules as $module ) {
2543
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2544
				$active[] = $module;
2545
				self::update_active_modules( $active );
2546
				continue;
2547
			}
2548
2549
			if ( in_array( $module, $active ) ) {
2550
				$module_info = Jetpack::get_module( $module );
2551
				if ( ! $module_info['deactivate'] ) {
2552
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2553 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2554
						$active_state = explode( ',', $active_state );
2555
					} else {
2556
						$active_state = array();
2557
					}
2558
					$active_state[] = $module;
2559
					Jetpack::state( $state, implode( ',', $active_state ) );
2560
				}
2561
				continue;
2562
			}
2563
2564
			$file = Jetpack::get_module_path( $module );
2565
			if ( ! file_exists( $file ) ) {
2566
				continue;
2567
			}
2568
2569
			// we'll override this later if the plugin can be included without fatal error
2570
			if ( $redirect ) {
2571
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2572
			}
2573
			Jetpack::state( 'error', 'module_activation_failed' );
2574
			Jetpack::state( 'module', $module );
2575
			ob_start();
2576
			require $file;
2577
2578
			$active[] = $module;
2579
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2580 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2581
				$active_state = explode( ',', $active_state );
2582
			} else {
2583
				$active_state = array();
2584
			}
2585
			$active_state[] = $module;
2586
			Jetpack::state( $state, implode( ',', $active_state ) );
2587
			Jetpack::update_active_modules( $active );
2588
2589
			ob_end_clean();
2590
		}
2591
		Jetpack::state( 'error', false );
2592
		Jetpack::state( 'module', false );
2593
		Jetpack::catch_errors( false );
2594
		/**
2595
		 * Fires when default modules are activated.
2596
		 *
2597
		 * @since 1.9.0
2598
		 *
2599
		 * @param string $min_version Minimum version number required to use modules.
2600
		 * @param string $max_version Maximum version number required to use modules.
2601
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2602
		 */
2603
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2604
	}
2605
2606
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2607
		/**
2608
		 * Fires before a module is activated.
2609
		 *
2610
		 * @since 2.6.0
2611
		 *
2612
		 * @param string $module Module slug.
2613
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2614
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2615
		 */
2616
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2617
2618
		$jetpack = Jetpack::init();
2619
2620
		if ( ! strlen( $module ) )
2621
			return false;
2622
2623
		if ( ! Jetpack::is_module( $module ) )
2624
			return false;
2625
2626
		// If it's already active, then don't do it again
2627
		$active = Jetpack::get_active_modules();
2628
		foreach ( $active as $act ) {
2629
			if ( $act == $module )
2630
				return true;
2631
		}
2632
2633
		$module_data = Jetpack::get_module( $module );
2634
2635
		if ( ! Jetpack::is_active() ) {
2636
			if ( !Jetpack::is_development_mode() )
2637
				return false;
2638
2639
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2640
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2641
				return false;
2642
		}
2643
2644
		// Check and see if the old plugin is active
2645
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2646
			// Deactivate the old plugin
2647
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2648
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2649
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2650
				Jetpack::state( 'deactivated_plugins', $module );
2651
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2652
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2653
			}
2654
		}
2655
2656
		// Protect won't work with mis-configured IPs
2657
		if ( 'protect' === $module ) {
2658
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2659
			if ( ! jetpack_protect_get_ip() ) {
2660
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2661
				return false;
2662
			}
2663
		}
2664
2665
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2666
		Jetpack::state( 'module', $module );
2667
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2668
2669
		Jetpack::catch_errors( true );
2670
		ob_start();
2671
		require Jetpack::get_module_path( $module );
2672
		/** This action is documented in class.jetpack.php */
2673
		do_action( 'jetpack_activate_module', $module );
2674
		$active[] = $module;
2675
		Jetpack::update_active_modules( $active );
2676
2677
		Jetpack::state( 'error', false ); // the override
2678
		ob_end_clean();
2679
		Jetpack::catch_errors( false );
2680
2681
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2682 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2683
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2684
2685
			//Jump start is being dismissed send data to MC Stats
2686
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2687
2688
			$jetpack->do_stats( 'server_side' );
2689
		}
2690
2691
		if ( $redirect ) {
2692
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2693
		}
2694
		if ( $exit ) {
2695
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2696
		}
2697
		return true;
2698
	}
2699
2700
	function activate_module_actions( $module ) {
2701
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2702
	}
2703
2704
	public static function deactivate_module( $module ) {
2705
		/**
2706
		 * Fires when a module is deactivated.
2707
		 *
2708
		 * @since 1.9.0
2709
		 *
2710
		 * @param string $module Module slug.
2711
		 */
2712
		do_action( 'jetpack_pre_deactivate_module', $module );
2713
2714
		$jetpack = Jetpack::init();
2715
2716
		$active = Jetpack::get_active_modules();
2717
		$new    = array_filter( array_diff( $active, (array) $module ) );
2718
2719
		// A flag for Jump Start so it's not shown again.
2720 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2721
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2722
2723
			//Jump start is being dismissed send data to MC Stats
2724
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2725
2726
			$jetpack->do_stats( 'server_side' );
2727
		}
2728
2729
		return self::update_active_modules( $new );
2730
	}
2731
2732
	public static function enable_module_configurable( $module ) {
2733
		$module = Jetpack::get_module_slug( $module );
2734
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2735
	}
2736
2737
	public static function module_configuration_url( $module ) {
2738
		$module = Jetpack::get_module_slug( $module );
2739
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2740
	}
2741
2742
	public static function module_configuration_load( $module, $method ) {
2743
		$module = Jetpack::get_module_slug( $module );
2744
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2745
	}
2746
2747
	public static function module_configuration_head( $module, $method ) {
2748
		$module = Jetpack::get_module_slug( $module );
2749
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2750
	}
2751
2752
	public static function module_configuration_screen( $module, $method ) {
2753
		$module = Jetpack::get_module_slug( $module );
2754
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2755
	}
2756
2757
	public static function module_configuration_activation_screen( $module, $method ) {
2758
		$module = Jetpack::get_module_slug( $module );
2759
		add_action( 'display_activate_module_setting_' . $module, $method );
2760
	}
2761
2762
/* Installation */
2763
2764
	public static function bail_on_activation( $message, $deactivate = true ) {
2765
?>
2766
<!doctype html>
2767
<html>
2768
<head>
2769
<meta charset="<?php bloginfo( 'charset' ); ?>">
2770
<style>
2771
* {
2772
	text-align: center;
2773
	margin: 0;
2774
	padding: 0;
2775
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2776
}
2777
p {
2778
	margin-top: 1em;
2779
	font-size: 18px;
2780
}
2781
</style>
2782
<body>
2783
<p><?php echo esc_html( $message ); ?></p>
2784
</body>
2785
</html>
2786
<?php
2787
		if ( $deactivate ) {
2788
			$plugins = get_option( 'active_plugins' );
2789
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2790
			$update  = false;
2791
			foreach ( $plugins as $i => $plugin ) {
2792
				if ( $plugin === $jetpack ) {
2793
					$plugins[$i] = false;
2794
					$update = true;
2795
				}
2796
			}
2797
2798
			if ( $update ) {
2799
				update_option( 'active_plugins', array_filter( $plugins ) );
2800
			}
2801
		}
2802
		exit;
2803
	}
2804
2805
	/**
2806
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2807
	 * @static
2808
	 */
2809
	public static function plugin_activation( $network_wide ) {
2810
		Jetpack_Options::update_option( 'activated', 1 );
2811
2812
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2813
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2814
		}
2815
2816
		if ( $network_wide )
2817
			Jetpack::state( 'network_nag', true );
2818
2819
		Jetpack::plugin_initialize();
2820
	}
2821
	/**
2822
	 * Runs before bumping version numbers up to a new version
2823
	 * @param  (string) $version    Version:timestamp
2824
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2825
	 * @return null              [description]
2826
	 */
2827
	public static function do_version_bump( $version, $old_version ) {
2828
2829
		if ( ! $old_version ) { // For new sites
2830
			// Setting up jetpack manage
2831
			Jetpack::activate_manage();
2832
		}
2833
	}
2834
2835
	/**
2836
	 * Sets the internal version number and activation state.
2837
	 * @static
2838
	 */
2839
	public static function plugin_initialize() {
2840
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2841
			Jetpack_Options::update_option( 'activated', 2 );
2842
		}
2843
2844 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2845
			$version = $old_version = JETPACK__VERSION . ':' . time();
2846
			/** This action is documented in class.jetpack.php */
2847
			do_action( 'updating_jetpack_version', $version, false );
2848
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2849
		}
2850
2851
		Jetpack::load_modules();
2852
2853
		Jetpack_Options::delete_option( 'do_activate' );
2854
	}
2855
2856
	/**
2857
	 * Removes all connection options
2858
	 * @static
2859
	 */
2860
	public static function plugin_deactivation( ) {
2861
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2862
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2863
			Jetpack_Network::init()->deactivate();
2864
		} else {
2865
			Jetpack::disconnect( false );
2866
			//Jetpack_Heartbeat::init()->deactivate();
2867
		}
2868
	}
2869
2870
	/**
2871
	 * Disconnects from the Jetpack servers.
2872
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2873
	 * @static
2874
	 */
2875
	public static function disconnect( $update_activated_state = true ) {
2876
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2877
		Jetpack::clean_nonces( true );
2878
2879
		// If the site is in an IDC because sync is not allowed,
2880
		// let's make sure to not disconnect the production site.
2881
		if ( ! self::validate_sync_error_idc_option() ) {
2882
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2883
			Jetpack::load_xml_rpc_client();
2884
			$xml = new Jetpack_IXR_Client();
2885
			$xml->query( 'jetpack.deregister' );
2886
		}
2887
2888
		Jetpack_Options::delete_option(
2889
			array(
2890
				'register',
2891
				'blog_token',
2892
				'user_token',
2893
				'user_tokens',
2894
				'master_user',
2895
				'time_diff',
2896
				'fallback_no_verify_ssl_certs',
2897
			)
2898
		);
2899
2900
		Jetpack_IDC::clear_all_idc_options();
2901
2902
		if ( $update_activated_state ) {
2903
			Jetpack_Options::update_option( 'activated', 4 );
2904
		}
2905
2906
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2907
			// Check then record unique disconnection if site has never been disconnected previously
2908
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2909
				$jetpack_unique_connection['disconnected'] = 1;
2910
			} else {
2911
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2912
					//track unique disconnect
2913
					$jetpack = Jetpack::init();
2914
2915
					$jetpack->stat( 'connections', 'unique-disconnect' );
2916
					$jetpack->do_stats( 'server_side' );
2917
				}
2918
				// increment number of times disconnected
2919
				$jetpack_unique_connection['disconnected'] += 1;
2920
			}
2921
2922
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2923
		}
2924
2925
		// Delete cached connected user data
2926
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2927
		delete_transient( $transient_key );
2928
2929
		// Delete all the sync related data. Since it could be taking up space.
2930
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2931
		Jetpack_Sync_Sender::get_instance()->uninstall();
2932
2933
		// Disable the Heartbeat cron
2934
		Jetpack_Heartbeat::init()->deactivate();
2935
	}
2936
2937
	/**
2938
	 * Unlinks the current user from the linked WordPress.com user
2939
	 */
2940
	public static function unlink_user( $user_id = null ) {
2941
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2942
			return false;
2943
2944
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2945
2946
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2947
			return false;
2948
2949
		if ( ! isset( $tokens[ $user_id ] ) )
2950
			return false;
2951
2952
		Jetpack::load_xml_rpc_client();
2953
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2954
		$xml->query( 'jetpack.unlink_user', $user_id );
2955
2956
		unset( $tokens[ $user_id ] );
2957
2958
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2959
2960
		/**
2961
		 * Fires after the current user has been unlinked from WordPress.com.
2962
		 *
2963
		 * @since 4.1.0
2964
		 *
2965
		 * @param int $user_id The current user's ID.
2966
		 */
2967
		do_action( 'jetpack_unlinked_user', $user_id );
2968
2969
		return true;
2970
	}
2971
2972
	/**
2973
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2974
	 */
2975
	public static function try_registration() {
2976
		// Let's get some testing in beta versions and such.
2977
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2978
			// Before attempting to connect, let's make sure that the domains are viable.
2979
			$domains_to_check = array_unique( array(
2980
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2981
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2982
			) );
2983
			foreach ( $domains_to_check as $domain ) {
2984
				$result = Jetpack_Data::is_usable_domain( $domain );
2985
				if ( is_wp_error( $result ) ) {
2986
					return $result;
2987
				}
2988
			}
2989
		}
2990
2991
		$result = Jetpack::register();
2992
2993
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2994
		if ( ! $result || is_wp_error( $result ) ) {
2995
			return $result;
2996
		} else {
2997
			return true;
2998
		}
2999
	}
3000
3001
	/**
3002
	 * Tracking an internal event log. Try not to put too much chaff in here.
3003
	 *
3004
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3005
	 */
3006
	public static function log( $code, $data = null ) {
3007
		// only grab the latest 200 entries
3008
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3009
3010
		// Append our event to the log
3011
		$log_entry = array(
3012
			'time'    => time(),
3013
			'user_id' => get_current_user_id(),
3014
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3015
			'code'    => $code,
3016
		);
3017
		// Don't bother storing it unless we've got some.
3018
		if ( ! is_null( $data ) ) {
3019
			$log_entry['data'] = $data;
3020
		}
3021
		$log[] = $log_entry;
3022
3023
		// Try add_option first, to make sure it's not autoloaded.
3024
		// @todo: Add an add_option method to Jetpack_Options
3025
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3026
			Jetpack_Options::update_option( 'log', $log );
3027
		}
3028
3029
		/**
3030
		 * Fires when Jetpack logs an internal event.
3031
		 *
3032
		 * @since 3.0.0
3033
		 *
3034
		 * @param array $log_entry {
3035
		 *	Array of details about the log entry.
3036
		 *
3037
		 *	@param string time Time of the event.
3038
		 *	@param int user_id ID of the user who trigerred the event.
3039
		 *	@param int blog_id Jetpack Blog ID.
3040
		 *	@param string code Unique name for the event.
3041
		 *	@param string data Data about the event.
3042
		 * }
3043
		 */
3044
		do_action( 'jetpack_log_entry', $log_entry );
3045
	}
3046
3047
	/**
3048
	 * Get the internal event log.
3049
	 *
3050
	 * @param $event (string) - only return the specific log events
3051
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3052
	 *
3053
	 * @return array of log events || WP_Error for invalid params
3054
	 */
3055
	public static function get_log( $event = false, $num = false ) {
3056
		if ( $event && ! is_string( $event ) ) {
3057
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3058
		}
3059
3060
		if ( $num && ! is_numeric( $num ) ) {
3061
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3062
		}
3063
3064
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3065
3066
		// If nothing set - act as it did before, otherwise let's start customizing the output
3067
		if ( ! $num && ! $event ) {
3068
			return $entire_log;
3069
		} else {
3070
			$entire_log = array_reverse( $entire_log );
3071
		}
3072
3073
		$custom_log_output = array();
3074
3075
		if ( $event ) {
3076
			foreach ( $entire_log as $log_event ) {
3077
				if ( $event == $log_event[ 'code' ] ) {
3078
					$custom_log_output[] = $log_event;
3079
				}
3080
			}
3081
		} else {
3082
			$custom_log_output = $entire_log;
3083
		}
3084
3085
		if ( $num ) {
3086
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3087
		}
3088
3089
		return $custom_log_output;
3090
	}
3091
3092
	/**
3093
	 * Log modification of important settings.
3094
	 */
3095
	public static function log_settings_change( $option, $old_value, $value ) {
3096
		switch( $option ) {
3097
			case 'jetpack_sync_non_public_post_stati':
3098
				self::log( $option, $value );
3099
				break;
3100
		}
3101
	}
3102
3103
	/**
3104
	 * Return stat data for WPCOM sync
3105
	 */
3106
	public static function get_stat_data( $encode = true, $extended = true ) {
3107
		$data = Jetpack_Heartbeat::generate_stats_array();
3108
3109
		if ( $extended ) {
3110
			$additional_data = self::get_additional_stat_data();
3111
			$data = array_merge( $data, $additional_data );
3112
		}
3113
3114
		if ( $encode ) {
3115
			return json_encode( $data );
3116
		}
3117
3118
		return $data;
3119
	}
3120
3121
	/**
3122
	 * Get additional stat data to sync to WPCOM
3123
	 */
3124
	public static function get_additional_stat_data( $prefix = '' ) {
3125
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3126
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3127
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3128
		$return["{$prefix}site-count"]     = 0;
3129
3130
		if ( function_exists( 'get_blog_count' ) ) {
3131
			$return["{$prefix}site-count"] = get_blog_count();
3132
		}
3133
		return $return;
3134
	}
3135
3136
	private static function get_site_user_count() {
3137
		global $wpdb;
3138
3139
		if ( function_exists( 'wp_is_large_network' ) ) {
3140
			if ( wp_is_large_network( 'users' ) ) {
3141
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3142
			}
3143
		}
3144 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3145
			// It wasn't there, so regenerate the data and save the transient
3146
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3147
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3148
		}
3149
		return $user_count;
3150
	}
3151
3152
	/* Admin Pages */
3153
3154
	function admin_init() {
3155
		// If the plugin is not connected, display a connect message.
3156
		if (
3157
			// the plugin was auto-activated and needs its candy
3158
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3159
		||
3160
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3161
			! Jetpack_Options::get_option( 'activated' )
3162
		) {
3163
			Jetpack::plugin_initialize();
3164
		}
3165
3166
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3167
			Jetpack_Connection_Banner::init();
3168
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3169
			// Upgrade: 1.1 -> 1.1.1
3170
			// Check and see if host can verify the Jetpack servers' SSL certificate
3171
			$args = array();
3172
			Jetpack_Client::_wp_remote_request(
3173
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3174
				$args,
3175
				true
3176
			);
3177
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3178
			// Show the notice on the Dashboard only for now
3179
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3180
		}
3181
3182
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3183
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3184
		}
3185
3186
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3187
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3188
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3189
3190
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3191
			// Artificially throw errors in certain whitelisted cases during plugin activation
3192
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3193
		}
3194
3195
		// Jetpack Manage Activation Screen from .com
3196
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3197
3198
		// Add custom column in wp-admin/users.php to show whether user is linked.
3199
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3200
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3201
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3202
	}
3203
3204
	function admin_body_class( $admin_body_class = '' ) {
3205
		$classes = explode( ' ', trim( $admin_body_class ) );
3206
3207
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3208
3209
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3210
		return " $admin_body_class ";
3211
	}
3212
3213
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3214
		return $admin_body_class . ' jetpack-pagestyles ';
3215
	}
3216
3217
	/**
3218
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3219
	 *
3220
	 * @return null
3221
	 */
3222
	function prepare_manage_jetpack_notice() {
3223
3224
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3225
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3226
	}
3227
3228
	function manage_activate_screen() {
3229
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3230
	}
3231
	/**
3232
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3233
	 * This function artificially throws errors for such cases (whitelisted).
3234
	 *
3235
	 * @param string $plugin The activated plugin.
3236
	 */
3237
	function throw_error_on_activate_plugin( $plugin ) {
3238
		$active_modules = Jetpack::get_active_modules();
3239
3240
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3241
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3242
			$throw = false;
3243
3244
			// Try and make sure it really was the stats plugin
3245
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3246
				if ( 'stats.php' == basename( $plugin ) ) {
3247
					$throw = true;
3248
				}
3249
			} else {
3250
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3251
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3252
					$throw = true;
3253
				}
3254
			}
3255
3256
			if ( $throw ) {
3257
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3258
			}
3259
		}
3260
	}
3261
3262
	function intercept_plugin_error_scrape_init() {
3263
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3264
	}
3265
3266
	function intercept_plugin_error_scrape( $action, $result ) {
3267
		if ( ! $result ) {
3268
			return;
3269
		}
3270
3271
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3272
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3273
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3274
			}
3275
		}
3276
	}
3277
3278
	function add_remote_request_handlers() {
3279
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3280
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3281
	}
3282
3283
	function remote_request_handlers() {
3284
		$action = current_filter();
3285
3286
		switch ( current_filter() ) {
3287
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3288
			$response = $this->upload_handler();
3289
			break;
3290
3291
		case 'wp_ajax_nopriv_jetpack_update_file' :
3292
			$response = $this->upload_handler( true );
3293
			break;
3294
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
3295
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3296
			break;
3297
		}
3298
3299
		if ( ! $response ) {
3300
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3301
		}
3302
3303
		if ( is_wp_error( $response ) ) {
3304
			$status_code       = $response->get_error_data();
3305
			$error             = $response->get_error_code();
3306
			$error_description = $response->get_error_message();
3307
3308
			if ( ! is_int( $status_code ) ) {
3309
				$status_code = 400;
3310
			}
3311
3312
			status_header( $status_code );
3313
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3314
		}
3315
3316
		status_header( 200 );
3317
		if ( true === $response ) {
3318
			exit;
3319
		}
3320
3321
		die( json_encode( (object) $response ) );
3322
	}
3323
3324
	/**
3325
	 * Uploads a file gotten from the global $_FILES.
3326
	 * If `$update_media_item` is true and `post_id` is defined
3327
	 * the attachment file of the media item (gotten through of the post_id)
3328
	 * will be updated instead of add a new one.
3329
	 * 
3330
	 * @param  boolean $update_media_item - update media attachment
3331
	 * @return array - An array describing the uploadind files process
3332
	 */
3333
	function upload_handler( $update_media_item = false ) {
3334
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3335
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3336
		}
3337
3338
		$user = wp_authenticate( '', '' );
3339
		if ( ! $user || is_wp_error( $user ) ) {
3340
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3341
		}
3342
3343
		wp_set_current_user( $user->ID );
3344
3345
		if ( ! current_user_can( 'upload_files' ) ) {
3346
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3347
		}
3348
3349
		if ( empty( $_FILES ) ) {
3350
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3351
		}
3352
3353
		foreach ( array_keys( $_FILES ) as $files_key ) {
3354
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3355
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3356
			}
3357
		}
3358
3359
		$media_keys = array_keys( $_FILES['media'] );
3360
3361
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3362
		if ( ! $token || is_wp_error( $token ) ) {
3363
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3364
		}
3365
3366
		$uploaded_files = array();
3367
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3368
		unset( $GLOBALS['post'] );
3369
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3370
			$file = array();
3371
			foreach ( $media_keys as $media_key ) {
3372
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3373
			}
3374
3375
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3376
3377
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3378
			if ( $hmac_provided !== $hmac_file ) {
3379
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3380
				continue;
3381
			}
3382
3383
			$_FILES['.jetpack.upload.'] = $file;
3384
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3385
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3386
				$post_id = 0;
3387
			}
3388
3389
			if ( $update_media_item ) {
3390
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3391
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3392
				}
3393
3394
				$media_array = $_FILES['media'];
3395
3396
				$file_array['name'] = $media_array['name'][0]; 
3397
				$file_array['type'] = $media_array['type'][0]; 
3398
				$file_array['tmp_name'] = $media_array['tmp_name'][0]; 
3399
				$file_array['error'] = $media_array['error'][0]; 
3400
				$file_array['size'] = $media_array['size'][0];
3401
3402
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3403
3404
				if ( is_wp_error( $edited_media_item ) ) {
3405
					return $edited_media_item;
3406
				}
3407
3408
				$response = (object) array(
3409
					'id'   => (string) $post_id,
3410
					'file' => (string) $edited_media_item->post_title,
3411
					'url'  => (string) wp_get_attachment_url( $post_id ),
3412
					'type' => (string) $edited_media_item->post_mime_type,
3413
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3414
				);
3415
3416
				return (array) array( $response );
3417
			}
3418
3419
			$attachment_id = media_handle_upload(
3420
				'.jetpack.upload.',
3421
				$post_id,
3422
				array(),
3423
				array(
3424
					'action' => 'jetpack_upload_file',
3425
				)
3426
			);
3427
3428
			if ( ! $attachment_id ) {
3429
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3430
			} elseif ( is_wp_error( $attachment_id ) ) {
3431
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3432
			} else {
3433
				$attachment = get_post( $attachment_id );
3434
				$uploaded_files[$index] = (object) array(
3435
					'id'   => (string) $attachment_id,
3436
					'file' => $attachment->post_title,
3437
					'url'  => wp_get_attachment_url( $attachment_id ),
3438
					'type' => $attachment->post_mime_type,
3439
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3440
				);
3441
				// Zip files uploads are not supported unless they are done for installation purposed
3442
				// lets delete them in case something goes wrong in this whole process
3443
				if ( 'application/zip' === $attachment->post_mime_type ) {
3444
					// Schedule a cleanup for 2 hours from now in case of failed install.
3445
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3446
				}
3447
			}
3448
		}
3449
		if ( ! is_null( $global_post ) ) {
3450
			$GLOBALS['post'] = $global_post;
3451
		}
3452
3453
		return $uploaded_files;
3454
	}
3455
3456
	/**
3457
	 * Add help to the Jetpack page
3458
	 *
3459
	 * @since Jetpack (1.2.3)
3460
	 * @return false if not the Jetpack page
3461
	 */
3462
	function admin_help() {
3463
		$current_screen = get_current_screen();
3464
3465
		// Overview
3466
		$current_screen->add_help_tab(
3467
			array(
3468
				'id'		=> 'home',
3469
				'title'		=> __( 'Home', 'jetpack' ),
3470
				'content'	=>
3471
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3472
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3473
					'<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>',
3474
			)
3475
		);
3476
3477
		// Screen Content
3478
		if ( current_user_can( 'manage_options' ) ) {
3479
			$current_screen->add_help_tab(
3480
				array(
3481
					'id'		=> 'settings',
3482
					'title'		=> __( 'Settings', 'jetpack' ),
3483
					'content'	=>
3484
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3485
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3486
						'<ol>' .
3487
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3488
							'<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>' .
3489
						'</ol>' .
3490
						'<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>'
3491
				)
3492
			);
3493
		}
3494
3495
		// Help Sidebar
3496
		$current_screen->set_help_sidebar(
3497
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3498
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3499
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3500
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3501
		);
3502
	}
3503
3504
	function admin_menu_css() {
3505
		wp_enqueue_style( 'jetpack-icons' );
3506
	}
3507
3508
	function admin_menu_order() {
3509
		return true;
3510
	}
3511
3512 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3513
		$jp_menu_order = array();
3514
3515
		foreach ( $menu_order as $index => $item ) {
3516
			if ( $item != 'jetpack' ) {
3517
				$jp_menu_order[] = $item;
3518
			}
3519
3520
			if ( $index == 0 ) {
3521
				$jp_menu_order[] = 'jetpack';
3522
			}
3523
		}
3524
3525
		return $jp_menu_order;
3526
	}
3527
3528
	function admin_head() {
3529 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3530
			/** This action is documented in class.jetpack-admin-page.php */
3531
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3532
	}
3533
3534
	function admin_banner_styles() {
3535
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3536
3537 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3538
			wp_register_style(
3539
				'jetpack-dops-style',
3540
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3541
				array(),
3542
				JETPACK__VERSION
3543
			);
3544
		}
3545
3546
		wp_enqueue_style(
3547
			'jetpack',
3548
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3549
			array( 'jetpack-dops-style' ),
3550
			 JETPACK__VERSION . '-20121016'
3551
		);
3552
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3553
		wp_style_add_data( 'jetpack', 'suffix', $min );
3554
	}
3555
3556
	function plugin_action_links( $actions ) {
3557
3558
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3559
3560
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3561
			return array_merge(
3562
				$jetpack_home,
3563
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3564
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3565
				$actions
3566
				);
3567
			}
3568
3569
		return array_merge( $jetpack_home, $actions );
3570
	}
3571
3572
	/**
3573
	 * This is the first banner
3574
	 * It should be visible only to user that can update the option
3575
	 * Are not connected
3576
	 *
3577
	 * @return null
3578
	 */
3579
	function admin_jetpack_manage_notice() {
3580
		$screen = get_current_screen();
3581
3582
		// Don't show the connect notice on the jetpack settings page.
3583
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3584
			return;
3585
		}
3586
3587
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3588
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3589
		/**
3590
		 * I think it would be great to have different wordsing depending on where you are
3591
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3592
		 * etc..
3593
		 */
3594
3595
		?>
3596
		<div id="message" class="updated jp-banner">
3597
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3598
				<div class="jp-banner__description-container">
3599
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3600
					<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>
3601
					<p class="jp-banner__button-container">
3602
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3603
						<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>
3604
					</p>
3605
				</div>
3606
		</div>
3607
		<?php
3608
	}
3609
3610
	/**
3611
	 * Returns the url that the user clicks to remove the notice for the big banner
3612
	 * @return (string)
3613
	 */
3614
	function opt_out_jetpack_manage_url() {
3615
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3616
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3617
	}
3618
	/**
3619
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3620
	 * @return (string)
3621
	 */
3622
	function opt_in_jetpack_manage_url() {
3623
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3624
	}
3625
3626
	function opt_in_jetpack_manage_notice() {
3627
		?>
3628
		<div class="wrap">
3629
			<div id="message" class="jetpack-message is-opt-in">
3630
				<?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' ); ?>
3631
			</div>
3632
		</div>
3633
		<?php
3634
3635
	}
3636
	/**
3637
	 * Determines whether to show the notice of not true = display notice
3638
	 * @return (bool)
3639
	 */
3640
	function can_display_jetpack_manage_notice() {
3641
		// never display the notice to users that can't do anything about it anyways
3642
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3643
			return false;
3644
3645
		// don't display if we are in development more
3646
		if( Jetpack::is_development_mode() ) {
3647
			return false;
3648
		}
3649
		// don't display if the site is private
3650
		if(  ! Jetpack_Options::get_option( 'public' ) )
3651
			return false;
3652
3653
		/**
3654
		 * Should the Jetpack Remote Site Management notice be displayed.
3655
		 *
3656
		 * @since 3.3.0
3657
		 *
3658
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3659
		 */
3660
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3661
	}
3662
3663
	/*
3664
	 * Registration flow:
3665
	 * 1 - ::admin_page_load() action=register
3666
	 * 2 - ::try_registration()
3667
	 * 3 - ::register()
3668
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3669
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3670
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3671
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3672
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3673
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3674
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3675
	 *       jetpack_id, jetpack_secret, jetpack_public
3676
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3677
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3678
	 * 5 - user logs in with WP.com account
3679
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3680
	 *		- Jetpack_Client_Server::authorize()
3681
	 *		- Jetpack_Client_Server::get_token()
3682
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3683
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3684
	 *			- which responds with access_token, token_type, scope
3685
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3686
	 *		- Jetpack::activate_default_modules()
3687
	 *     		- Deactivates deprecated plugins
3688
	 *     		- Activates all default modules
3689
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3690
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3691
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3692
	 *     Done!
3693
	 */
3694
3695
	/**
3696
	 * Handles the page load events for the Jetpack admin page
3697
	 */
3698
	function admin_page_load() {
3699
		$error = false;
3700
3701
		// Make sure we have the right body class to hook stylings for subpages off of.
3702
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3703
3704
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3705
			// Should only be used in intermediate redirects to preserve state across redirects
3706
			Jetpack::restate();
3707
		}
3708
3709
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3710
			// User clicked in the iframe to link their accounts
3711
			if ( ! Jetpack::is_user_connected() ) {
3712
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3713
				if ( isset( $_GET['notes_iframe'] ) )
3714
					$connect_url .= '&notes_iframe';
3715
				wp_redirect( $connect_url );
3716
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3717
			} else {
3718
				if ( ! isset( $_GET['calypso_env'] ) ) {
3719
					Jetpack::state( 'message', 'already_authorized' );
3720
					wp_safe_redirect( Jetpack::admin_url() );
3721
				} else {
3722
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3723
					$connect_url .= '&already_authorized=true';
3724
					wp_redirect( $connect_url );
3725
				}
3726
			}
3727
		}
3728
3729
3730
		if ( isset( $_GET['action'] ) ) {
3731
			switch ( $_GET['action'] ) {
3732
			case 'authorize':
3733
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3734
					Jetpack::state( 'message', 'already_authorized' );
3735
					wp_safe_redirect( Jetpack::admin_url() );
3736
					exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3737
				}
3738
				Jetpack::log( 'authorize' );
3739
				$client_server = new Jetpack_Client_Server;
3740
				$client_server->client_authorize();
3741
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3742
			case 'register' :
3743
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3744
					$error = 'cheatin';
3745
					break;
3746
				}
3747
				check_admin_referer( 'jetpack-register' );
3748
				Jetpack::log( 'register' );
3749
				Jetpack::maybe_set_version_option();
3750
				$registered = Jetpack::try_registration();
3751
				if ( is_wp_error( $registered ) ) {
3752
					$error = $registered->get_error_code();
3753
					Jetpack::state( 'error', $error );
3754
					Jetpack::state( 'error', $registered->get_error_message() );
3755
					break;
3756
				}
3757
3758
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3759
3760
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3761
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3762
			case 'activate' :
3763
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3764
					$error = 'cheatin';
3765
					break;
3766
				}
3767
3768
				$module = stripslashes( $_GET['module'] );
3769
				check_admin_referer( "jetpack_activate-$module" );
3770
				Jetpack::log( 'activate', $module );
3771
				Jetpack::activate_module( $module );
3772
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3773
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3774
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3775
			case 'activate_default_modules' :
3776
				check_admin_referer( 'activate_default_modules' );
3777
				Jetpack::log( 'activate_default_modules' );
3778
				Jetpack::restate();
3779
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3780
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3781
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3782
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3783
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3784
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3785
			case 'disconnect' :
3786
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3787
					$error = 'cheatin';
3788
					break;
3789
				}
3790
3791
				check_admin_referer( 'jetpack-disconnect' );
3792
				Jetpack::log( 'disconnect' );
3793
				Jetpack::disconnect();
3794
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3795
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3796
			case 'reconnect' :
3797
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3798
					$error = 'cheatin';
3799
					break;
3800
				}
3801
3802
				check_admin_referer( 'jetpack-reconnect' );
3803
				Jetpack::log( 'reconnect' );
3804
				$this->disconnect();
3805
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3806
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3807 View Code Duplication
			case 'deactivate' :
3808
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3809
					$error = 'cheatin';
3810
					break;
3811
				}
3812
3813
				$modules = stripslashes( $_GET['module'] );
3814
				check_admin_referer( "jetpack_deactivate-$modules" );
3815
				foreach ( explode( ',', $modules ) as $module ) {
3816
					Jetpack::log( 'deactivate', $module );
3817
					Jetpack::deactivate_module( $module );
3818
					Jetpack::state( 'message', 'module_deactivated' );
3819
				}
3820
				Jetpack::state( 'module', $modules );
3821
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3822
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3823
			case 'unlink' :
3824
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3825
				check_admin_referer( 'jetpack-unlink' );
3826
				Jetpack::log( 'unlink' );
3827
				$this->unlink_user();
3828
				Jetpack::state( 'message', 'unlinked' );
3829
				if ( 'sub-unlink' == $redirect ) {
3830
					wp_safe_redirect( admin_url() );
3831
				} else {
3832
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3833
				}
3834
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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