Completed
Push — update/remove-manage-module ( 76347c...953431 )
by
unknown
247:47 queued 240:03
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

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