Completed
Push — update/woo-analytics-enqueue ( 2a82d5...d184ac )
by Jeremy
07:21
created

class.jetpack.php (1 issue)

Severity

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
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $xmlrpc_verification = null;
44
	private $rest_authentication_status = null;
45
46
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
47
48
	private $tracking;
49
50
	/**
51
	 * @var array The handles of styles that are concatenated into jetpack.css.
52
	 *
53
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
54
	 */
55
	public $concatenated_style_handles = array(
56
		'jetpack-carousel',
57
		'grunion.css',
58
		'the-neverending-homepage',
59
		'jetpack_likes',
60
		'jetpack_related-posts',
61
		'sharedaddy',
62
		'jetpack-slideshow',
63
		'presentations',
64
		'quiz',
65
		'jetpack-subscriptions',
66
		'jetpack-responsive-videos-style',
67
		'jetpack-social-menu',
68
		'tiled-gallery',
69
		'jetpack_display_posts_widget',
70
		'gravatar-profile-widget',
71
		'goodreads-widget',
72
		'jetpack_social_media_icons_widget',
73
		'jetpack-top-posts-widget',
74
		'jetpack_image_widget',
75
		'jetpack-my-community-widget',
76
		'jetpack-authors-widget',
77
		'wordads',
78
		'eu-cookie-law-style',
79
		'flickr-widget-style',
80
		'jetpack-search-widget',
81
		'jetpack-simple-payments-widget-style',
82
		'jetpack-widget-social-icons-styles',
83
	);
84
85
	/**
86
	 * The handles of scripts that can be loaded asynchronously.
87
	 *
88
	 * @var array
89
	 */
90
	public $async_script_handles = array(
91
		'woocommerce-analytics',
92
	);
93
94
	/**
95
	 * Contains all assets that have had their URL rewritten to minified versions.
96
	 *
97
	 * @var array
98
	 */
99
	static $min_assets = array();
100
101
	public $plugins_to_deactivate = array(
102
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
104
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
105
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
106
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
107
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
108
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
109
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
110
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
111
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
112
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
113
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
114
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
115
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
116
	);
117
118
	/**
119
	 * Map of roles we care about, and their corresponding minimum capabilities.
120
	 *
121
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
122
	 *
123
	 * @access public
124
	 * @static
125
	 *
126
	 * @var array
127
	 */
128
	public static $capability_translations = array(
129
		'administrator' => 'manage_options',
130
		'editor'        => 'edit_others_posts',
131
		'author'        => 'publish_posts',
132
		'contributor'   => 'edit_posts',
133
		'subscriber'    => 'read',
134
	);
135
136
	/**
137
	 * Map of modules that have conflicts with plugins and should not be auto-activated
138
	 * if the plugins are active.  Used by filter_default_modules
139
	 *
140
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
141
	 * change `module-slug` and add this to your plugin:
142
	 *
143
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
144
	 * function my_jetpack_get_default_modules( $modules ) {
145
	 *     return array_diff( $modules, array( 'module-slug' ) );
146
	 * }
147
	 *
148
	 * @var array
149
	 */
150
	private $conflicting_plugins = array(
151
		'comments'          => array(
152
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
153
			'Disqus'                               => 'disqus-comment-system/disqus.php',
154
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
155
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
156
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
157
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
158
		),
159
		'comment-likes' => array(
160
			'Epoch'                                => 'epoch/plugincore.php',
161
		),
162
		'contact-form'      => array(
163
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
164
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
165
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
166
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
167
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
168
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
169
		),
170
		'minileven'         => array(
171
			'WPtouch'                              => 'wptouch/wptouch.php',
172
		),
173
		'latex'             => array(
174
			'LaTeX for WordPress'                  => 'latex/latex.php',
175
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
176
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
177
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
178
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
179
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
180
		),
181
		'protect'           => array(
182
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
183
			'Captcha'                              => 'captcha/captcha.php',
184
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
185
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
186
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
187
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
188
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
189
			'Security-protection'                  => 'security-protection/security-protection.php',
190
			'Login Security'                       => 'login-security/login-security.php',
191
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
192
			'Wordfence Security'                   => 'wordfence/wordfence.php',
193
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
194
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
195
		),
196
		'random-redirect'   => array(
197
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
198
		),
199
		'related-posts'     => array(
200
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
201
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
202
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
203
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
204
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
205
			'outbrain'                             => 'outbrain/outbrain.php',
206
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
207
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
208
		),
209
		'sharedaddy'        => array(
210
			'AddThis'                              => 'addthis/addthis_social_widget.php',
211
			'Add To Any'                           => 'add-to-any/add-to-any.php',
212
			'ShareThis'                            => 'share-this/sharethis.php',
213
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
214
		),
215
		'seo-tools' => array(
216
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'                    => 'autodescription/autodescription.php',
221
		),
222
		'verification-tools' => array(
223
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
224
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
225
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
226
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
227
			'The SEO Framework'                    => 'autodescription/autodescription.php',
228
		),
229
		'widget-visibility' => array(
230
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
231
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
232
		),
233
		'sitemaps' => array(
234
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
235
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
236
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
237
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
238
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
239
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
240
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
241
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
242
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
243
			'The SEO Framework'                    => 'autodescription/autodescription.php',
244
			'Sitemap'                              => 'sitemap/sitemap.php',
245
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
246
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
247
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
248
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
249
		),
250
		'lazy-images' => array(
251
			'Lazy Load'              => 'lazy-load/lazy-load.php',
252
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
253
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
254
		),
255
	);
256
257
	/**
258
	 * Plugins for which we turn off our Facebook OG Tags implementation.
259
	 *
260
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
261
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
262
	 *
263
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
264
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
265
	 */
266
	private $open_graph_conflicting_plugins = array(
267
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
268
		                                                         // 2 Click Social Media Buttons
269
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
270
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
271
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
272
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
273
		                                                         // Open Graph Meta Tags by Heateor
274
		'facebook/facebook.php',                                 // Facebook (official plugin)
275
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
276
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
277
		                                                         // Facebook Featured Image & OG Meta Tags
278
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
279
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
280
		                                                         // Facebook Open Graph Meta Tags for WordPress
281
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
282
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
283
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
284
		                                                         // Fedmich's Facebook Open Graph Meta
285
		'network-publisher/networkpub.php',                      // Network Publisher
286
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
287
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
288
		                                                         // NextScripts SNAP
289
		'og-tags/og-tags.php',                                   // OG Tags
290
		'opengraph/opengraph.php',                               // Open Graph
291
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
292
		                                                         // Open Graph Protocol Framework
293
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
294
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
295
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
296
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
297
		'sharepress/sharepress.php',                             // SharePress
298
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
299
		'social-discussions/social-discussions.php',             // Social Discussions
300
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
301
		'socialize/socialize.php',                               // Socialize
302
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
303
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
304
		                                                         // Tweet, Like, Google +1 and Share
305
		'wordbooker/wordbooker.php',                             // Wordbooker
306
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
307
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
308
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
309
		                                                         // WP Facebook Like Send & Open Graph Meta
310
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
311
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
312
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
313
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
314
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
315
	);
316
317
	/**
318
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
319
	 */
320
	private $twitter_cards_conflicting_plugins = array(
321
	//	'twitter/twitter.php',                       // The official one handles this on its own.
322
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
323
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
324
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
325
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
326
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
327
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
328
		'twitter-cards/twitter-cards.php',           // Twitter Cards
329
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
330
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
331
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
332
	);
333
334
	/**
335
	 * Message to display in admin_notice
336
	 * @var string
337
	 */
338
	public $message = '';
339
340
	/**
341
	 * Error to display in admin_notice
342
	 * @var string
343
	 */
344
	public $error = '';
345
346
	/**
347
	 * Modules that need more privacy description.
348
	 * @var string
349
	 */
350
	public $privacy_checks = '';
351
352
	/**
353
	 * Stats to record once the page loads
354
	 *
355
	 * @var array
356
	 */
357
	public $stats = array();
358
359
	/**
360
	 * Jetpack_Sync object
361
	 */
362
	public $sync;
363
364
	/**
365
	 * Verified data for JSON authorization request
366
	 */
367
	public $json_api_authorization_request = array();
368
369
	/**
370
	 * @var \Automattic\Jetpack\Connection\Manager
371
	 */
372
	protected $connection_manager;
373
374
	/**
375
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
376
	 */
377
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
378
379
	/**
380
	 * Holds the singleton instance of this class
381
	 * @since 2.3.3
382
	 * @var Jetpack
383
	 */
384
	static $instance = false;
385
386
	/**
387
	 * Singleton
388
	 * @static
389
	 */
390
	public static function init() {
391
		if ( ! self::$instance ) {
392
			self::$instance = new Jetpack;
393
394
			self::$instance->plugin_upgrade();
395
		}
396
397
		return self::$instance;
398
	}
399
400
	/**
401
	 * Must never be called statically
402
	 */
403
	function plugin_upgrade() {
404
		if ( Jetpack::is_active() ) {
405
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
406
			if ( JETPACK__VERSION != $version ) {
407
				// Prevent multiple upgrades at once - only a single process should trigger
408
				// an upgrade to avoid stampedes
409
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
410
					return;
411
				}
412
413
				// Set a short lock to prevent multiple instances of the upgrade
414
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
415
416
				// check which active modules actually exist and remove others from active_modules list
417
				$unfiltered_modules = Jetpack::get_active_modules();
418
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
419
				if ( array_diff( $unfiltered_modules, $modules ) ) {
420
					Jetpack::update_active_modules( $modules );
421
				}
422
423
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
424
425
				// Upgrade to 4.3.0
426
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
427
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
428
				}
429
430
				// Make sure Markdown for posts gets turned back on
431
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
432
					update_option( 'wpcom_publish_posts_with_markdown', true );
433
				}
434
435
				if ( did_action( 'wp_loaded' ) ) {
436
					self::upgrade_on_load();
437
				} else {
438
					add_action(
439
						'wp_loaded',
440
						array( __CLASS__, 'upgrade_on_load' )
441
					);
442
				}
443
			}
444
		}
445
	}
446
447
	/**
448
	 * Runs upgrade routines that need to have modules loaded.
449
	 */
450
	static function upgrade_on_load() {
451
452
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
453
		// This can happen in case Jetpack has been just upgraded and is
454
		// being initialized late during the page load. In this case we wait
455
		// until the next proper admin page load with Jetpack active.
456
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
457
			delete_transient( self::$plugin_upgrade_lock_key );
458
459
			return;
460
		}
461
462
		Jetpack::maybe_set_version_option();
463
464
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
465
			Jetpack_Widget_Conditions::migrate_post_type_rules();
466
		}
467
468
		if (
469
			class_exists( 'Jetpack_Sitemap_Manager' )
470
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
471
		) {
472
			do_action( 'jetpack_sitemaps_purge_data' );
473
		}
474
475
		// Delete old stats cache
476
		delete_option( 'jetpack_restapi_stats_cache' );
477
478
		delete_transient( self::$plugin_upgrade_lock_key );
479
	}
480
481
	/**
482
	 * Saves all the currently active modules to options.
483
	 * Also fires Action hooks for each newly activated and deactivated module.
484
	 *
485
	 * @param $modules Array Array of active modules to be saved in options.
486
	 *
487
	 * @return $success bool true for success, false for failure.
488
	 */
489
	static function update_active_modules( $modules ) {
490
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
491
		$active_modules       = Jetpack::get_active_modules();
492
		$new_active_modules   = array_diff( $modules, $current_modules );
493
		$new_inactive_modules = array_diff( $active_modules, $modules );
494
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
495
		$reindexed_modules    = array_values( $new_current_modules );
496
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
497
498
		foreach ( $new_active_modules as $module ) {
499
			/**
500
			 * Fires when a specific module is activated.
501
			 *
502
			 * @since 1.9.0
503
			 *
504
			 * @param string $module Module slug.
505
			 * @param boolean $success whether the module was activated. @since 4.2
506
			 */
507
			do_action( 'jetpack_activate_module', $module, $success );
508
			/**
509
			 * Fires when a module is activated.
510
			 * The dynamic part of the filter, $module, is the module slug.
511
			 *
512
			 * @since 1.9.0
513
			 *
514
			 * @param string $module Module slug.
515
			 */
516
			do_action( "jetpack_activate_module_$module", $module );
517
		}
518
519
		foreach ( $new_inactive_modules as $module ) {
520
			/**
521
			 * Fired after a module has been deactivated.
522
			 *
523
			 * @since 4.2.0
524
			 *
525
			 * @param string $module Module slug.
526
			 * @param boolean $success whether the module was deactivated.
527
			 */
528
			do_action( 'jetpack_deactivate_module', $module, $success );
529
			/**
530
			 * Fires when a module is deactivated.
531
			 * The dynamic part of the filter, $module, is the module slug.
532
			 *
533
			 * @since 1.9.0
534
			 *
535
			 * @param string $module Module slug.
536
			 */
537
			do_action( "jetpack_deactivate_module_$module", $module );
538
		}
539
540
		return $success;
541
	}
542
543
	static function delete_active_modules() {
544
		self::update_active_modules( array() );
545
	}
546
547
	/**
548
	 * Constructor.  Initializes WordPress hooks
549
	 */
550
	private function __construct() {
551
		/*
552
		 * Check for and alert any deprecated hooks
553
		 */
554
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
555
556
		/*
557
		 * Enable enhanced handling of previewing sites in Calypso
558
		 */
559
		if ( Jetpack::is_active() ) {
560
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
561
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
562
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
563
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
564
		}
565
566
		if ( self::jetpack_tos_agreed() ) {
567
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
568
			add_action( 'init', array( $tracking, 'init' ) );
569
		}
570
571
		/*
572
		 * Load things that should only be in Network Admin.
573
		 *
574
		 * For now blow away everything else until a more full
575
		 * understanding of what is needed at the network level is
576
		 * available
577
		 */
578
		if ( is_multisite() ) {
579
			Jetpack_Network::init();
580
		}
581
582
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
583
			return function() {
584
				return wp_generate_password( 32, false );
585
			};
586
		} );
587
588
		$this->connection_manager = new Connection_Manager( );
589
590
		/**
591
		 * Prepare Gutenberg Editor functionality
592
		 */
593
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
594
		Jetpack_Gutenberg::init();
595
		Jetpack_Gutenberg::load_independent_blocks();
596
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
597
598
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
599
600
		// Unlink user before deleting the user from .com
601
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
602
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
603
604
		$is_jetpack_xmlrpc_request = $this->setup_xmlrpc_handlers( $_GET, Jetpack::is_active(), $this->verify_xml_rpc_signature() );
605
606
		if ( $is_jetpack_xmlrpc_request ) {
607
			// pass
608
		} elseif (
609
			is_admin() &&
610
			isset( $_POST['action'] ) && (
611
				'jetpack_upload_file' == $_POST['action'] ||
612
				'jetpack_update_file' == $_POST['action']
613
			)
614
		) {
615
			$this->require_jetpack_authentication();
616
			$this->add_remote_request_handlers();
617
		} else {
618
			if ( Jetpack::is_active() ) {
619
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
620
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
621
			} else {
622
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
623
			}
624
		}
625
626
		if ( Jetpack::is_active() ) {
627
			Jetpack_Heartbeat::init();
628
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
629
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
630
				Jetpack_Search_Performance_Logger::init();
631
			}
632
		}
633
634
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
635
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
636
637
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
638
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
639
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
640
		}
641
642
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
643
644
		add_action( 'admin_init', array( $this, 'admin_init' ) );
645
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
646
647
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
648
649
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
650
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
651
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
652
653
		// returns HTTPS support status
654
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
655
656
		// JITM AJAX callback function
657
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
658
659
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
660
661
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
662
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
663
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
664
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
665
666
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
667
668
		/**
669
		 * These actions run checks to load additional files.
670
		 * They check for external files or plugins, so they need to run as late as possible.
671
		 */
672
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
673
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
674
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
675
676
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
677
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
678
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
679
680
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
681
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
682
683
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
684
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
685
686
		// A filter to control all just in time messages
687
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
688
689
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
690
691
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
692
		// We should make sure to only do this for front end links.
693
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
694
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
695
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
696
697
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
698
			//so they point moderation links on emails to Calypso
699
			jetpack_require_lib( 'functions.wp-notify' );
700
		}
701
702
		// Hide edit post link if mobile app.
703
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
704
			add_filter( 'edit_post_link', '__return_empty_string' );
705
		}
706
707
		// Update the Jetpack plan from API on heartbeats
708
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
709
710
		/**
711
		 * This is the hack to concatenate all css files into one.
712
		 * For description and reasoning see the implode_frontend_css method
713
		 *
714
		 * Super late priority so we catch all the registered styles
715
		 */
716
		if( !is_admin() ) {
717
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
718
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
719
		}
720
721
722
		/**
723
		 * These are sync actions that we need to keep track of for jitms
724
		 */
725
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
726
727
		// Actually push the stats on shutdown.
728
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
729
			add_action( 'shutdown', array( $this, 'push_stats' ) );
730
		}
731
732
		/*
733
		 * Load some scripts asynchronously.
734
		 */
735
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
736
	}
737
738
	function setup_xmlrpc_handlers( $request_params, $is_active, $is_signed, Jetpack_XMLRPC_Server $xmlrpc_server = null ) {
739
		if ( ! isset( $request_params['for'] ) || 'jetpack' != $request_params['for'] ) {
740
			return false;
741
		}
742
743
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
744
		if ( isset( $request_params['jetpack'] ) && 'comms' == $request_params['jetpack'] ) {
745
			if ( ! Constants::is_defined( 'XMLRPC_REQUEST' ) ) {
746
				// Use the real constant here for WordPress' sake.
747
				define( 'XMLRPC_REQUEST', true );
748
			}
749
750
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
751
752
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
753
		}
754
755
		if ( ! Constants::get_constant( 'XMLRPC_REQUEST' ) ) {
756
			return false;
757
		}
758
759
		@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
760
761
		if ( $xmlrpc_server ) {
762
			$this->xmlrpc_server = $xmlrpc_server;
763
		} else {
764
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
765
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
766
		}
767
768
		$this->require_jetpack_authentication();
769
770
		if ( $is_active ) {
771
			// Hack to preserve $HTTP_RAW_POST_DATA
772
			add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
773
774
			if ( $is_signed ) {
775
				// The actual API methods.
776
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
777
			} else {
778
				// The jetpack.authorize method should be available for unauthenticated users on a site with an
779
				// active Jetpack connection, so that additional users can link their account.
780
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
781
			}
782
		} else {
783
			// The bootstrap API methods.
784
			add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
785
786
			new XMLRPC_Connector( $this->connection_manager );
787
788
			if ( $is_signed ) {
789
				// the jetpack Provision method is available for blog-token-signed requests
790
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
791
			}
792
		}
793
794
		// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
795
		add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
796
797
		return true;
798
	}
799
800
	function initialize_rest_api_registration_connector() {
801
		new REST_Connector( $this->connection_manager );
802
	}
803
804
	/**
805
	 * This is ported over from the manage module, which has been deprecated and baked in here.
806
	 *
807
	 * @param $domains
808
	 */
809
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
810
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
811
	}
812
813
	/**
814
	 * Return $domains, with 'wordpress.com' appended.
815
	 * This is ported over from the manage module, which has been deprecated and baked in here.
816
	 *
817
	 * @param $domains
818
	 * @return array
819
	 */
820
	function allow_wpcom_domain( $domains ) {
821
		if ( empty( $domains ) ) {
822
			$domains = array();
823
		}
824
		$domains[] = 'wordpress.com';
825
		return array_unique( $domains );
826
	}
827
828
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
829
		$post = get_post( $post_id );
830
831
		if ( empty( $post ) ) {
832
			return $default_url;
833
		}
834
835
		$post_type = $post->post_type;
836
837
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
838
		// https://en.support.wordpress.com/custom-post-types/
839
		$allowed_post_types = array(
840
			'post' => 'post',
841
			'page' => 'page',
842
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
843
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
844
		);
845
846
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
847
			return $default_url;
848
		}
849
850
		$path_prefix = $allowed_post_types[ $post_type ];
851
852
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
853
854
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
855
	}
856
857
	function point_edit_comment_links_to_calypso( $url ) {
858
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
859
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
860
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
861
			Jetpack::build_raw_urls( get_home_url() ),
862
			$query_args['amp;c']
863
		) );
864
	}
865
866
	function jetpack_track_last_sync_callback( $params ) {
867
		/**
868
		 * Filter to turn off jitm caching
869
		 *
870
		 * @since 5.4.0
871
		 *
872
		 * @param bool false Whether to cache just in time messages
873
		 */
874
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
875
			return $params;
876
		}
877
878
		if ( is_array( $params ) && isset( $params[0] ) ) {
879
			$option = $params[0];
880
			if ( 'active_plugins' === $option ) {
881
				// use the cache if we can, but not terribly important if it gets evicted
882
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
883
			}
884
		}
885
886
		return $params;
887
	}
888
889
	function jetpack_connection_banner_callback() {
890
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
891
892
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
893
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
894
			wp_send_json_success();
895
		}
896
897
		wp_die();
898
	}
899
900
	/**
901
	 * Removes all XML-RPC methods that are not `jetpack.*`.
902
	 * Only used in our alternate XML-RPC endpoint, where we want to
903
	 * ensure that Core and other plugins' methods are not exposed.
904
	 *
905
	 * @param array $methods
906
	 * @return array filtered $methods
907
	 */
908
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
909
		$jetpack_methods = array();
910
911
		foreach ( $methods as $method => $callback ) {
912
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
913
				$jetpack_methods[ $method ] = $callback;
914
			}
915
		}
916
917
		return $jetpack_methods;
918
	}
919
920
	/**
921
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
922
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
923
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
924
	 * which is accessible via a different URI. Most of the below is copied directly
925
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
926
	 */
927
	function alternate_xmlrpc() {
928
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
929
		global $HTTP_RAW_POST_DATA;
930
931
		// Some browser-embedded clients send cookies. We don't want them.
932
		$_COOKIE = array();
933
934
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
935
		// but we can do it ourself.
936
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
937
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
938
		}
939
940
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
941
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
942
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
943
		}
944
945
		// phpcs:enable
946
947
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
948
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
949
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
950
951
		/**
952
		 * Filters the class used for handling XML-RPC requests.
953
		 *
954
		 * @since 3.1.0
955
		 *
956
		 * @param string $class The name of the XML-RPC server class.
957
		 */
958
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
959
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
960
961
		// Fire off the request
962
		nocache_headers();
963
		$wp_xmlrpc_server->serve_request();
964
965
		exit;
966
	}
967
968
	/**
969
	 * The callback for the JITM ajax requests.
970
	 */
971
	function jetpack_jitm_ajax_callback() {
972
		// Check for nonce
973
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
974
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
975
		}
976
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
977
			$module_slug = $_REQUEST['jitmModule'];
978
			Jetpack::log( 'activate', $module_slug );
979
			Jetpack::activate_module( $module_slug, false, false );
980
			Jetpack::state( 'message', 'no_message' );
981
982
			//A Jetpack module is being activated through a JITM, track it
983
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
984
			$this->do_stats( 'server_side' );
985
986
			wp_send_json_success();
987
		}
988
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
989
			// get the hide_jitm options array
990
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
991
			$module_slug = $_REQUEST['jitmModule'];
992
993
			if( ! $jetpack_hide_jitm ) {
994
				$jetpack_hide_jitm = array(
995
					$module_slug => 'hide'
996
				);
997
			} else {
998
				$jetpack_hide_jitm[$module_slug] = 'hide';
999
			}
1000
1001
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
1002
1003
			//jitm is being dismissed forever, track it
1004
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
1005
			$this->do_stats( 'server_side' );
1006
1007
			wp_send_json_success();
1008
		}
1009 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
1010
			$module_slug = $_REQUEST['jitmModule'];
1011
1012
			// User went to WordPress.com, track this
1013
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
1014
			$this->do_stats( 'server_side' );
1015
1016
			wp_send_json_success();
1017
		}
1018 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
1019
			$track = $_REQUEST['jitmModule'];
1020
1021
			// User is viewing JITM, track it.
1022
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
1023
			$this->do_stats( 'server_side' );
1024
1025
			wp_send_json_success();
1026
		}
1027
	}
1028
1029
	/**
1030
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1031
	 */
1032
	function push_stats() {
1033
		if ( ! empty( $this->stats ) ) {
1034
			$this->do_stats( 'server_side' );
1035
		}
1036
	}
1037
1038
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1039
		switch( $cap ) {
1040
			case 'jetpack_connect' :
1041
			case 'jetpack_reconnect' :
1042
				if ( Jetpack::is_development_mode() ) {
1043
					$caps = array( 'do_not_allow' );
1044
					break;
1045
				}
1046
				/**
1047
				 * Pass through. If it's not development mode, these should match disconnect.
1048
				 * Let users disconnect if it's development mode, just in case things glitch.
1049
				 */
1050
			case 'jetpack_disconnect' :
1051
				/**
1052
				 * In multisite, can individual site admins manage their own connection?
1053
				 *
1054
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1055
				 */
1056
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1057
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1058
						/**
1059
						 * We need to update the option name -- it's terribly unclear which
1060
						 * direction the override goes.
1061
						 *
1062
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1063
						 */
1064
						$caps = array( 'do_not_allow' );
1065
						break;
1066
					}
1067
				}
1068
1069
				$caps = array( 'manage_options' );
1070
				break;
1071
			case 'jetpack_manage_modules' :
1072
			case 'jetpack_activate_modules' :
1073
			case 'jetpack_deactivate_modules' :
1074
				$caps = array( 'manage_options' );
1075
				break;
1076
			case 'jetpack_configure_modules' :
1077
				$caps = array( 'manage_options' );
1078
				break;
1079
			case 'jetpack_manage_autoupdates' :
1080
				$caps = array(
1081
					'manage_options',
1082
					'update_plugins',
1083
				);
1084
				break;
1085
			case 'jetpack_network_admin_page':
1086
			case 'jetpack_network_settings_page':
1087
				$caps = array( 'manage_network_plugins' );
1088
				break;
1089
			case 'jetpack_network_sites_page':
1090
				$caps = array( 'manage_sites' );
1091
				break;
1092
			case 'jetpack_admin_page' :
1093
				if ( Jetpack::is_development_mode() ) {
1094
					$caps = array( 'manage_options' );
1095
					break;
1096
				} else {
1097
					$caps = array( 'read' );
1098
				}
1099
				break;
1100
			case 'jetpack_connect_user' :
1101
				if ( Jetpack::is_development_mode() ) {
1102
					$caps = array( 'do_not_allow' );
1103
					break;
1104
				}
1105
				$caps = array( 'read' );
1106
				break;
1107
		}
1108
		return $caps;
1109
	}
1110
1111
	function require_jetpack_authentication() {
1112
		// Don't let anyone authenticate
1113
		$_COOKIE = array();
1114
		remove_all_filters( 'authenticate' );
1115
		remove_all_actions( 'wp_login_failed' );
1116
1117
		if ( Jetpack::is_active() ) {
1118
			// Allow Jetpack authentication
1119
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1120
		}
1121
	}
1122
1123
	/**
1124
	 * Load language files
1125
	 * @action plugins_loaded
1126
	 */
1127
	public static function plugin_textdomain() {
1128
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1129
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1130
	}
1131
1132
	/**
1133
	 * Register assets for use in various modules and the Jetpack admin page.
1134
	 *
1135
	 * @uses wp_script_is, wp_register_script, plugins_url
1136
	 * @action wp_loaded
1137
	 * @return null
1138
	 */
1139
	public function register_assets() {
1140
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1141
			wp_register_script(
1142
				'spin',
1143
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1144
				false,
1145
				'1.3'
1146
			);
1147
		}
1148
1149 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1150
			wp_register_script(
1151
				'jquery.spin',
1152
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1153
				array( 'jquery', 'spin' ),
1154
				'1.3'
1155
			);
1156
		}
1157
1158 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1159
			wp_register_script(
1160
				'jetpack-gallery-settings',
1161
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1162
				array( 'media-views' ),
1163
				'20121225'
1164
			);
1165
		}
1166
1167 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1168
			wp_register_script(
1169
				'jetpack-twitter-timeline',
1170
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1171
				array( 'jquery' ),
1172
				'4.0.0',
1173
				true
1174
			);
1175
		}
1176
1177
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1178
			wp_register_script(
1179
				'jetpack-facebook-embed',
1180
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1181
				array( 'jquery' ),
1182
				null,
1183
				true
1184
			);
1185
1186
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1187
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1188
			if ( ! is_numeric( $fb_app_id ) ) {
1189
				$fb_app_id = '';
1190
			}
1191
			wp_localize_script(
1192
				'jetpack-facebook-embed',
1193
				'jpfbembed',
1194
				array(
1195
					'appid' => $fb_app_id,
1196
					'locale' => $this->get_locale(),
1197
				)
1198
			);
1199
		}
1200
1201
		/**
1202
		 * As jetpack_register_genericons is by default fired off a hook,
1203
		 * the hook may have already fired by this point.
1204
		 * So, let's just trigger it manually.
1205
		 */
1206
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1207
		jetpack_register_genericons();
1208
1209
		/**
1210
		 * Register the social logos
1211
		 */
1212
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1213
		jetpack_register_social_logos();
1214
1215 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1216
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1217
	}
1218
1219
	/**
1220
	 * Guess locale from language code.
1221
	 *
1222
	 * @param string $lang Language code.
1223
	 * @return string|bool
1224
	 */
1225 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1226
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1227
			return 'en_US';
1228
		}
1229
1230
		if ( ! class_exists( 'GP_Locales' ) ) {
1231
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1232
				return false;
1233
			}
1234
1235
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1236
		}
1237
1238
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1239
			// WP.com: get_locale() returns 'it'
1240
			$locale = GP_Locales::by_slug( $lang );
1241
		} else {
1242
			// Jetpack: get_locale() returns 'it_IT';
1243
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1244
		}
1245
1246
		if ( ! $locale ) {
1247
			return false;
1248
		}
1249
1250
		if ( empty( $locale->facebook_locale ) ) {
1251
			if ( empty( $locale->wp_locale ) ) {
1252
				return false;
1253
			} else {
1254
				// Facebook SDK is smart enough to fall back to en_US if a
1255
				// locale isn't supported. Since supported Facebook locales
1256
				// can fall out of sync, we'll attempt to use the known
1257
				// wp_locale value and rely on said fallback.
1258
				return $locale->wp_locale;
1259
			}
1260
		}
1261
1262
		return $locale->facebook_locale;
1263
	}
1264
1265
	/**
1266
	 * Get the locale.
1267
	 *
1268
	 * @return string|bool
1269
	 */
1270
	function get_locale() {
1271
		$locale = $this->guess_locale_from_lang( get_locale() );
1272
1273
		if ( ! $locale ) {
1274
			$locale = 'en_US';
1275
		}
1276
1277
		return $locale;
1278
	}
1279
1280
	/**
1281
	 * Device Pixels support
1282
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1283
	 */
1284
	function devicepx() {
1285
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1286
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1287
		}
1288
	}
1289
1290
	/**
1291
	 * Return the network_site_url so that .com knows what network this site is a part of.
1292
	 * @param  bool $option
1293
	 * @return string
1294
	 */
1295
	public function jetpack_main_network_site_option( $option ) {
1296
		return network_site_url();
1297
	}
1298
	/**
1299
	 * Network Name.
1300
	 */
1301
	static function network_name( $option = null ) {
1302
		global $current_site;
1303
		return $current_site->site_name;
1304
	}
1305
	/**
1306
	 * Does the network allow new user and site registrations.
1307
	 * @return string
1308
	 */
1309
	static function network_allow_new_registrations( $option = null ) {
1310
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1311
	}
1312
	/**
1313
	 * Does the network allow admins to add new users.
1314
	 * @return boolian
1315
	 */
1316
	static function network_add_new_users( $option = null ) {
1317
		return (bool) get_site_option( 'add_new_users' );
1318
	}
1319
	/**
1320
	 * File upload psace left per site in MB.
1321
	 *  -1 means NO LIMIT.
1322
	 * @return number
1323
	 */
1324
	static function network_site_upload_space( $option = null ) {
1325
		// value in MB
1326
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1327
	}
1328
1329
	/**
1330
	 * Network allowed file types.
1331
	 * @return string
1332
	 */
1333
	static function network_upload_file_types( $option = null ) {
1334
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1335
	}
1336
1337
	/**
1338
	 * Maximum file upload size set by the network.
1339
	 * @return number
1340
	 */
1341
	static function network_max_upload_file_size( $option = null ) {
1342
		// value in KB
1343
		return get_site_option( 'fileupload_maxk', 300 );
1344
	}
1345
1346
	/**
1347
	 * Lets us know if a site allows admins to manage the network.
1348
	 * @return array
1349
	 */
1350
	static function network_enable_administration_menus( $option = null ) {
1351
		return get_site_option( 'menu_items' );
1352
	}
1353
1354
	/**
1355
	 * If a user has been promoted to or demoted from admin, we need to clear the
1356
	 * jetpack_other_linked_admins transient.
1357
	 *
1358
	 * @since 4.3.2
1359
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1360
	 *
1361
	 * @param int    $user_id   The user ID whose role changed.
1362
	 * @param string $role      The new role.
1363
	 * @param array  $old_roles An array of the user's previous roles.
1364
	 */
1365
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1366
		if ( 'administrator' == $role
1367
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1368
			|| is_null( $old_roles )
1369
		) {
1370
			delete_transient( 'jetpack_other_linked_admins' );
1371
		}
1372
	}
1373
1374
	/**
1375
	 * Checks to see if there are any other users available to become primary
1376
	 * Users must both:
1377
	 * - Be linked to wpcom
1378
	 * - Be an admin
1379
	 *
1380
	 * @return mixed False if no other users are linked, Int if there are.
1381
	 */
1382
	static function get_other_linked_admins() {
1383
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1384
1385
		if ( false === $other_linked_users ) {
1386
			$admins = get_users( array( 'role' => 'administrator' ) );
1387
			if ( count( $admins ) > 1 ) {
1388
				$available = array();
1389
				foreach ( $admins as $admin ) {
1390
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1391
						$available[] = $admin->ID;
1392
					}
1393
				}
1394
1395
				$count_connected_admins = count( $available );
1396
				if ( count( $available ) > 1 ) {
1397
					$other_linked_users = $count_connected_admins;
1398
				} else {
1399
					$other_linked_users = 0;
1400
				}
1401
			} else {
1402
				$other_linked_users = 0;
1403
			}
1404
1405
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1406
		}
1407
1408
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1409
	}
1410
1411
	/**
1412
	 * Return whether we are dealing with a multi network setup or not.
1413
	 * The reason we are type casting this is because we want to avoid the situation where
1414
	 * the result is false since when is_main_network_option return false it cases
1415
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1416
	 * database which could be set to anything as opposed to what this function returns.
1417
	 * @param  bool  $option
1418
	 *
1419
	 * @return boolean
1420
	 */
1421
	public function is_main_network_option( $option ) {
1422
		// return '1' or ''
1423
		return (string) (bool) Jetpack::is_multi_network();
1424
	}
1425
1426
	/**
1427
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1428
	 *
1429
	 * @param  string  $option
1430
	 * @return boolean
1431
	 */
1432
	public function is_multisite( $option ) {
1433
		return (string) (bool) is_multisite();
1434
	}
1435
1436
	/**
1437
	 * Implemented since there is no core is multi network function
1438
	 * Right now there is no way to tell if we which network is the dominant network on the system
1439
	 *
1440
	 * @since  3.3
1441
	 * @return boolean
1442
	 */
1443 View Code Duplication
	public static function is_multi_network() {
1444
		global  $wpdb;
1445
1446
		// if we don't have a multi site setup no need to do any more
1447
		if ( ! is_multisite() ) {
1448
			return false;
1449
		}
1450
1451
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1452
		if ( $num_sites > 1 ) {
1453
			return true;
1454
		} else {
1455
			return false;
1456
		}
1457
	}
1458
1459
	/**
1460
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1461
	 * @return null
1462
	 */
1463
	function update_jetpack_main_network_site_option() {
1464
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1465
	}
1466
	/**
1467
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1468
	 *
1469
	 */
1470
	function update_jetpack_network_settings() {
1471
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1472
		// Only sync this info for the main network site.
1473
	}
1474
1475
	/**
1476
	 * Get back if the current site is single user site.
1477
	 *
1478
	 * @return bool
1479
	 */
1480 View Code Duplication
	public static function is_single_user_site() {
1481
		global $wpdb;
1482
1483
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1484
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1485
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1486
		}
1487
		return 1 === (int) $some_users;
1488
	}
1489
1490
	/**
1491
	 * Returns true if the site has file write access false otherwise.
1492
	 * @return string ( '1' | '0' )
1493
	 **/
1494
	public static function file_system_write_access() {
1495
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1496
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1497
		}
1498
1499
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1500
1501
		$filesystem_method = get_filesystem_method();
1502
		if ( $filesystem_method === 'direct' ) {
1503
			return 1;
1504
		}
1505
1506
		ob_start();
1507
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1508
		ob_end_clean();
1509
		if ( $filesystem_credentials_are_stored ) {
1510
			return 1;
1511
		}
1512
		return 0;
1513
	}
1514
1515
	/**
1516
	 * Finds out if a site is using a version control system.
1517
	 * @return string ( '1' | '0' )
1518
	 **/
1519
	public static function is_version_controlled() {
1520
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1521
		return (string) (int) Functions::is_version_controlled();
1522
	}
1523
1524
	/**
1525
	 * Determines whether the current theme supports featured images or not.
1526
	 * @return string ( '1' | '0' )
1527
	 */
1528
	public static function featured_images_enabled() {
1529
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1530
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1531
	}
1532
1533
	/**
1534
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1535
	 *
1536
	 * @deprecated 4.7 use get_avatar_url instead.
1537
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1538
	 * @param int $size Size of the avatar image
1539
	 * @param string $default URL to a default image to use if no avatar is available
1540
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1541
	 *
1542
	 * @return array
1543
	 */
1544
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1546
		return get_avatar_url( $id_or_email, array(
1547
			'size' => $size,
1548
			'default' => $default,
1549
			'force_default' => $force_display,
1550
		) );
1551
	}
1552
1553
	/**
1554
	 * jetpack_updates is saved in the following schema:
1555
	 *
1556
	 * array (
1557
	 *      'plugins'                       => (int) Number of plugin updates available.
1558
	 *      'themes'                        => (int) Number of theme updates available.
1559
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1560
	 *      'translations'                  => (int) Number of translation updates available.
1561
	 *      'total'                         => (int) Total of all available updates.
1562
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1563
	 * )
1564
	 * @return array
1565
	 */
1566
	public static function get_updates() {
1567
		$update_data = wp_get_update_data();
1568
1569
		// Stores the individual update counts as well as the total count.
1570
		if ( isset( $update_data['counts'] ) ) {
1571
			$updates = $update_data['counts'];
1572
		}
1573
1574
		// If we need to update WordPress core, let's find the latest version number.
1575 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1576
			$cur = get_preferred_from_update_core();
1577
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1578
				$updates['wp_update_version'] = $cur->current;
1579
			}
1580
		}
1581
		return isset( $updates ) ? $updates : array();
1582
	}
1583
1584
	public static function get_update_details() {
1585
		$update_details = array(
1586
			'update_core' => get_site_transient( 'update_core' ),
1587
			'update_plugins' => get_site_transient( 'update_plugins' ),
1588
			'update_themes' => get_site_transient( 'update_themes' ),
1589
		);
1590
		return $update_details;
1591
	}
1592
1593
	public static function refresh_update_data() {
1594
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1595
1596
	}
1597
1598
	public static function refresh_theme_data() {
1599
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1600
	}
1601
1602
	/**
1603
	 * Is Jetpack active?
1604
	 */
1605
	public static function is_active() {
1606
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1607
	}
1608
1609
	/**
1610
	 * Make an API call to WordPress.com for plan status
1611
	 *
1612
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1613
	 *
1614
	 * @return bool True if plan is updated, false if no update
1615
	 */
1616
	public static function refresh_active_plan_from_wpcom() {
1617
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1618
		return Jetpack_Plan::refresh_from_wpcom();
1619
	}
1620
1621
	/**
1622
	 * Get the plan that this Jetpack site is currently using
1623
	 *
1624
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1625
	 * @return array Active Jetpack plan details.
1626
	 */
1627
	public static function get_active_plan() {
1628
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1629
		return Jetpack_Plan::get();
1630
	}
1631
1632
	/**
1633
	 * Determine whether the active plan supports a particular feature
1634
	 *
1635
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1636
	 * @return bool True if plan supports feature, false if not.
1637
	 */
1638
	public static function active_plan_supports( $feature ) {
1639
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1640
		return Jetpack_Plan::supports( $feature );
1641
	}
1642
1643
	/**
1644
	 * Is Jetpack in development (offline) mode?
1645
	 */
1646 View Code Duplication
	public static function is_development_mode() {
1647
		$development_mode = false;
1648
1649
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1650
			$development_mode = JETPACK_DEV_DEBUG;
1651
		} elseif ( $site_url = site_url() ) {
1652
			$development_mode = false === strpos( $site_url, '.' );
1653
		}
1654
1655
		/**
1656
		 * Filters Jetpack's development mode.
1657
		 *
1658
		 * @see https://jetpack.com/support/development-mode/
1659
		 *
1660
		 * @since 2.2.1
1661
		 *
1662
		 * @param bool $development_mode Is Jetpack's development mode active.
1663
		 */
1664
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1665
		return $development_mode;
1666
	}
1667
1668
	/**
1669
	 * Whether the site is currently onboarding or not.
1670
	 * A site is considered as being onboarded if it currently has an onboarding token.
1671
	 *
1672
	 * @since 5.8
1673
	 *
1674
	 * @access public
1675
	 * @static
1676
	 *
1677
	 * @return bool True if the site is currently onboarding, false otherwise
1678
	 */
1679
	public static function is_onboarding() {
1680
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1681
	}
1682
1683
	/**
1684
	 * Determines reason for Jetpack development mode.
1685
	 */
1686
	public static function development_mode_trigger_text() {
1687
		if ( ! Jetpack::is_development_mode() ) {
1688
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1689
		}
1690
1691
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1692
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1693
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1694
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1695
		} else {
1696
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1697
		}
1698
1699
		return $notice;
1700
1701
	}
1702
	/**
1703
	* Get Jetpack development mode notice text and notice class.
1704
	*
1705
	* Mirrors the checks made in Jetpack::is_development_mode
1706
	*
1707
	*/
1708
	public static function show_development_mode_notice() {
1709 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1710
			$notice = sprintf(
1711
			/* translators: %s is a URL */
1712
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1713
				'https://jetpack.com/support/development-mode/'
1714
			);
1715
1716
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1717
1718
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1719
		}
1720
1721
		// Throw up a notice if using a development version and as for feedback.
1722
		if ( Jetpack::is_development_version() ) {
1723
			/* translators: %s is a URL */
1724
			$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/' );
1725
1726
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1727
		}
1728
		// Throw up a notice if using staging mode
1729
		if ( Jetpack::is_staging_site() ) {
1730
			/* translators: %s is a URL */
1731
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1732
1733
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1734
		}
1735
	}
1736
1737
	/**
1738
	 * Whether Jetpack's version maps to a public release, or a development version.
1739
	 */
1740
	public static function is_development_version() {
1741
		/**
1742
		 * Allows filtering whether this is a development version of Jetpack.
1743
		 *
1744
		 * This filter is especially useful for tests.
1745
		 *
1746
		 * @since 4.3.0
1747
		 *
1748
		 * @param bool $development_version Is this a develoment version of Jetpack?
1749
		 */
1750
		return (bool) apply_filters(
1751
			'jetpack_development_version',
1752
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1753
		);
1754
	}
1755
1756
	/**
1757
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1758
	 */
1759
	public static function is_user_connected( $user_id = false ) {
1760
		return self::connection()->is_user_connected( $user_id );
1761
	}
1762
1763
	/**
1764
	 * Get the wpcom user data of the current|specified connected user.
1765
	 */
1766 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1767
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1768
		if ( ! $user_id ) {
1769
			$user_id = get_current_user_id();
1770
		}
1771
1772
		$transient_key = "jetpack_connected_user_data_$user_id";
1773
1774
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1775
			return $cached_user_data;
1776
		}
1777
1778
		Jetpack::load_xml_rpc_client();
1779
		$xml = new Jetpack_IXR_Client( array(
1780
			'user_id' => $user_id,
1781
		) );
1782
		$xml->query( 'wpcom.getUser' );
1783
		if ( ! $xml->isError() ) {
1784
			$user_data = $xml->getResponse();
1785
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1786
			return $user_data;
1787
		}
1788
1789
		return false;
1790
	}
1791
1792
	/**
1793
	 * Get the wpcom email of the current|specified connected user.
1794
	 */
1795 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1796
		if ( ! $user_id ) {
1797
			$user_id = get_current_user_id();
1798
		}
1799
		Jetpack::load_xml_rpc_client();
1800
		$xml = new Jetpack_IXR_Client( array(
1801
			'user_id' => $user_id,
1802
		) );
1803
		$xml->query( 'wpcom.getUserEmail' );
1804
		if ( ! $xml->isError() ) {
1805
			return $xml->getResponse();
1806
		}
1807
		return false;
1808
	}
1809
1810
	/**
1811
	 * Get the wpcom email of the master user.
1812
	 */
1813
	public static function get_master_user_email() {
1814
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1815
		if ( $master_user_id ) {
1816
			return self::get_connected_user_email( $master_user_id );
1817
		}
1818
		return '';
1819
	}
1820
1821
	function current_user_is_connection_owner() {
1822
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1823
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1824
	}
1825
1826
	/**
1827
	 * Gets current user IP address.
1828
	 *
1829
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1830
	 *
1831
	 * @return string                  Current user IP address.
1832
	 */
1833
	public static function current_user_ip( $check_all_headers = false ) {
1834
		if ( $check_all_headers ) {
1835
			foreach ( array(
1836
				'HTTP_CF_CONNECTING_IP',
1837
				'HTTP_CLIENT_IP',
1838
				'HTTP_X_FORWARDED_FOR',
1839
				'HTTP_X_FORWARDED',
1840
				'HTTP_X_CLUSTER_CLIENT_IP',
1841
				'HTTP_FORWARDED_FOR',
1842
				'HTTP_FORWARDED',
1843
				'HTTP_VIA',
1844
			) as $key ) {
1845
				if ( ! empty( $_SERVER[ $key ] ) ) {
1846
					return $_SERVER[ $key ];
1847
				}
1848
			}
1849
		}
1850
1851
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1852
	}
1853
1854
	/**
1855
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1856
	 */
1857
	function extra_oembed_providers() {
1858
		// Cloudup: https://dev.cloudup.com/#oembed
1859
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1860
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1861
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1862
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1863
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1864
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1865
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1866
	}
1867
1868
	/**
1869
	 * Synchronize connected user role changes
1870
	 */
1871
	function user_role_change( $user_id ) {
1872
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1873
		Users::user_role_change( $user_id );
1874
	}
1875
1876
	/**
1877
	 * Loads the currently active modules.
1878
	 */
1879
	public static function load_modules() {
1880
		if (
1881
			! self::is_active()
1882
			&& ! self::is_development_mode()
1883
			&& ! self::is_onboarding()
1884
			&& (
1885
				! is_multisite()
1886
				|| ! get_site_option( 'jetpack_protect_active' )
1887
			)
1888
		) {
1889
			return;
1890
		}
1891
1892
		$version = Jetpack_Options::get_option( 'version' );
1893 View Code Duplication
		if ( ! $version ) {
1894
			$version = $old_version = JETPACK__VERSION . ':' . time();
1895
			/** This action is documented in class.jetpack.php */
1896
			do_action( 'updating_jetpack_version', $version, false );
1897
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1898
		}
1899
		list( $version ) = explode( ':', $version );
1900
1901
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1902
1903
		$modules_data = array();
1904
1905
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1906
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1907
			$updated_modules = array();
1908
			foreach ( $modules as $module ) {
1909
				$modules_data[ $module ] = Jetpack::get_module( $module );
1910
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1911
					continue;
1912
				}
1913
1914
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1915
					continue;
1916
				}
1917
1918
				$updated_modules[] = $module;
1919
			}
1920
1921
			$modules = array_diff( $modules, $updated_modules );
1922
		}
1923
1924
		$is_development_mode = Jetpack::is_development_mode();
1925
1926
		foreach ( $modules as $index => $module ) {
1927
			// If we're in dev mode, disable modules requiring a connection
1928
			if ( $is_development_mode ) {
1929
				// Prime the pump if we need to
1930
				if ( empty( $modules_data[ $module ] ) ) {
1931
					$modules_data[ $module ] = Jetpack::get_module( $module );
1932
				}
1933
				// If the module requires a connection, but we're in local mode, don't include it.
1934
				if ( $modules_data[ $module ]['requires_connection'] ) {
1935
					continue;
1936
				}
1937
			}
1938
1939
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1940
				continue;
1941
			}
1942
1943
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1944
				unset( $modules[ $index ] );
1945
				self::update_active_modules( array_values( $modules ) );
1946
				continue;
1947
			}
1948
1949
			/**
1950
			 * Fires when a specific module is loaded.
1951
			 * The dynamic part of the hook, $module, is the module slug.
1952
			 *
1953
			 * @since 1.1.0
1954
			 */
1955
			do_action( 'jetpack_module_loaded_' . $module );
1956
		}
1957
1958
		/**
1959
		 * Fires when all the modules are loaded.
1960
		 *
1961
		 * @since 1.1.0
1962
		 */
1963
		do_action( 'jetpack_modules_loaded' );
1964
1965
		// 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.
1966
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1967
	}
1968
1969
	/**
1970
	 * Check if Jetpack's REST API compat file should be included
1971
	 * @action plugins_loaded
1972
	 * @return null
1973
	 */
1974
	public function check_rest_api_compat() {
1975
		/**
1976
		 * Filters the list of REST API compat files to be included.
1977
		 *
1978
		 * @since 2.2.5
1979
		 *
1980
		 * @param array $args Array of REST API compat files to include.
1981
		 */
1982
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1983
1984
		if ( function_exists( 'bbpress' ) )
1985
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1986
1987
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1988
			require_once $_jetpack_rest_api_compat_include;
1989
	}
1990
1991
	/**
1992
	 * Gets all plugins currently active in values, regardless of whether they're
1993
	 * traditionally activated or network activated.
1994
	 *
1995
	 * @todo Store the result in core's object cache maybe?
1996
	 */
1997
	public static function get_active_plugins() {
1998
		$active_plugins = (array) get_option( 'active_plugins', array() );
1999
2000
		if ( is_multisite() ) {
2001
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2002
			// whereas active_plugins stores them in the values.
2003
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2004
			if ( $network_plugins ) {
2005
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2006
			}
2007
		}
2008
2009
		sort( $active_plugins );
2010
2011
		return array_unique( $active_plugins );
2012
	}
2013
2014
	/**
2015
	 * Gets and parses additional plugin data to send with the heartbeat data
2016
	 *
2017
	 * @since 3.8.1
2018
	 *
2019
	 * @return array Array of plugin data
2020
	 */
2021
	public static function get_parsed_plugin_data() {
2022
		if ( ! function_exists( 'get_plugins' ) ) {
2023
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
2024
		}
2025
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2026
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2027
		$active_plugins = Jetpack::get_active_plugins();
2028
2029
		$plugins = array();
2030
		foreach ( $all_plugins as $path => $plugin_data ) {
2031
			$plugins[ $path ] = array(
2032
					'is_active' => in_array( $path, $active_plugins ),
2033
					'file'      => $path,
2034
					'name'      => $plugin_data['Name'],
2035
					'version'   => $plugin_data['Version'],
2036
					'author'    => $plugin_data['Author'],
2037
			);
2038
		}
2039
2040
		return $plugins;
2041
	}
2042
2043
	/**
2044
	 * Gets and parses theme data to send with the heartbeat data
2045
	 *
2046
	 * @since 3.8.1
2047
	 *
2048
	 * @return array Array of theme data
2049
	 */
2050
	public static function get_parsed_theme_data() {
2051
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2052
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2053
2054
		$themes = array();
2055
		foreach ( $all_themes as $slug => $theme_data ) {
2056
			$theme_headers = array();
2057
			foreach ( $header_keys as $header_key ) {
2058
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2059
			}
2060
2061
			$themes[ $slug ] = array(
2062
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2063
					'slug' => $slug,
2064
					'theme_root' => $theme_data->get_theme_root_uri(),
2065
					'parent' => $theme_data->parent(),
2066
					'headers' => $theme_headers
2067
			);
2068
		}
2069
2070
		return $themes;
2071
	}
2072
2073
	/**
2074
	 * Checks whether a specific plugin is active.
2075
	 *
2076
	 * We don't want to store these in a static variable, in case
2077
	 * there are switch_to_blog() calls involved.
2078
	 */
2079
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2080
		return in_array( $plugin, self::get_active_plugins() );
2081
	}
2082
2083
	/**
2084
	 * Check if Jetpack's Open Graph tags should be used.
2085
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2086
	 *
2087
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2088
	 * @action plugins_loaded
2089
	 * @return null
2090
	 */
2091
	public function check_open_graph() {
2092
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2093
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2094
		}
2095
2096
		$active_plugins = self::get_active_plugins();
2097
2098
		if ( ! empty( $active_plugins ) ) {
2099
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2100
				if ( in_array( $plugin, $active_plugins ) ) {
2101
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2102
					break;
2103
				}
2104
			}
2105
		}
2106
2107
		/**
2108
		 * Allow the addition of Open Graph Meta Tags to all pages.
2109
		 *
2110
		 * @since 2.0.3
2111
		 *
2112
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2113
		 */
2114
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2115
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2116
		}
2117
	}
2118
2119
	/**
2120
	 * Check if Jetpack's Twitter tags should be used.
2121
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2122
	 *
2123
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2124
	 * @action plugins_loaded
2125
	 * @return null
2126
	 */
2127
	public function check_twitter_tags() {
2128
2129
		$active_plugins = self::get_active_plugins();
2130
2131
		if ( ! empty( $active_plugins ) ) {
2132
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2133
				if ( in_array( $plugin, $active_plugins ) ) {
2134
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2135
					break;
2136
				}
2137
			}
2138
		}
2139
2140
		/**
2141
		 * Allow Twitter Card Meta tags to be disabled.
2142
		 *
2143
		 * @since 2.6.0
2144
		 *
2145
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2146
		 */
2147
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2148
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2149
		}
2150
	}
2151
2152
	/**
2153
	 * Allows plugins to submit security reports.
2154
 	 *
2155
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2156
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2157
	 * @param array   $args         See definitions above
2158
	 */
2159
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2160
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2161
	}
2162
2163
/* Jetpack Options API */
2164
2165
	public static function get_option_names( $type = 'compact' ) {
2166
		return Jetpack_Options::get_option_names( $type );
2167
	}
2168
2169
	/**
2170
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2171
 	 *
2172
	 * @param string $name    Option name
2173
	 * @param mixed  $default (optional)
2174
	 */
2175
	public static function get_option( $name, $default = false ) {
2176
		return Jetpack_Options::get_option( $name, $default );
2177
	}
2178
2179
	/**
2180
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2181
 	 *
2182
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2183
	 * @param string $name  Option name
2184
	 * @param mixed  $value Option value
2185
	 */
2186
	public static function update_option( $name, $value ) {
2187
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2188
		return Jetpack_Options::update_option( $name, $value );
2189
	}
2190
2191
	/**
2192
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2193
 	 *
2194
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2195
	 * @param array $array array( option name => option value, ... )
2196
	 */
2197
	public static function update_options( $array ) {
2198
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2199
		return Jetpack_Options::update_options( $array );
2200
	}
2201
2202
	/**
2203
	 * Deletes the given option.  May be passed multiple option names as an array.
2204
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2205
	 *
2206
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2207
	 * @param string|array $names
2208
	 */
2209
	public static function delete_option( $names ) {
2210
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2211
		return Jetpack_Options::delete_option( $names );
2212
	}
2213
2214
	/**
2215
	 * Enters a user token into the user_tokens option
2216
	 *
2217
	 * @param int $user_id
2218
	 * @param string $token
2219
	 * return bool
2220
	 */
2221
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2222
		// not designed for concurrent updates
2223
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2224
		if ( ! is_array( $user_tokens ) )
2225
			$user_tokens = array();
2226
		$user_tokens[$user_id] = $token;
2227
		if ( $is_master_user ) {
2228
			$master_user = $user_id;
2229
			$options     = compact( 'user_tokens', 'master_user' );
2230
		} else {
2231
			$options = compact( 'user_tokens' );
2232
		}
2233
		return Jetpack_Options::update_options( $options );
2234
	}
2235
2236
	/**
2237
	 * Returns an array of all PHP files in the specified absolute path.
2238
	 * Equivalent to glob( "$absolute_path/*.php" ).
2239
	 *
2240
	 * @param string $absolute_path The absolute path of the directory to search.
2241
	 * @return array Array of absolute paths to the PHP files.
2242
	 */
2243
	public static function glob_php( $absolute_path ) {
2244
		if ( function_exists( 'glob' ) ) {
2245
			return glob( "$absolute_path/*.php" );
2246
		}
2247
2248
		$absolute_path = untrailingslashit( $absolute_path );
2249
		$files = array();
2250
		if ( ! $dir = @opendir( $absolute_path ) ) {
2251
			return $files;
2252
		}
2253
2254
		while ( false !== $file = readdir( $dir ) ) {
2255
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2256
				continue;
2257
			}
2258
2259
			$file = "$absolute_path/$file";
2260
2261
			if ( ! is_file( $file ) ) {
2262
				continue;
2263
			}
2264
2265
			$files[] = $file;
2266
		}
2267
2268
		closedir( $dir );
2269
2270
		return $files;
2271
	}
2272
2273
	public static function activate_new_modules( $redirect = false ) {
2274
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2275
			return;
2276
		}
2277
2278
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2279 View Code Duplication
		if ( ! $jetpack_old_version ) {
2280
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2281
			/** This action is documented in class.jetpack.php */
2282
			do_action( 'updating_jetpack_version', $version, false );
2283
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2284
		}
2285
2286
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2287
2288
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2289
			return;
2290
		}
2291
2292
		$active_modules     = Jetpack::get_active_modules();
2293
		$reactivate_modules = array();
2294
		foreach ( $active_modules as $active_module ) {
2295
			$module = Jetpack::get_module( $active_module );
2296
			if ( ! isset( $module['changed'] ) ) {
2297
				continue;
2298
			}
2299
2300
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2301
				continue;
2302
			}
2303
2304
			$reactivate_modules[] = $active_module;
2305
			Jetpack::deactivate_module( $active_module );
2306
		}
2307
2308
		$new_version = JETPACK__VERSION . ':' . time();
2309
		/** This action is documented in class.jetpack.php */
2310
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2311
		Jetpack_Options::update_options(
2312
			array(
2313
				'version'     => $new_version,
2314
				'old_version' => $jetpack_old_version,
2315
			)
2316
		);
2317
2318
		Jetpack::state( 'message', 'modules_activated' );
2319
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2320
2321
		if ( $redirect ) {
2322
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2323
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2324
				$page = $_GET['page'];
2325
			}
2326
2327
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2328
			exit;
2329
		}
2330
	}
2331
2332
	/**
2333
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2334
	 * Make sure to tuck away module "library" files in a sub-directory.
2335
	 */
2336
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2337
		static $modules = null;
2338
2339
		if ( ! isset( $modules ) ) {
2340
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2341
			// Use the cache if we're on the front-end and it's available...
2342
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2343
				$modules = $available_modules_option[ JETPACK__VERSION ];
2344
			} else {
2345
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2346
2347
				$modules = array();
2348
2349
				foreach ( $files as $file ) {
2350
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2351
						continue;
2352
					}
2353
2354
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2355
				}
2356
2357
				Jetpack_Options::update_option( 'available_modules', array(
2358
					JETPACK__VERSION => $modules,
2359
				) );
2360
			}
2361
		}
2362
2363
		/**
2364
		 * Filters the array of modules available to be activated.
2365
		 *
2366
		 * @since 2.4.0
2367
		 *
2368
		 * @param array $modules Array of available modules.
2369
		 * @param string $min_version Minimum version number required to use modules.
2370
		 * @param string $max_version Maximum version number required to use modules.
2371
		 */
2372
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2373
2374
		if ( ! $min_version && ! $max_version ) {
2375
			return array_keys( $mods );
2376
		}
2377
2378
		$r = array();
2379
		foreach ( $mods as $slug => $introduced ) {
2380
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2381
				continue;
2382
			}
2383
2384
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2385
				continue;
2386
			}
2387
2388
			$r[] = $slug;
2389
		}
2390
2391
		return $r;
2392
	}
2393
2394
	/**
2395
	 * Default modules loaded on activation.
2396
	 */
2397
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2398
		$return = array();
2399
2400
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2401
			$module_data = Jetpack::get_module( $module );
2402
2403
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2404
				case 'yes' :
2405
					$return[] = $module;
2406
					break;
2407
				case 'public' :
2408
					if ( Jetpack_Options::get_option( 'public' ) ) {
2409
						$return[] = $module;
2410
					}
2411
					break;
2412
				case 'no' :
2413
				default :
2414
					break;
2415
			}
2416
		}
2417
		/**
2418
		 * Filters the array of default modules.
2419
		 *
2420
		 * @since 2.5.0
2421
		 *
2422
		 * @param array $return Array of default modules.
2423
		 * @param string $min_version Minimum version number required to use modules.
2424
		 * @param string $max_version Maximum version number required to use modules.
2425
		 */
2426
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2427
	}
2428
2429
	/**
2430
	 * Checks activated modules during auto-activation to determine
2431
	 * if any of those modules are being deprecated.  If so, close
2432
	 * them out, and add any replacement modules.
2433
	 *
2434
	 * Runs at priority 99 by default.
2435
	 *
2436
	 * This is run late, so that it can still activate a module if
2437
	 * the new module is a replacement for another that the user
2438
	 * currently has active, even if something at the normal priority
2439
	 * would kibosh everything.
2440
	 *
2441
	 * @since 2.6
2442
	 * @uses jetpack_get_default_modules filter
2443
	 * @param array $modules
2444
	 * @return array
2445
	 */
2446
	function handle_deprecated_modules( $modules ) {
2447
		$deprecated_modules = array(
2448
			'debug'            => null,  // Closed out and moved to the debugger library.
2449
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2450
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2451
		);
2452
2453
		// Don't activate SSO if they never completed activating WPCC.
2454
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2455
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2456
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2457
				$deprecated_modules['wpcc'] = null;
2458
			}
2459
		}
2460
2461
		foreach ( $deprecated_modules as $module => $replacement ) {
2462
			if ( Jetpack::is_module_active( $module ) ) {
2463
				self::deactivate_module( $module );
2464
				if ( $replacement ) {
2465
					$modules[] = $replacement;
2466
				}
2467
			}
2468
		}
2469
2470
		return array_unique( $modules );
2471
	}
2472
2473
	/**
2474
	 * Checks activated plugins during auto-activation to determine
2475
	 * if any of those plugins are in the list with a corresponding module
2476
	 * that is not compatible with the plugin. The module will not be allowed
2477
	 * to auto-activate.
2478
	 *
2479
	 * @since 2.6
2480
	 * @uses jetpack_get_default_modules filter
2481
	 * @param array $modules
2482
	 * @return array
2483
	 */
2484
	function filter_default_modules( $modules ) {
2485
2486
		$active_plugins = self::get_active_plugins();
2487
2488
		if ( ! empty( $active_plugins ) ) {
2489
2490
			// For each module we'd like to auto-activate...
2491
			foreach ( $modules as $key => $module ) {
2492
				// If there are potential conflicts for it...
2493
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2494
					// For each potential conflict...
2495
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2496
						// If that conflicting plugin is active...
2497
						if ( in_array( $plugin, $active_plugins ) ) {
2498
							// Remove that item from being auto-activated.
2499
							unset( $modules[ $key ] );
2500
						}
2501
					}
2502
				}
2503
			}
2504
		}
2505
2506
		return $modules;
2507
	}
2508
2509
	/**
2510
	 * Extract a module's slug from its full path.
2511
	 */
2512
	public static function get_module_slug( $file ) {
2513
		return str_replace( '.php', '', basename( $file ) );
2514
	}
2515
2516
	/**
2517
	 * Generate a module's path from its slug.
2518
	 */
2519
	public static function get_module_path( $slug ) {
2520
		/**
2521
		 * Filters the path of a modules.
2522
		 *
2523
		 * @since 7.4.0
2524
		 *
2525
		 * @param array $return The absolute path to a module's root php file
2526
		 * @param string $slug The module slug
2527
		 */
2528
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2529
	}
2530
2531
	/**
2532
	 * Load module data from module file. Headers differ from WordPress
2533
	 * plugin headers to avoid them being identified as standalone
2534
	 * plugins on the WordPress plugins page.
2535
	 */
2536
	public static function get_module( $module ) {
2537
		$headers = array(
2538
			'name'                      => 'Module Name',
2539
			'description'               => 'Module Description',
2540
			'sort'                      => 'Sort Order',
2541
			'recommendation_order'      => 'Recommendation Order',
2542
			'introduced'                => 'First Introduced',
2543
			'changed'                   => 'Major Changes In',
2544
			'deactivate'                => 'Deactivate',
2545
			'free'                      => 'Free',
2546
			'requires_connection'       => 'Requires Connection',
2547
			'auto_activate'             => 'Auto Activate',
2548
			'module_tags'               => 'Module Tags',
2549
			'feature'                   => 'Feature',
2550
			'additional_search_queries' => 'Additional Search Queries',
2551
			'plan_classes'              => 'Plans',
2552
		);
2553
2554
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2555
2556
		$mod = Jetpack::get_file_data( $file, $headers );
2557
		if ( empty( $mod['name'] ) ) {
2558
			return false;
2559
		}
2560
2561
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2562
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2563
		$mod['deactivate']              = empty( $mod['deactivate'] );
2564
		$mod['free']                    = empty( $mod['free'] );
2565
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2566
2567
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2568
			$mod['auto_activate'] = 'No';
2569
		} else {
2570
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2571
		}
2572
2573
		if ( $mod['module_tags'] ) {
2574
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2575
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2576
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2577
		} else {
2578
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2579
		}
2580
2581 View Code Duplication
		if ( $mod['plan_classes'] ) {
2582
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2583
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2584
		} else {
2585
			$mod['plan_classes'] = array( 'free' );
2586
		}
2587
2588 View Code Duplication
		if ( $mod['feature'] ) {
2589
			$mod['feature'] = explode( ',', $mod['feature'] );
2590
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2591
		} else {
2592
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2593
		}
2594
2595
		/**
2596
		 * Filters the feature array on a module.
2597
		 *
2598
		 * This filter allows you to control where each module is filtered: Recommended,
2599
		 * and the default "Other" listing.
2600
		 *
2601
		 * @since 3.5.0
2602
		 *
2603
		 * @param array   $mod['feature'] The areas to feature this module:
2604
		 *     'Recommended' shows on the main Jetpack admin screen.
2605
		 *     'Other' should be the default if no other value is in the array.
2606
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2607
		 * @param array   $mod All the currently assembled module data.
2608
		 */
2609
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2610
2611
		/**
2612
		 * Filter the returned data about a module.
2613
		 *
2614
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2615
		 * so please be careful.
2616
		 *
2617
		 * @since 3.6.0
2618
		 *
2619
		 * @param array   $mod    The details of the requested module.
2620
		 * @param string  $module The slug of the module, e.g. sharedaddy
2621
		 * @param string  $file   The path to the module source file.
2622
		 */
2623
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2624
	}
2625
2626
	/**
2627
	 * Like core's get_file_data implementation, but caches the result.
2628
	 */
2629
	public static function get_file_data( $file, $headers ) {
2630
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2631
		$file_name = basename( $file );
2632
2633
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2634
2635
		$file_data_option = get_transient( $cache_key );
2636
2637
		if ( false === $file_data_option ) {
2638
			$file_data_option = array();
2639
		}
2640
2641
		$key           = md5( $file_name . serialize( $headers ) );
2642
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2643
2644
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2645
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2646
			return $file_data_option[ $key ];
2647
		}
2648
2649
		$data = get_file_data( $file, $headers );
2650
2651
		$file_data_option[ $key ] = $data;
2652
2653
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2654
2655
		return $data;
2656
	}
2657
2658
2659
	/**
2660
	 * Return translated module tag.
2661
	 *
2662
	 * @param string $tag Tag as it appears in each module heading.
2663
	 *
2664
	 * @return mixed
2665
	 */
2666
	public static function translate_module_tag( $tag ) {
2667
		return jetpack_get_module_i18n_tag( $tag );
2668
	}
2669
2670
	/**
2671
	 * Get i18n strings as a JSON-encoded string
2672
	 *
2673
	 * @return string The locale as JSON
2674
	 */
2675
	public static function get_i18n_data_json() {
2676
2677
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2678
		// JSON files with the file they should be included for. This is an md5
2679
		// of '_inc/build/admin.js'.
2680
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2681
2682
		$i18n_json =
2683
				   JETPACK__PLUGIN_DIR
2684
				   . 'languages/json/jetpack-'
2685
				   . get_user_locale()
2686
				   . '-'
2687
				   . $path_md5
2688
				   . '.json';
2689
2690
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2691
			$locale_data = @file_get_contents( $i18n_json );
2692
			if ( $locale_data ) {
2693
				return $locale_data;
2694
			}
2695
		}
2696
2697
		// Return valid empty Jed locale
2698
		return '{ "locale_data": { "messages": { "": {} } } }';
2699
	}
2700
2701
	/**
2702
	 * Add locale data setup to wp-i18n
2703
	 *
2704
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2705
	 *
2706
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2707
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2708
	 *
2709
	 * This method provides a safe way to request the setup multiple times but add the script at
2710
	 * most once.
2711
	 *
2712
	 * @since 6.7.0
2713
	 *
2714
	 * @return void
2715
	 */
2716
	public static function setup_wp_i18n_locale_data() {
2717
		static $script_added = false;
2718
		if ( ! $script_added ) {
2719
			$script_added = true;
2720
			wp_add_inline_script(
2721
				'wp-i18n',
2722
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2723
			);
2724
		}
2725
	}
2726
2727
	/**
2728
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2729
	 *
2730
	 * @since 3.9.2
2731
	 *
2732
	 * @param array $modules
2733
	 *
2734
	 * @return string|void
2735
	 */
2736
	public static function get_translated_modules( $modules ) {
2737
		foreach ( $modules as $index => $module ) {
2738
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2739
			if ( isset( $module['name'] ) ) {
2740
				$modules[ $index ]['name'] = $i18n_module['name'];
2741
			}
2742
			if ( isset( $module['description'] ) ) {
2743
				$modules[ $index ]['description'] = $i18n_module['description'];
2744
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2745
			}
2746
		}
2747
		return $modules;
2748
	}
2749
2750
	/**
2751
	 * Get a list of activated modules as an array of module slugs.
2752
	 */
2753
	public static function get_active_modules() {
2754
		$active = Jetpack_Options::get_option( 'active_modules' );
2755
2756
		if ( ! is_array( $active ) ) {
2757
			$active = array();
2758
		}
2759
2760
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2761
			$active[] = 'vaultpress';
2762
		} else {
2763
			$active = array_diff( $active, array( 'vaultpress' ) );
2764
		}
2765
2766
		//If protect is active on the main site of a multisite, it should be active on all sites.
2767
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2768
			$active[] = 'protect';
2769
		}
2770
2771
		/**
2772
		 * Allow filtering of the active modules.
2773
		 *
2774
		 * Gives theme and plugin developers the power to alter the modules that
2775
		 * are activated on the fly.
2776
		 *
2777
		 * @since 5.8.0
2778
		 *
2779
		 * @param array $active Array of active module slugs.
2780
		 */
2781
		$active = apply_filters( 'jetpack_active_modules', $active );
2782
2783
		return array_unique( $active );
2784
	}
2785
2786
	/**
2787
	 * Check whether or not a Jetpack module is active.
2788
	 *
2789
	 * @param string $module The slug of a Jetpack module.
2790
	 * @return bool
2791
	 *
2792
	 * @static
2793
	 */
2794
	public static function is_module_active( $module ) {
2795
		return in_array( $module, self::get_active_modules() );
2796
	}
2797
2798
	public static function is_module( $module ) {
2799
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2800
	}
2801
2802
	/**
2803
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2804
	 *
2805
	 * @param bool $catch True to start catching, False to stop.
2806
	 *
2807
	 * @static
2808
	 */
2809
	public static function catch_errors( $catch ) {
2810
		static $display_errors, $error_reporting;
2811
2812
		if ( $catch ) {
2813
			$display_errors  = @ini_set( 'display_errors', 1 );
2814
			$error_reporting = @error_reporting( E_ALL );
2815
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2816
		} else {
2817
			@ini_set( 'display_errors', $display_errors );
2818
			@error_reporting( $error_reporting );
2819
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2820
		}
2821
	}
2822
2823
	/**
2824
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2825
	 */
2826
	public static function catch_errors_on_shutdown() {
2827
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2828
	}
2829
2830
	/**
2831
	 * Rewrite any string to make paths easier to read.
2832
	 *
2833
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2834
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2835
	 *
2836
	 * @param $string
2837
	 * @return mixed
2838
	 */
2839
	public static function alias_directories( $string ) {
2840
		// ABSPATH has a trailing slash.
2841
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2842
		// WP_CONTENT_DIR does not have a trailing slash.
2843
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2844
2845
		return $string;
2846
	}
2847
2848
	public static function activate_default_modules(
2849
		$min_version = false,
2850
		$max_version = false,
2851
		$other_modules = array(),
2852
		$redirect = true,
2853
		$send_state_messages = true
2854
	) {
2855
		$jetpack = Jetpack::init();
2856
2857
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2858
		$modules = array_merge( $other_modules, $modules );
2859
2860
		// Look for standalone plugins and disable if active.
2861
2862
		$to_deactivate = array();
2863
		foreach ( $modules as $module ) {
2864
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2865
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2866
			}
2867
		}
2868
2869
		$deactivated = array();
2870
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2871
			list( $probable_file, $probable_title ) = $deactivate_me;
2872
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2873
				$deactivated[] = $module;
2874
			}
2875
		}
2876
2877
		if ( $deactivated && $redirect ) {
2878
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2879
2880
			$url = add_query_arg(
2881
				array(
2882
					'action'   => 'activate_default_modules',
2883
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2884
				),
2885
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2886
			);
2887
			wp_safe_redirect( $url );
2888
			exit;
2889
		}
2890
2891
		/**
2892
		 * Fires before default modules are activated.
2893
		 *
2894
		 * @since 1.9.0
2895
		 *
2896
		 * @param string $min_version Minimum version number required to use modules.
2897
		 * @param string $max_version Maximum version number required to use modules.
2898
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2899
		 */
2900
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2901
2902
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2903
		if ( $send_state_messages ) {
2904
			Jetpack::restate();
2905
			Jetpack::catch_errors( true );
2906
		}
2907
2908
		$active = Jetpack::get_active_modules();
2909
2910
		foreach ( $modules as $module ) {
2911
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2912
				$active[] = $module;
2913
				self::update_active_modules( $active );
2914
				continue;
2915
			}
2916
2917
			if ( $send_state_messages && in_array( $module, $active ) ) {
2918
				$module_info = Jetpack::get_module( $module );
2919 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2920
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2921
					if ( $active_state = Jetpack::state( $state ) ) {
2922
						$active_state = explode( ',', $active_state );
2923
					} else {
2924
						$active_state = array();
2925
					}
2926
					$active_state[] = $module;
2927
					Jetpack::state( $state, implode( ',', $active_state ) );
2928
				}
2929
				continue;
2930
			}
2931
2932
			$file = Jetpack::get_module_path( $module );
2933
			if ( ! file_exists( $file ) ) {
2934
				continue;
2935
			}
2936
2937
			// we'll override this later if the plugin can be included without fatal error
2938
			if ( $redirect ) {
2939
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2940
			}
2941
2942
			if ( $send_state_messages ) {
2943
				Jetpack::state( 'error', 'module_activation_failed' );
2944
				Jetpack::state( 'module', $module );
2945
			}
2946
2947
			ob_start();
2948
			require_once $file;
2949
2950
			$active[] = $module;
2951
2952 View Code Duplication
			if ( $send_state_messages ) {
2953
2954
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2955
				if ( $active_state = Jetpack::state( $state ) ) {
2956
					$active_state = explode( ',', $active_state );
2957
				} else {
2958
					$active_state = array();
2959
				}
2960
				$active_state[] = $module;
2961
				Jetpack::state( $state, implode( ',', $active_state ) );
2962
			}
2963
2964
			Jetpack::update_active_modules( $active );
2965
2966
			ob_end_clean();
2967
		}
2968
2969
		if ( $send_state_messages ) {
2970
			Jetpack::state( 'error', false );
2971
			Jetpack::state( 'module', false );
2972
		}
2973
2974
		Jetpack::catch_errors( false );
2975
		/**
2976
		 * Fires when default modules are activated.
2977
		 *
2978
		 * @since 1.9.0
2979
		 *
2980
		 * @param string $min_version Minimum version number required to use modules.
2981
		 * @param string $max_version Maximum version number required to use modules.
2982
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2983
		 */
2984
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2985
	}
2986
2987
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2988
		/**
2989
		 * Fires before a module is activated.
2990
		 *
2991
		 * @since 2.6.0
2992
		 *
2993
		 * @param string $module Module slug.
2994
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2995
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2996
		 */
2997
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2998
2999
		$jetpack = Jetpack::init();
3000
3001
		if ( ! strlen( $module ) )
3002
			return false;
3003
3004
		if ( ! Jetpack::is_module( $module ) )
3005
			return false;
3006
3007
		// If it's already active, then don't do it again
3008
		$active = Jetpack::get_active_modules();
3009
		foreach ( $active as $act ) {
3010
			if ( $act == $module )
3011
				return true;
3012
		}
3013
3014
		$module_data = Jetpack::get_module( $module );
3015
3016
		if ( ! Jetpack::is_active() ) {
3017
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
3018
				return false;
3019
3020
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3021
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
3022
				return false;
3023
		}
3024
3025
		// Check and see if the old plugin is active
3026
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3027
			// Deactivate the old plugin
3028
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3029
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3030
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3031
				Jetpack::state( 'deactivated_plugins', $module );
3032
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3033
				exit;
3034
			}
3035
		}
3036
3037
		// Protect won't work with mis-configured IPs
3038
		if ( 'protect' === $module ) {
3039
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3040
			if ( ! jetpack_protect_get_ip() ) {
3041
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3042
				return false;
3043
			}
3044
		}
3045
3046
		if ( ! Jetpack_Plan::supports( $module ) ) {
3047
			return false;
3048
		}
3049
3050
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3051
		Jetpack::state( 'module', $module );
3052
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3053
3054
		Jetpack::catch_errors( true );
3055
		ob_start();
3056
		require Jetpack::get_module_path( $module );
3057
		/** This action is documented in class.jetpack.php */
3058
		do_action( 'jetpack_activate_module', $module );
3059
		$active[] = $module;
3060
		Jetpack::update_active_modules( $active );
3061
3062
		Jetpack::state( 'error', false ); // the override
3063
		ob_end_clean();
3064
		Jetpack::catch_errors( false );
3065
3066
		if ( $redirect ) {
3067
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3068
		}
3069
		if ( $exit ) {
3070
			exit;
3071
		}
3072
		return true;
3073
	}
3074
3075
	function activate_module_actions( $module ) {
3076
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3077
	}
3078
3079
	public static function deactivate_module( $module ) {
3080
		/**
3081
		 * Fires when a module is deactivated.
3082
		 *
3083
		 * @since 1.9.0
3084
		 *
3085
		 * @param string $module Module slug.
3086
		 */
3087
		do_action( 'jetpack_pre_deactivate_module', $module );
3088
3089
		$jetpack = Jetpack::init();
3090
3091
		$active = Jetpack::get_active_modules();
3092
		$new    = array_filter( array_diff( $active, (array) $module ) );
3093
3094
		return self::update_active_modules( $new );
3095
	}
3096
3097
	public static function enable_module_configurable( $module ) {
3098
		$module = Jetpack::get_module_slug( $module );
3099
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3100
	}
3101
3102
	/**
3103
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3104
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3105
	 *
3106
	 * @param string $module Module slug
3107
	 * @return string $url module configuration URL
3108
	 */
3109
	public static function module_configuration_url( $module ) {
3110
		$module = Jetpack::get_module_slug( $module );
3111
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3112
		/**
3113
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3114
		 *
3115
		 * @since 6.9.0
3116
		 *
3117
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3118
		 */
3119
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3120
3121
		return $url;
3122
	}
3123
3124
/* Installation */
3125
	public static function bail_on_activation( $message, $deactivate = true ) {
3126
?>
3127
<!doctype html>
3128
<html>
3129
<head>
3130
<meta charset="<?php bloginfo( 'charset' ); ?>">
3131
<style>
3132
* {
3133
	text-align: center;
3134
	margin: 0;
3135
	padding: 0;
3136
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3137
}
3138
p {
3139
	margin-top: 1em;
3140
	font-size: 18px;
3141
}
3142
</style>
3143
<body>
3144
<p><?php echo esc_html( $message ); ?></p>
3145
</body>
3146
</html>
3147
<?php
3148
		if ( $deactivate ) {
3149
			$plugins = get_option( 'active_plugins' );
3150
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3151
			$update  = false;
3152
			foreach ( $plugins as $i => $plugin ) {
3153
				if ( $plugin === $jetpack ) {
3154
					$plugins[$i] = false;
3155
					$update = true;
3156
				}
3157
			}
3158
3159
			if ( $update ) {
3160
				update_option( 'active_plugins', array_filter( $plugins ) );
3161
			}
3162
		}
3163
		exit;
3164
	}
3165
3166
	/**
3167
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3168
	 * @static
3169
	 */
3170
	public static function plugin_activation( $network_wide ) {
3171
		Jetpack_Options::update_option( 'activated', 1 );
3172
3173
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3174
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3175
		}
3176
3177
		if ( $network_wide )
3178
			Jetpack::state( 'network_nag', true );
3179
3180
		// For firing one-off events (notices) immediately after activation
3181
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3182
3183
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3184
3185
		Jetpack::plugin_initialize();
3186
	}
3187
3188
	public static function get_activation_source( $referer_url ) {
3189
3190
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3191
			return array( 'wp-cli', null );
3192
		}
3193
3194
		$referer = parse_url( $referer_url );
3195
3196
		$source_type = 'unknown';
3197
		$source_query = null;
3198
3199
		if ( ! is_array( $referer ) ) {
3200
			return array( $source_type, $source_query );
3201
		}
3202
3203
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3204
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3205
3206
		if ( isset( $referer['query'] ) ) {
3207
			parse_str( $referer['query'], $query_parts );
3208
		} else {
3209
			$query_parts = array();
3210
		}
3211
3212
		if ( $plugins_path === $referer['path'] ) {
3213
			$source_type = 'list';
3214
		} elseif ( $plugins_install_path === $referer['path'] ) {
3215
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3216
			switch( $tab ) {
3217
				case 'popular':
3218
					$source_type = 'popular';
3219
					break;
3220
				case 'recommended':
3221
					$source_type = 'recommended';
3222
					break;
3223
				case 'favorites':
3224
					$source_type = 'favorites';
3225
					break;
3226
				case 'search':
3227
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3228
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3229
					break;
3230
				default:
3231
					$source_type = 'featured';
3232
			}
3233
		}
3234
3235
		return array( $source_type, $source_query );
3236
	}
3237
3238
	/**
3239
	 * Runs before bumping version numbers up to a new version
3240
	 * @param  string $version    Version:timestamp
3241
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3242
	 * @return null              [description]
3243
	 */
3244
	public static function do_version_bump( $version, $old_version ) {
3245
		if ( ! $old_version ) { // For new sites
3246
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3247
		}
3248
	}
3249
3250
	/**
3251
	 * Sets the internal version number and activation state.
3252
	 * @static
3253
	 */
3254
	public static function plugin_initialize() {
3255
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3256
			Jetpack_Options::update_option( 'activated', 2 );
3257
		}
3258
3259 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3260
			$version = $old_version = JETPACK__VERSION . ':' . time();
3261
			/** This action is documented in class.jetpack.php */
3262
			do_action( 'updating_jetpack_version', $version, false );
3263
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3264
		}
3265
3266
		Jetpack::load_modules();
3267
3268
		Jetpack_Options::delete_option( 'do_activate' );
3269
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3270
	}
3271
3272
	/**
3273
	 * Removes all connection options
3274
	 * @static
3275
	 */
3276
	public static function plugin_deactivation( ) {
3277
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3278
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3279
			Jetpack_Network::init()->deactivate();
3280
		} else {
3281
			Jetpack::disconnect( false );
3282
			//Jetpack_Heartbeat::init()->deactivate();
3283
		}
3284
	}
3285
3286
	/**
3287
	 * Disconnects from the Jetpack servers.
3288
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3289
	 * @static
3290
	 */
3291
	public static function disconnect( $update_activated_state = true ) {
3292
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3293
		Jetpack::clean_nonces( true );
3294
3295
		// If the site is in an IDC because sync is not allowed,
3296
		// let's make sure to not disconnect the production site.
3297
		if ( ! self::validate_sync_error_idc_option() ) {
3298
			$tracking = new Tracking();
3299
			$tracking->record_user_event( 'disconnect_site', array() );
3300
			Jetpack::load_xml_rpc_client();
3301
			$xml = new Jetpack_IXR_Client();
3302
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3303
		}
3304
3305
		Jetpack_Options::delete_option(
3306
			array(
3307
				'blog_token',
3308
				'user_token',
3309
				'user_tokens',
3310
				'master_user',
3311
				'time_diff',
3312
				'fallback_no_verify_ssl_certs',
3313
			)
3314
		);
3315
3316
		Jetpack_IDC::clear_all_idc_options();
3317
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3318
3319
		if ( $update_activated_state ) {
3320
			Jetpack_Options::update_option( 'activated', 4 );
3321
		}
3322
3323
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3324
			// Check then record unique disconnection if site has never been disconnected previously
3325
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3326
				$jetpack_unique_connection['disconnected'] = 1;
3327
			} else {
3328
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3329
					//track unique disconnect
3330
					$jetpack = Jetpack::init();
3331
3332
					$jetpack->stat( 'connections', 'unique-disconnect' );
3333
					$jetpack->do_stats( 'server_side' );
3334
				}
3335
				// increment number of times disconnected
3336
				$jetpack_unique_connection['disconnected'] += 1;
3337
			}
3338
3339
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3340
		}
3341
3342
		// Delete cached connected user data
3343
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3344
		delete_transient( $transient_key );
3345
3346
		// Delete all the sync related data. Since it could be taking up space.
3347
		Sender::get_instance()->uninstall();
3348
3349
		// Disable the Heartbeat cron
3350
		Jetpack_Heartbeat::init()->deactivate();
3351
	}
3352
3353
	/**
3354
	 * Unlinks the current user from the linked WordPress.com user
3355
	 */
3356
	public static function unlink_user( $user_id = null ) {
3357
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3358
			return false;
3359
3360
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3361
3362
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3363
			return false;
3364
3365
		if ( ! isset( $tokens[ $user_id ] ) )
3366
			return false;
3367
3368
		Jetpack::load_xml_rpc_client();
3369
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3370
		$xml->query( 'jetpack.unlink_user', $user_id );
3371
3372
		unset( $tokens[ $user_id ] );
3373
3374
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3375
3376
		/**
3377
		 * Fires after the current user has been unlinked from WordPress.com.
3378
		 *
3379
		 * @since 4.1.0
3380
		 *
3381
		 * @param int $user_id The current user's ID.
3382
		 */
3383
		do_action( 'jetpack_unlinked_user', $user_id );
3384
3385
		return true;
3386
	}
3387
3388
	/**
3389
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3390
	 */
3391
	public static function try_registration() {
3392
		// The user has agreed to the TOS at some point by now.
3393
		Jetpack_Options::update_option( 'tos_agreed', true );
3394
3395
		// Let's get some testing in beta versions and such.
3396
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3397
			// Before attempting to connect, let's make sure that the domains are viable.
3398
			$domains_to_check = array_unique( array(
3399
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3400
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3401
			) );
3402
			foreach ( $domains_to_check as $domain ) {
3403
				$result = self::connection()->is_usable_domain( $domain );
3404
				if ( is_wp_error( $result ) ) {
3405
					return $result;
3406
				}
3407
			}
3408
		}
3409
3410
		$result = Jetpack::register();
3411
3412
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3413
		if ( ! $result || is_wp_error( $result ) ) {
3414
			return $result;
3415
		} else {
3416
			return true;
3417
		}
3418
	}
3419
3420
	/**
3421
	 * Tracking an internal event log. Try not to put too much chaff in here.
3422
	 *
3423
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3424
	 */
3425
	public static function log( $code, $data = null ) {
3426
		// only grab the latest 200 entries
3427
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3428
3429
		// Append our event to the log
3430
		$log_entry = array(
3431
			'time'    => time(),
3432
			'user_id' => get_current_user_id(),
3433
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3434
			'code'    => $code,
3435
		);
3436
		// Don't bother storing it unless we've got some.
3437
		if ( ! is_null( $data ) ) {
3438
			$log_entry['data'] = $data;
3439
		}
3440
		$log[] = $log_entry;
3441
3442
		// Try add_option first, to make sure it's not autoloaded.
3443
		// @todo: Add an add_option method to Jetpack_Options
3444
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3445
			Jetpack_Options::update_option( 'log', $log );
3446
		}
3447
3448
		/**
3449
		 * Fires when Jetpack logs an internal event.
3450
		 *
3451
		 * @since 3.0.0
3452
		 *
3453
		 * @param array $log_entry {
3454
		 *	Array of details about the log entry.
3455
		 *
3456
		 *	@param string time Time of the event.
3457
		 *	@param int user_id ID of the user who trigerred the event.
3458
		 *	@param int blog_id Jetpack Blog ID.
3459
		 *	@param string code Unique name for the event.
3460
		 *	@param string data Data about the event.
3461
		 * }
3462
		 */
3463
		do_action( 'jetpack_log_entry', $log_entry );
3464
	}
3465
3466
	/**
3467
	 * Get the internal event log.
3468
	 *
3469
	 * @param $event (string) - only return the specific log events
3470
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3471
	 *
3472
	 * @return array of log events || WP_Error for invalid params
3473
	 */
3474
	public static function get_log( $event = false, $num = false ) {
3475
		if ( $event && ! is_string( $event ) ) {
3476
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3477
		}
3478
3479
		if ( $num && ! is_numeric( $num ) ) {
3480
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3481
		}
3482
3483
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3484
3485
		// If nothing set - act as it did before, otherwise let's start customizing the output
3486
		if ( ! $num && ! $event ) {
3487
			return $entire_log;
3488
		} else {
3489
			$entire_log = array_reverse( $entire_log );
3490
		}
3491
3492
		$custom_log_output = array();
3493
3494
		if ( $event ) {
3495
			foreach ( $entire_log as $log_event ) {
3496
				if ( $event == $log_event[ 'code' ] ) {
3497
					$custom_log_output[] = $log_event;
3498
				}
3499
			}
3500
		} else {
3501
			$custom_log_output = $entire_log;
3502
		}
3503
3504
		if ( $num ) {
3505
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3506
		}
3507
3508
		return $custom_log_output;
3509
	}
3510
3511
	/**
3512
	 * Log modification of important settings.
3513
	 */
3514
	public static function log_settings_change( $option, $old_value, $value ) {
3515
		switch( $option ) {
3516
			case 'jetpack_sync_non_public_post_stati':
3517
				self::log( $option, $value );
3518
				break;
3519
		}
3520
	}
3521
3522
	/**
3523
	 * Return stat data for WPCOM sync
3524
	 */
3525
	public static function get_stat_data( $encode = true, $extended = true ) {
3526
		$data = Jetpack_Heartbeat::generate_stats_array();
3527
3528
		if ( $extended ) {
3529
			$additional_data = self::get_additional_stat_data();
3530
			$data = array_merge( $data, $additional_data );
3531
		}
3532
3533
		if ( $encode ) {
3534
			return json_encode( $data );
3535
		}
3536
3537
		return $data;
3538
	}
3539
3540
	/**
3541
	 * Get additional stat data to sync to WPCOM
3542
	 */
3543
	public static function get_additional_stat_data( $prefix = '' ) {
3544
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3545
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3546
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3547
		$return["{$prefix}site-count"]     = 0;
3548
3549
		if ( function_exists( 'get_blog_count' ) ) {
3550
			$return["{$prefix}site-count"] = get_blog_count();
3551
		}
3552
		return $return;
3553
	}
3554
3555
	private static function get_site_user_count() {
3556
		global $wpdb;
3557
3558
		if ( function_exists( 'wp_is_large_network' ) ) {
3559
			if ( wp_is_large_network( 'users' ) ) {
3560
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3561
			}
3562
		}
3563
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3564
			// It wasn't there, so regenerate the data and save the transient
3565
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3566
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3567
		}
3568
		return $user_count;
3569
	}
3570
3571
	/* Admin Pages */
3572
3573
	function admin_init() {
3574
		// If the plugin is not connected, display a connect message.
3575
		if (
3576
			// the plugin was auto-activated and needs its candy
3577
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3578
		||
3579
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3580
			! Jetpack_Options::get_option( 'activated' )
3581
		) {
3582
			Jetpack::plugin_initialize();
3583
		}
3584
3585
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3586
			Jetpack_Connection_Banner::init();
3587
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3588
			// Upgrade: 1.1 -> 1.1.1
3589
			// Check and see if host can verify the Jetpack servers' SSL certificate
3590
			$args = array();
3591
			Client::_wp_remote_request(
3592
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3593
				$args,
3594
				true
3595
			);
3596
		}
3597
3598
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3599
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3600
		}
3601
3602
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3603
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3604
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3605
3606
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3607
			// Artificially throw errors in certain whitelisted cases during plugin activation
3608
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3609
		}
3610
3611
		// Add custom column in wp-admin/users.php to show whether user is linked.
3612
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3613
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3614
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3615
	}
3616
3617
	function admin_body_class( $admin_body_class = '' ) {
3618
		$classes = explode( ' ', trim( $admin_body_class ) );
3619
3620
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3621
3622
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3623
		return " $admin_body_class ";
3624
	}
3625
3626
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3627
		return $admin_body_class . ' jetpack-pagestyles ';
3628
	}
3629
3630
	/**
3631
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3632
	 * This function artificially throws errors for such cases (whitelisted).
3633
	 *
3634
	 * @param string $plugin The activated plugin.
3635
	 */
3636
	function throw_error_on_activate_plugin( $plugin ) {
3637
		$active_modules = Jetpack::get_active_modules();
3638
3639
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3640
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3641
			$throw = false;
3642
3643
			// Try and make sure it really was the stats plugin
3644
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3645
				if ( 'stats.php' == basename( $plugin ) ) {
3646
					$throw = true;
3647
				}
3648
			} else {
3649
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3650
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3651
					$throw = true;
3652
				}
3653
			}
3654
3655
			if ( $throw ) {
3656
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3657
			}
3658
		}
3659
	}
3660
3661
	function intercept_plugin_error_scrape_init() {
3662
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3663
	}
3664
3665
	function intercept_plugin_error_scrape( $action, $result ) {
3666
		if ( ! $result ) {
3667
			return;
3668
		}
3669
3670
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3671
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3672
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3673
			}
3674
		}
3675
	}
3676
3677
	function add_remote_request_handlers() {
3678
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3679
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3680
	}
3681
3682
	function remote_request_handlers() {
3683
		$action = current_filter();
3684
3685
		switch ( current_filter() ) {
3686
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3687
			$response = $this->upload_handler();
3688
			break;
3689
3690
		case 'wp_ajax_nopriv_jetpack_update_file' :
3691
			$response = $this->upload_handler( true );
3692
			break;
3693
		default :
3694
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3695
			break;
3696
		}
3697
3698
		if ( ! $response ) {
3699
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3700
		}
3701
3702
		if ( is_wp_error( $response ) ) {
3703
			$status_code       = $response->get_error_data();
3704
			$error             = $response->get_error_code();
3705
			$error_description = $response->get_error_message();
3706
3707
			if ( ! is_int( $status_code ) ) {
3708
				$status_code = 400;
3709
			}
3710
3711
			status_header( $status_code );
3712
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3713
		}
3714
3715
		status_header( 200 );
3716
		if ( true === $response ) {
3717
			exit;
3718
		}
3719
3720
		die( json_encode( (object) $response ) );
3721
	}
3722
3723
	/**
3724
	 * Uploads a file gotten from the global $_FILES.
3725
	 * If `$update_media_item` is true and `post_id` is defined
3726
	 * the attachment file of the media item (gotten through of the post_id)
3727
	 * will be updated instead of add a new one.
3728
	 *
3729
	 * @param  boolean $update_media_item - update media attachment
3730
	 * @return array - An array describing the uploadind files process
3731
	 */
3732
	function upload_handler( $update_media_item = false ) {
3733
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3734
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3735
		}
3736
3737
		$user = wp_authenticate( '', '' );
3738
		if ( ! $user || is_wp_error( $user ) ) {
3739
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3740
		}
3741
3742
		wp_set_current_user( $user->ID );
3743
3744
		if ( ! current_user_can( 'upload_files' ) ) {
3745
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3746
		}
3747
3748
		if ( empty( $_FILES ) ) {
3749
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3750
		}
3751
3752
		foreach ( array_keys( $_FILES ) as $files_key ) {
3753
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3754
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3755
			}
3756
		}
3757
3758
		$media_keys = array_keys( $_FILES['media'] );
3759
3760
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3761
		if ( ! $token || is_wp_error( $token ) ) {
3762
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3763
		}
3764
3765
		$uploaded_files = array();
3766
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3767
		unset( $GLOBALS['post'] );
3768
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3769
			$file = array();
3770
			foreach ( $media_keys as $media_key ) {
3771
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3772
			}
3773
3774
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3775
3776
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3777
			if ( $hmac_provided !== $hmac_file ) {
3778
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3779
				continue;
3780
			}
3781
3782
			$_FILES['.jetpack.upload.'] = $file;
3783
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3784
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3785
				$post_id = 0;
3786
			}
3787
3788
			if ( $update_media_item ) {
3789
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3790
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3791
				}
3792
3793
				$media_array = $_FILES['media'];
3794
3795
				$file_array['name'] = $media_array['name'][0];
3796
				$file_array['type'] = $media_array['type'][0];
3797
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3798
				$file_array['error'] = $media_array['error'][0];
3799
				$file_array['size'] = $media_array['size'][0];
3800
3801
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3802
3803
				if ( is_wp_error( $edited_media_item ) ) {
3804
					return $edited_media_item;
3805
				}
3806
3807
				$response = (object) array(
3808
					'id'   => (string) $post_id,
3809
					'file' => (string) $edited_media_item->post_title,
3810
					'url'  => (string) wp_get_attachment_url( $post_id ),
3811
					'type' => (string) $edited_media_item->post_mime_type,
3812
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3813
				);
3814
3815
				return (array) array( $response );
3816
			}
3817
3818
			$attachment_id = media_handle_upload(
3819
				'.jetpack.upload.',
3820
				$post_id,
3821
				array(),
3822
				array(
3823
					'action' => 'jetpack_upload_file',
3824
				)
3825
			);
3826
3827
			if ( ! $attachment_id ) {
3828
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3829
			} elseif ( is_wp_error( $attachment_id ) ) {
3830
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3831
			} else {
3832
				$attachment = get_post( $attachment_id );
3833
				$uploaded_files[$index] = (object) array(
3834
					'id'   => (string) $attachment_id,
3835
					'file' => $attachment->post_title,
3836
					'url'  => wp_get_attachment_url( $attachment_id ),
3837
					'type' => $attachment->post_mime_type,
3838
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3839
				);
3840
				// Zip files uploads are not supported unless they are done for installation purposed
3841
				// lets delete them in case something goes wrong in this whole process
3842
				if ( 'application/zip' === $attachment->post_mime_type ) {
3843
					// Schedule a cleanup for 2 hours from now in case of failed install.
3844
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3845
				}
3846
			}
3847
		}
3848
		if ( ! is_null( $global_post ) ) {
3849
			$GLOBALS['post'] = $global_post;
3850
		}
3851
3852
		return $uploaded_files;
3853
	}
3854
3855
	/**
3856
	 * Add help to the Jetpack page
3857
	 *
3858
	 * @since Jetpack (1.2.3)
3859
	 * @return false if not the Jetpack page
3860
	 */
3861
	function admin_help() {
3862
		$current_screen = get_current_screen();
3863
3864
		// Overview
3865
		$current_screen->add_help_tab(
3866
			array(
3867
				'id'		=> 'home',
3868
				'title'		=> __( 'Home', 'jetpack' ),
3869
				'content'	=>
3870
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3871
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3872
					'<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>',
3873
			)
3874
		);
3875
3876
		// Screen Content
3877
		if ( current_user_can( 'manage_options' ) ) {
3878
			$current_screen->add_help_tab(
3879
				array(
3880
					'id'		=> 'settings',
3881
					'title'		=> __( 'Settings', 'jetpack' ),
3882
					'content'	=>
3883
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3884
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3885
						'<ol>' .
3886
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3887
							'<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>' .
3888
						'</ol>' .
3889
						'<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>'
3890
				)
3891
			);
3892
		}
3893
3894
		// Help Sidebar
3895
		$current_screen->set_help_sidebar(
3896
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3897
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3898
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3899
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3900
		);
3901
	}
3902
3903
	function admin_menu_css() {
3904
		wp_enqueue_style( 'jetpack-icons' );
3905
	}
3906
3907
	function admin_menu_order() {
3908
		return true;
3909
	}
3910
3911 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3912
		$jp_menu_order = array();
3913
3914
		foreach ( $menu_order as $index => $item ) {
3915
			if ( $item != 'jetpack' ) {
3916
				$jp_menu_order[] = $item;
3917
			}
3918
3919
			if ( $index == 0 ) {
3920
				$jp_menu_order[] = 'jetpack';
3921
			}
3922
		}
3923
3924
		return $jp_menu_order;
3925
	}
3926
3927
	function admin_banner_styles() {
3928
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3929
3930
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3931
			wp_register_style(
3932
				'jetpack-dops-style',
3933
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3934
				array(),
3935
				JETPACK__VERSION
3936
			);
3937
		}
3938
3939
		wp_enqueue_style(
3940
			'jetpack',
3941
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3942
			array( 'jetpack-dops-style' ),
3943
			 JETPACK__VERSION . '-20121016'
3944
		);
3945
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3946
		wp_style_add_data( 'jetpack', 'suffix', $min );
3947
	}
3948
3949
	function plugin_action_links( $actions ) {
3950
3951
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3952
3953
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3954
			return array_merge(
3955
				$jetpack_home,
3956
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3957
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3958
				$actions
3959
				);
3960
			}
3961
3962
		return array_merge( $jetpack_home, $actions );
3963
	}
3964
3965
	/*
3966
	 * Registration flow:
3967
	 * 1 - ::admin_page_load() action=register
3968
	 * 2 - ::try_registration()
3969
	 * 3 - ::register()
3970
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3971
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3972
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3973
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3974
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3975
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3976
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3977
	 *       jetpack_id, jetpack_secret, jetpack_public
3978
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3979
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3980
	 * 5 - user logs in with WP.com account
3981
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3982
	 *		- Jetpack_Client_Server::authorize()
3983
	 *		- Jetpack_Client_Server::get_token()
3984
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3985
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3986
	 *			- which responds with access_token, token_type, scope
3987
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3988
	 *		- Jetpack::activate_default_modules()
3989
	 *     		- Deactivates deprecated plugins
3990
	 *     		- Activates all default modules
3991
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3992
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3993
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3994
	 *     Done!
3995
	 */
3996
3997
	/**
3998
	 * Handles the page load events for the Jetpack admin page
3999
	 */
4000
	function admin_page_load() {
4001
		$error = false;
4002
4003
		// Make sure we have the right body class to hook stylings for subpages off of.
4004
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4005
4006
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4007
			// Should only be used in intermediate redirects to preserve state across redirects
4008
			Jetpack::restate();
4009
		}
4010
4011
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4012
			// @todo: Add validation against a known whitelist
4013
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4014
			// User clicked in the iframe to link their accounts
4015
			if ( ! Jetpack::is_user_connected() ) {
4016
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4017
4018
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4019
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4020
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4021
4022
				if ( isset( $_GET['notes_iframe'] ) )
4023
					$connect_url .= '&notes_iframe';
4024
				wp_redirect( $connect_url );
4025
				exit;
4026
			} else {
4027
				if ( ! isset( $_GET['calypso_env'] ) ) {
4028
					Jetpack::state( 'message', 'already_authorized' );
4029
					wp_safe_redirect( Jetpack::admin_url() );
4030
					exit;
4031
				} else {
4032
					$connect_url = $this->build_connect_url( true, false, $from );
4033
					$connect_url .= '&already_authorized=true';
4034
					wp_redirect( $connect_url );
4035
					exit;
4036
				}
4037
			}
4038
		}
4039
4040
4041
		if ( isset( $_GET['action'] ) ) {
4042
			switch ( $_GET['action'] ) {
4043
			case 'authorize':
4044
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4045
					Jetpack::state( 'message', 'already_authorized' );
4046
					wp_safe_redirect( Jetpack::admin_url() );
4047
					exit;
4048
				}
4049
				Jetpack::log( 'authorize' );
4050
				$client_server = new Jetpack_Client_Server;
4051
				$client_server->client_authorize();
4052
				exit;
4053
			case 'register' :
4054
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4055
					$error = 'cheatin';
4056
					break;
4057
				}
4058
				check_admin_referer( 'jetpack-register' );
4059
				Jetpack::log( 'register' );
4060
				Jetpack::maybe_set_version_option();
4061
				$registered = Jetpack::try_registration();
4062
				if ( is_wp_error( $registered ) ) {
4063
					$error = $registered->get_error_code();
4064
					Jetpack::state( 'error', $error );
4065
					Jetpack::state( 'error', $registered->get_error_message() );
4066
4067
					/**
4068
					 * Jetpack registration Error.
4069
					 *
4070
					 * @since 7.5.0
4071
					 *
4072
					 * @param string|int $error The error code.
4073
					 * @param \WP_Error $registered The error object.
4074
					 */
4075
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4076
					break;
4077
				}
4078
4079
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4080
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4081
4082
				/**
4083
				 * Jetpack registration Success.
4084
				 *
4085
				 * @since 7.5.0
4086
				 *
4087
				 * @param string $from 'from' GET parameter;
4088
				 */
4089
				do_action( 'jetpack_connection_register_success', $from );
4090
4091
				$url = $this->build_connect_url( true, $redirect, $from );
4092
4093
				if ( ! empty( $_GET['onboarding'] ) ) {
4094
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4095
				}
4096
4097
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4098
					$url = add_query_arg( 'auth_approved', 'true', $url );
4099
				}
4100
4101
				wp_redirect( $url );
4102
				exit;
4103
			case 'activate' :
4104
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4105
					$error = 'cheatin';
4106
					break;
4107
				}
4108
4109
				$module = stripslashes( $_GET['module'] );
4110
				check_admin_referer( "jetpack_activate-$module" );
4111
				Jetpack::log( 'activate', $module );
4112
				if ( ! Jetpack::activate_module( $module ) ) {
4113
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4114
				}
4115
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4116
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4117
				exit;
4118
			case 'activate_default_modules' :
4119
				check_admin_referer( 'activate_default_modules' );
4120
				Jetpack::log( 'activate_default_modules' );
4121
				Jetpack::restate();
4122
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4123
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4124
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4125
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4126
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4127
				exit;
4128
			case 'disconnect' :
4129
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4130
					$error = 'cheatin';
4131
					break;
4132
				}
4133
4134
				check_admin_referer( 'jetpack-disconnect' );
4135
				Jetpack::log( 'disconnect' );
4136
				Jetpack::disconnect();
4137
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4138
				exit;
4139
			case 'reconnect' :
4140
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4141
					$error = 'cheatin';
4142
					break;
4143
				}
4144
4145
				check_admin_referer( 'jetpack-reconnect' );
4146
				Jetpack::log( 'reconnect' );
4147
				$this->disconnect();
4148
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4149
				exit;
4150 View Code Duplication
			case 'deactivate' :
4151
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4152
					$error = 'cheatin';
4153
					break;
4154
				}
4155
4156
				$modules = stripslashes( $_GET['module'] );
4157
				check_admin_referer( "jetpack_deactivate-$modules" );
4158
				foreach ( explode( ',', $modules ) as $module ) {
4159
					Jetpack::log( 'deactivate', $module );
4160
					Jetpack::deactivate_module( $module );
4161
					Jetpack::state( 'message', 'module_deactivated' );
4162
				}
4163
				Jetpack::state( 'module', $modules );
4164
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4165
				exit;
4166
			case 'unlink' :
4167
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4168
				check_admin_referer( 'jetpack-unlink' );
4169
				Jetpack::log( 'unlink' );
4170
				$this->unlink_user();
4171
				Jetpack::state( 'message', 'unlinked' );
4172
				if ( 'sub-unlink' == $redirect ) {
4173
					wp_safe_redirect( admin_url() );
4174
				} else {
4175
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4176
				}
4177
				exit;
4178
			case 'onboard' :
4179
				if ( ! current_user_can( 'manage_options' ) ) {
4180
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4181
				} else {
4182
					Jetpack::create_onboarding_token();
4183
					$url = $this->build_connect_url( true );
4184
4185
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4186
						$url = add_query_arg( 'onboarding', $token, $url );
4187
					}
4188
4189
					$calypso_env = $this->get_calypso_env();
4190
					if ( ! empty( $calypso_env ) ) {
4191
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4192
					}
4193
4194
					wp_redirect( $url );
4195
					exit;
4196
				}
4197
				exit;
4198
			default:
4199
				/**
4200
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4201
				 *
4202
				 * @since 2.6.0
4203
				 *
4204
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4205
				 */
4206
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4207
			}
4208
		}
4209
4210
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4211
			self::activate_new_modules( true );
4212
		}
4213
4214
		$message_code = Jetpack::state( 'message' );
4215
		if ( Jetpack::state( 'optin-manage' ) ) {
4216
			$activated_manage = $message_code;
4217
			$message_code = 'jetpack-manage';
4218
		}
4219
4220
		switch ( $message_code ) {
4221
		case 'jetpack-manage':
4222
			$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>';
4223
			if ( $activated_manage ) {
4224
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4225
			}
4226
			break;
4227
4228
		}
4229
4230
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4231
4232
		if ( ! empty( $deactivated_plugins ) ) {
4233
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4234
			$deactivated_titles  = array();
4235
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4236
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4237
					continue;
4238
				}
4239
4240
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4241
			}
4242
4243
			if ( $deactivated_titles ) {
4244
				if ( $this->message ) {
4245
					$this->message .= "<br /><br />\n";
4246
				}
4247
4248
				$this->message .= wp_sprintf(
4249
					_n(
4250
						'Jetpack contains the most recent version of the old %l plugin.',
4251
						'Jetpack contains the most recent versions of the old %l plugins.',
4252
						count( $deactivated_titles ),
4253
						'jetpack'
4254
					),
4255
					$deactivated_titles
4256
				);
4257
4258
				$this->message .= "<br />\n";
4259
4260
				$this->message .= _n(
4261
					'The old version has been deactivated and can be removed from your site.',
4262
					'The old versions have been deactivated and can be removed from your site.',
4263
					count( $deactivated_titles ),
4264
					'jetpack'
4265
				);
4266
			}
4267
		}
4268
4269
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4270
4271
		if ( $this->message || $this->error || $this->privacy_checks ) {
4272
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4273
		}
4274
4275
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4276
	}
4277
4278
	function admin_notices() {
4279
4280
		if ( $this->error ) {
4281
?>
4282
<div id="message" class="jetpack-message jetpack-err">
4283
	<div class="squeezer">
4284
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4285
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4286
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4287
<?php	endif; ?>
4288
	</div>
4289
</div>
4290
<?php
4291
		}
4292
4293
		if ( $this->message ) {
4294
?>
4295
<div id="message" class="jetpack-message">
4296
	<div class="squeezer">
4297
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4298
	</div>
4299
</div>
4300
<?php
4301
		}
4302
4303
		if ( $this->privacy_checks ) :
4304
			$module_names = $module_slugs = array();
4305
4306
			$privacy_checks = explode( ',', $this->privacy_checks );
4307
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4308
			foreach ( $privacy_checks as $module_slug ) {
4309
				$module = Jetpack::get_module( $module_slug );
4310
				if ( ! $module ) {
4311
					continue;
4312
				}
4313
4314
				$module_slugs[] = $module_slug;
4315
				$module_names[] = "<strong>{$module['name']}</strong>";
4316
			}
4317
4318
			$module_slugs = join( ',', $module_slugs );
4319
?>
4320
<div id="message" class="jetpack-message jetpack-err">
4321
	<div class="squeezer">
4322
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4323
		<p><?php
4324
			echo wp_kses(
4325
				wptexturize(
4326
					wp_sprintf(
4327
						_nx(
4328
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4329
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4330
							count( $privacy_checks ),
4331
							'%l = list of Jetpack module/feature names',
4332
							'jetpack'
4333
						),
4334
						$module_names
4335
					)
4336
				),
4337
				array( 'strong' => true )
4338
			);
4339
4340
			echo "\n<br />\n";
4341
4342
			echo wp_kses(
4343
				sprintf(
4344
					_nx(
4345
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4346
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4347
						count( $privacy_checks ),
4348
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4349
						'jetpack'
4350
					),
4351
					wp_nonce_url(
4352
						Jetpack::admin_url(
4353
							array(
4354
								'page'   => 'jetpack',
4355
								'action' => 'deactivate',
4356
								'module' => urlencode( $module_slugs ),
4357
							)
4358
						),
4359
						"jetpack_deactivate-$module_slugs"
4360
					),
4361
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4362
				),
4363
				array( 'a' => array( 'href' => true, 'title' => true ) )
4364
			);
4365
		?></p>
4366
	</div>
4367
</div>
4368
<?php endif;
4369
	}
4370
4371
	/**
4372
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4373
	 */
4374
	function stat( $group, $detail ) {
4375
		if ( ! isset( $this->stats[ $group ] ) )
4376
			$this->stats[ $group ] = array();
4377
		$this->stats[ $group ][] = $detail;
4378
	}
4379
4380
	/**
4381
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4382
	 */
4383
	function do_stats( $method = '' ) {
4384
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4385
			foreach ( $this->stats as $group => $stats ) {
4386
				if ( is_array( $stats ) && count( $stats ) ) {
4387
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4388
					if ( 'server_side' === $method ) {
4389
						self::do_server_side_stat( $args );
4390
					} else {
4391
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4392
					}
4393
				}
4394
				unset( $this->stats[ $group ] );
4395
			}
4396
		}
4397
	}
4398
4399
	/**
4400
	 * Runs stats code for a one-off, server-side.
4401
	 *
4402
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4403
	 *
4404
	 * @return bool If it worked.
4405
	 */
4406
	static function do_server_side_stat( $args ) {
4407
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4408
		if ( is_wp_error( $response ) )
4409
			return false;
4410
4411
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4412
			return false;
4413
4414
		return true;
4415
	}
4416
4417
	/**
4418
	 * Builds the stats url.
4419
	 *
4420
	 * @param $args array|string The arguments to append to the URL.
4421
	 *
4422
	 * @return string The URL to be pinged.
4423
	 */
4424
	static function build_stats_url( $args ) {
4425
		$defaults = array(
4426
			'v'    => 'wpcom2',
4427
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4428
		);
4429
		$args     = wp_parse_args( $args, $defaults );
4430
		/**
4431
		 * Filter the URL used as the Stats tracking pixel.
4432
		 *
4433
		 * @since 2.3.2
4434
		 *
4435
		 * @param string $url Base URL used as the Stats tracking pixel.
4436
		 */
4437
		$base_url = apply_filters(
4438
			'jetpack_stats_base_url',
4439
			'https://pixel.wp.com/g.gif'
4440
		);
4441
		$url      = add_query_arg( $args, $base_url );
4442
		return $url;
4443
	}
4444
4445
	/**
4446
	 * Get the role of the current user.
4447
	 *
4448
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4449
	 *
4450
	 * @access public
4451
	 * @static
4452
	 *
4453
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4454
	 */
4455
	public static function translate_current_user_to_role() {
4456
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4457
4458
		$roles = new Roles();
4459
		return $roles->translate_current_user_to_role();
4460
	}
4461
4462
	/**
4463
	 * Get the role of a particular user.
4464
	 *
4465
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4466
	 *
4467
	 * @access public
4468
	 * @static
4469
	 *
4470
	 * @param \WP_User $user User object.
4471
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4472
	 */
4473
	public static function translate_user_to_role( $user ) {
4474
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4475
4476
		$roles = new Roles();
4477
		return $roles->translate_user_to_role( $user );
4478
	}
4479
4480
	/**
4481
	 * Get the minimum capability for a role.
4482
	 *
4483
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4484
	 *
4485
	 * @access public
4486
	 * @static
4487
	 *
4488
	 * @param string $role Role name.
4489
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4490
	 */
4491
	public static function translate_role_to_cap( $role ) {
4492
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4493
4494
		$roles = new Roles();
4495
		return $roles->translate_role_to_cap( $role );
4496
	}
4497
4498
	static function sign_role( $role, $user_id = null ) {
4499
		if ( empty( $user_id ) ) {
4500
			$user_id = (int) get_current_user_id();
4501
		}
4502
4503
		if ( ! $user_id  ) {
4504
			return false;
4505
		}
4506
4507
		$token = Jetpack_Data::get_access_token();
4508
		if ( ! $token || is_wp_error( $token ) ) {
4509
			return false;
4510
		}
4511
4512
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4513
	}
4514
4515
4516
	/**
4517
	 * Builds a URL to the Jetpack connection auth page
4518
	 *
4519
	 * @since 3.9.5
4520
	 *
4521
	 * @param bool $raw If true, URL will not be escaped.
4522
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4523
	 *                              If string, will be a custom redirect.
4524
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4525
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4526
	 *
4527
	 * @return string Connect URL
4528
	 */
4529
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4530
		$site_id = Jetpack_Options::get_option( 'id' );
4531
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4532
4533
		if ( $register || ! $blog_token || ! $site_id ) {
4534
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4535
4536
			if ( ! empty( $redirect ) ) {
4537
				$url = add_query_arg(
4538
					'redirect',
4539
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4540
					$url
4541
				);
4542
			}
4543
4544
			if( is_network_admin() ) {
4545
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4546
			}
4547
		} else {
4548
4549
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4550
			// because otherwise this logic can get us in to a loop.
4551
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4552
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4553
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4554
4555
				$response = Client::wpcom_json_api_request_as_blog(
4556
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4557
					'1.1'
4558
				);
4559
4560
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4561
4562
					// Generating a register URL instead to refresh the existing token
4563
					return $this->build_connect_url( $raw, $redirect, $from, true );
4564
				}
4565
			}
4566
4567
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4568
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4569
			}
4570
4571
			$roles       = new Roles();
4572
			$role        = $roles->translate_current_user_to_role();
4573
			$signed_role = self::sign_role( $role );
4574
4575
			$user = wp_get_current_user();
4576
4577
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4578
			$redirect = $redirect
4579
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4580
				: $jetpack_admin_page;
4581
4582
			if( isset( $_REQUEST['is_multisite'] ) ) {
4583
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4584
			}
4585
4586
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4587
4588
			/**
4589
			 * Filter the type of authorization.
4590
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4591
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4592
			 *
4593
			 * @since 4.3.3
4594
			 *
4595
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4596
			 */
4597
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4598
4599
4600
			$tracks = new Tracking();
4601
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4602
4603
			$args = urlencode_deep(
4604
				array(
4605
					'response_type' => 'code',
4606
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4607
					'redirect_uri'  => add_query_arg(
4608
						array(
4609
							'action'   => 'authorize',
4610
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4611
							'redirect' => urlencode( $redirect ),
4612
						),
4613
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4614
					),
4615
					'state'         => $user->ID,
4616
					'scope'         => $signed_role,
4617
					'user_email'    => $user->user_email,
4618
					'user_login'    => $user->user_login,
4619
					'is_active'     => Jetpack::is_active(),
4620
					'jp_version'    => JETPACK__VERSION,
4621
					'auth_type'     => $auth_type,
4622
					'secret'        => $secrets['secret_1'],
4623
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4624
					'blogname'      => get_option( 'blogname' ),
4625
					'site_url'      => site_url(),
4626
					'home_url'      => home_url(),
4627
					'site_icon'     => get_site_icon_url(),
4628
					'site_lang'     => get_locale(),
4629
					'_ui'           => $tracks_identity['_ui'],
4630
					'_ut'           => $tracks_identity['_ut'],
4631
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4632
				)
4633
			);
4634
4635
			self::apply_activation_source_to_args( $args );
4636
4637
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4638
		}
4639
4640
		if ( $from ) {
4641
			$url = add_query_arg( 'from', $from, $url );
4642
		}
4643
4644
		// Ensure that class to get the affiliate code is loaded
4645
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4646
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4647
		}
4648
		// Get affiliate code and add it to the URL
4649
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4650
4651
		$calypso_env = $this->get_calypso_env();
4652
4653
		if ( ! empty( $calypso_env ) ) {
4654
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4655
		}
4656
4657
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4658
	}
4659
4660
	/**
4661
	 * Get our assumed site creation date.
4662
	 * Calculated based on the earlier date of either:
4663
	 * - Earliest admin user registration date.
4664
	 * - Earliest date of post of any post type.
4665
	 *
4666
	 * @since 7.2.0
4667
	 *
4668
	 * @return string Assumed site creation date and time.
4669
	 */
4670
	public static function get_assumed_site_creation_date() {
4671
		$earliest_registered_users = get_users( array(
4672
			'role'    => 'administrator',
4673
			'orderby' => 'user_registered',
4674
			'order'   => 'ASC',
4675
			'fields'  => array( 'user_registered' ),
4676
			'number'  => 1,
4677
		) );
4678
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4679
4680
		$earliest_posts = get_posts( array(
4681
			'posts_per_page' => 1,
4682
			'post_type'      => 'any',
4683
			'post_status'    => 'any',
4684
			'orderby'        => 'date',
4685
			'order'          => 'ASC',
4686
		) );
4687
4688
		// If there are no posts at all, we'll count only on user registration date.
4689
		if ( $earliest_posts ) {
4690
			$earliest_post_date = $earliest_posts[0]->post_date;
4691
		} else {
4692
			$earliest_post_date = PHP_INT_MAX;
4693
		}
4694
4695
		return min( $earliest_registration_date, $earliest_post_date );
4696
	}
4697
4698
	public static function apply_activation_source_to_args( &$args ) {
4699
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4700
4701
		if ( $activation_source_name ) {
4702
			$args['_as'] = urlencode( $activation_source_name );
4703
		}
4704
4705
		if ( $activation_source_keyword ) {
4706
			$args['_ak'] = urlencode( $activation_source_keyword );
4707
		}
4708
	}
4709
4710
	function build_reconnect_url( $raw = false ) {
4711
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4712
		return $raw ? $url : esc_url( $url );
4713
	}
4714
4715
	public static function admin_url( $args = null ) {
4716
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4717
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4718
		return $url;
4719
	}
4720
4721
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4722
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4723
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4724
	}
4725
4726
	function dismiss_jetpack_notice() {
4727
4728
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4729
			return;
4730
		}
4731
4732
		switch( $_GET['jetpack-notice'] ) {
4733
			case 'dismiss':
4734
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4735
4736
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4737
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4738
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4739
				}
4740
				break;
4741
			case 'jetpack-protect-multisite-opt-out':
4742
4743
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4744
					// Don't show the banner again
4745
4746
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4747
					// redirect back to the page that had the notice
4748
					if ( wp_get_referer() ) {
4749
						wp_safe_redirect( wp_get_referer() );
4750
					} else {
4751
						// Take me to Jetpack
4752
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4753
					}
4754
				}
4755
				break;
4756
		}
4757
	}
4758
4759
	public static function sort_modules( $a, $b ) {
4760
		if ( $a['sort'] == $b['sort'] )
4761
			return 0;
4762
4763
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4764
	}
4765
4766
	function ajax_recheck_ssl() {
4767
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4768
		$result = Jetpack::permit_ssl( true );
4769
		wp_send_json( array(
4770
			'enabled' => $result,
4771
			'message' => get_transient( 'jetpack_https_test_message' )
4772
		) );
4773
	}
4774
4775
/* Client API */
4776
4777
	/**
4778
	 * Returns the requested Jetpack API URL
4779
	 *
4780
	 * @return string
4781
	 */
4782
	public static function api_url( $relative_url ) {
4783
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4784
	}
4785
4786
	/**
4787
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4788
	 */
4789
	public static function fix_url_for_bad_hosts( $url ) {
4790
		if ( 0 !== strpos( $url, 'https://' ) ) {
4791
			return $url;
4792
		}
4793
4794
		switch ( JETPACK_CLIENT__HTTPS ) {
4795
			case 'ALWAYS' :
4796
				return $url;
4797
			case 'NEVER' :
4798
				return set_url_scheme( $url, 'http' );
4799
			// default : case 'AUTO' :
4800
		}
4801
4802
		// we now return the unmodified SSL URL by default, as a security precaution
4803
		return $url;
4804
	}
4805
4806
	/**
4807
	 * Create a random secret for validating onboarding payload
4808
	 *
4809
	 * @return string Secret token
4810
	 */
4811
	public static function create_onboarding_token() {
4812
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4813
			$token = wp_generate_password( 32, false );
4814
			Jetpack_Options::update_option( 'onboarding', $token );
4815
		}
4816
4817
		return $token;
4818
	}
4819
4820
	/**
4821
	 * Remove the onboarding token
4822
	 *
4823
	 * @return bool True on success, false on failure
4824
	 */
4825
	public static function invalidate_onboarding_token() {
4826
		return Jetpack_Options::delete_option( 'onboarding' );
4827
	}
4828
4829
	/**
4830
	 * Validate an onboarding token for a specific action
4831
	 *
4832
	 * @return boolean True if token/action pair is accepted, false if not
4833
	 */
4834
	public static function validate_onboarding_token_action( $token, $action ) {
4835
		// Compare tokens, bail if tokens do not match
4836
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4837
			return false;
4838
		}
4839
4840
		// List of valid actions we can take
4841
		$valid_actions = array(
4842
			'/jetpack/v4/settings',
4843
		);
4844
4845
		// Whitelist the action
4846
		if ( ! in_array( $action, $valid_actions ) ) {
4847
			return false;
4848
		}
4849
4850
		return true;
4851
	}
4852
4853
	/**
4854
	 * Checks to see if the URL is using SSL to connect with Jetpack
4855
	 *
4856
	 * @since 2.3.3
4857
	 * @return boolean
4858
	 */
4859
	public static function permit_ssl( $force_recheck = false ) {
4860
		// Do some fancy tests to see if ssl is being supported
4861
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4862
			$message = '';
4863
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4864
				$ssl = 0;
4865
			} else {
4866
				switch ( JETPACK_CLIENT__HTTPS ) {
4867
					case 'NEVER':
4868
						$ssl = 0;
4869
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4870
						break;
4871
					case 'ALWAYS':
4872
					case 'AUTO':
4873
					default:
4874
						$ssl = 1;
4875
						break;
4876
				}
4877
4878
				// If it's not 'NEVER', test to see
4879
				if ( $ssl ) {
4880
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4881
						$ssl = 0;
4882
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4883
					} else {
4884
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4885
						if ( is_wp_error( $response ) ) {
4886
							$ssl = 0;
4887
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4888
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4889
							$ssl = 0;
4890
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4891
						}
4892
					}
4893
				}
4894
			}
4895
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4896
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4897
		}
4898
4899
		return (bool) $ssl;
4900
	}
4901
4902
	/*
4903
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4904
	 */
4905
	public function alert_auto_ssl_fail() {
4906
		if ( ! current_user_can( 'manage_options' ) )
4907
			return;
4908
4909
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4910
		?>
4911
4912
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4913
			<div class="jp-banner__content">
4914
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4915
				<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>
4916
				<p>
4917
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4918
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4919
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4920
				</p>
4921
				<p>
4922
					<?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' ),
4923
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4924
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4925
				</p>
4926
			</div>
4927
		</div>
4928
		<style>
4929
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4930
		</style>
4931
		<script type="text/javascript">
4932
			jQuery( document ).ready( function( $ ) {
4933
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4934
					var $this = $( this );
4935
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4936
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4937
					e.preventDefault();
4938
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4939
					$.post( ajaxurl, data )
4940
					  .done( function( response ) {
4941
					  	if ( response.enabled ) {
4942
					  		$( '#jetpack-ssl-warning' ).hide();
4943
					  	} else {
4944
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4945
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4946
					  	}
4947
					  }.bind( $this ) );
4948
				} );
4949
			} );
4950
		</script>
4951
4952
		<?php
4953
	}
4954
4955
	/**
4956
	 * Returns the Jetpack XML-RPC API
4957
	 *
4958
	 * @return string
4959
	 */
4960
	public static function xmlrpc_api_url() {
4961
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4962
		return untrailingslashit( $base ) . '/xmlrpc.php';
4963
	}
4964
4965
	public static function connection() {
4966
		return self::init()->connection_manager;
4967
	}
4968
4969
	/**
4970
	 * Creates two secret tokens and the end of life timestamp for them.
4971
	 *
4972
	 * Note these tokens are unique per call, NOT static per site for connecting.
4973
	 *
4974
	 * @since 2.6
4975
	 * @return array
4976
	 */
4977
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4978
		if ( false === $user_id ) {
4979
			$user_id = get_current_user_id();
4980
		}
4981
4982
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4983
	}
4984
4985
	public static function get_secrets( $action, $user_id ) {
4986
		$secrets = self::connection()->get_secrets( $action, $user_id );
4987
4988
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4989
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4990
		}
4991
4992
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4993
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4994
		}
4995
4996
		return $secrets;
4997
	}
4998
4999
	/**
5000
	 * @deprecated 7.5 Use Connection_Manager instead.
5001
	 *
5002
	 * @param $action
5003
	 * @param $user_id
5004
	 */
5005
	public static function delete_secrets( $action, $user_id ) {
5006
		return self::connection()->delete_secrets( $action, $user_id );
5007
	}
5008
5009
	/**
5010
	 * Builds the timeout limit for queries talking with the wpcom servers.
5011
	 *
5012
	 * Based on local php max_execution_time in php.ini
5013
	 *
5014
	 * @since 2.6
5015
	 * @return int
5016
	 * @deprecated
5017
	 **/
5018
	public function get_remote_query_timeout_limit() {
5019
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5020
		return Jetpack::get_max_execution_time();
5021
	}
5022
5023
	/**
5024
	 * Builds the timeout limit for queries talking with the wpcom servers.
5025
	 *
5026
	 * Based on local php max_execution_time in php.ini
5027
	 *
5028
	 * @since 5.4
5029
	 * @return int
5030
	 **/
5031
	public static function get_max_execution_time() {
5032
		$timeout = (int) ini_get( 'max_execution_time' );
5033
5034
		// Ensure exec time set in php.ini
5035
		if ( ! $timeout ) {
5036
			$timeout = 30;
5037
		}
5038
		return $timeout;
5039
	}
5040
5041
	/**
5042
	 * Sets a minimum request timeout, and returns the current timeout
5043
	 *
5044
	 * @since 5.4
5045
	 **/
5046
	public static function set_min_time_limit( $min_timeout ) {
5047
		$timeout = self::get_max_execution_time();
5048
		if ( $timeout < $min_timeout ) {
5049
			$timeout = $min_timeout;
5050
			set_time_limit( $timeout );
5051
		}
5052
		return $timeout;
5053
	}
5054
5055
5056
	/**
5057
	 * Takes the response from the Jetpack register new site endpoint and
5058
	 * verifies it worked properly.
5059
	 *
5060
	 * @since 2.6
5061
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5062
	 **/
5063
	public function validate_remote_register_response( $response ) {
5064
	  if ( is_wp_error( $response ) ) {
5065
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5066
		}
5067
5068
		$code   = wp_remote_retrieve_response_code( $response );
5069
		$entity = wp_remote_retrieve_body( $response );
5070
		if ( $entity )
5071
			$registration_response = json_decode( $entity );
5072
		else
5073
			$registration_response = false;
5074
5075
		$code_type = intval( $code / 100 );
5076
		if ( 5 == $code_type ) {
5077
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5078
		} elseif ( 408 == $code ) {
5079
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5080
		} elseif ( ! empty( $registration_response->error ) ) {
5081
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5082
				$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' );
5083
			} else {
5084
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5085
			}
5086
5087
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5088
		} elseif ( 200 != $code ) {
5089
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5090
		}
5091
5092
		// Jetpack ID error block
5093
		if ( empty( $registration_response->jetpack_id ) ) {
5094
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5095
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5096
			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 );
5097
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5098
			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 );
5099
		}
5100
5101
	    return $registration_response;
5102
	}
5103
	/**
5104
	 * @return bool|WP_Error
5105
	 */
5106
	public static function register() {
5107
		$tracking = new Tracking();
5108
		$tracking->record_user_event( 'jpc_register_begin' );
5109
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5110
		$secrets = Jetpack::generate_secrets( 'register' );
5111
5112 View Code Duplication
		if (
5113
			empty( $secrets['secret_1'] ) ||
5114
			empty( $secrets['secret_2'] ) ||
5115
			empty( $secrets['exp'] )
5116
		) {
5117
			return new Jetpack_Error( 'missing_secrets' );
5118
		}
5119
5120
		// better to try (and fail) to set a higher timeout than this system
5121
		// supports than to have register fail for more users than it should
5122
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5123
5124
		$gmt_offset = get_option( 'gmt_offset' );
5125
		if ( ! $gmt_offset ) {
5126
			$gmt_offset = 0;
5127
		}
5128
5129
		$stats_options = get_option( 'stats_options' );
5130
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5131
5132
		$tracks = new Tracking();
5133
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5134
5135
		$args = array(
5136
			'method'  => 'POST',
5137
			'body'    => array(
5138
				'siteurl'         => site_url(),
5139
				'home'            => home_url(),
5140
				'gmt_offset'      => $gmt_offset,
5141
				'timezone_string' => (string) get_option( 'timezone_string' ),
5142
				'site_name'       => (string) get_option( 'blogname' ),
5143
				'secret_1'        => $secrets['secret_1'],
5144
				'secret_2'        => $secrets['secret_2'],
5145
				'site_lang'       => get_locale(),
5146
				'timeout'         => $timeout,
5147
				'stats_id'        => $stats_id,
5148
				'state'           => get_current_user_id(),
5149
				'_ui'             => $tracks_identity['_ui'],
5150
				'_ut'             => $tracks_identity['_ut'],
5151
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5152
				'jetpack_version' => JETPACK__VERSION,
5153
				'ABSPATH'         => defined( 'ABSPATH' ) ? ABSPATH : '',
5154
			),
5155
			'headers' => array(
5156
				'Accept' => 'application/json',
5157
			),
5158
			'timeout' => $timeout,
5159
		);
5160
5161
		self::apply_activation_source_to_args( $args['body'] );
5162
5163
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5164
5165
		// Make sure the response is valid and does not contain any Jetpack errors
5166
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5167
		if ( is_wp_error( $registration_details ) ) {
5168
			return $registration_details;
5169
		} elseif ( ! $registration_details ) {
5170
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5171
		}
5172
5173 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5174
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5175
		}
5176
5177
		if ( isset( $registration_details->jetpack_public ) ) {
5178
			$jetpack_public = (int) $registration_details->jetpack_public;
5179
		} else {
5180
			$jetpack_public = false;
5181
		}
5182
5183
		Jetpack_Options::update_options(
5184
			array(
5185
				'id'         => (int)    $registration_details->jetpack_id,
5186
				'blog_token' => (string) $registration_details->jetpack_secret,
5187
				'public'     => $jetpack_public,
5188
			)
5189
		);
5190
5191
		/**
5192
		 * Fires when a site is registered on WordPress.com.
5193
		 *
5194
		 * @since 3.7.0
5195
		 *
5196
		 * @param int $json->jetpack_id Jetpack Blog ID.
5197
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5198
		 * @param int|bool $jetpack_public Is the site public.
5199
		 */
5200
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5201
5202
		$jetpack = Jetpack::init();
5203
5204
		return true;
5205
	}
5206
5207
	/**
5208
	 * If the db version is showing something other that what we've got now, bump it to current.
5209
	 *
5210
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5211
	 */
5212
	public static function maybe_set_version_option() {
5213
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5214
		if ( JETPACK__VERSION != $version ) {
5215
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5216
5217
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5218
				/** This action is documented in class.jetpack.php */
5219
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5220
			}
5221
5222
			return true;
5223
		}
5224
		return false;
5225
	}
5226
5227
/* Client Server API */
5228
5229
	/**
5230
	 * Loads the Jetpack XML-RPC client
5231
	 */
5232
	public static function load_xml_rpc_client() {
5233
		require_once ABSPATH . WPINC . '/class-IXR.php';
5234
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5235
	}
5236
5237
	/**
5238
	 * Resets the saved authentication state in between testing requests.
5239
	 */
5240
	public function reset_saved_auth_state() {
5241
		$this->xmlrpc_verification = null;
5242
		$this->rest_authentication_status = null;
5243
	}
5244
5245
	/**
5246
	 * Verifies the signature of the current request.
5247
	 *
5248
	 * @return false|array
5249
	 */
5250
	function verify_xml_rpc_signature() {
5251
		if ( is_null( $this->xmlrpc_verification ) ) {
5252
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5253
5254
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5255
				/**
5256
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5257
				 *
5258
				 * Error codes:
5259
				 * - malformed_token
5260
				 * - malformed_user_id
5261
				 * - unknown_token
5262
				 * - could_not_sign
5263
				 * - invalid_nonce
5264
				 * - signature_mismatch
5265
				 *
5266
				 * @since 7.5.0
5267
				 *
5268
				 * @param WP_Error $signature_verification_error The verification error
5269
				 */
5270
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5271
			}
5272
		}
5273
5274
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5275
	}
5276
5277
	/**
5278
	 * Verifies the signature of the current request.
5279
	 *
5280
	 * This function has side effects and should not be used. Instead,
5281
	 * use the memoized version `->verify_xml_rpc_signature()`.
5282
	 *
5283
	 * @internal
5284
	 */
5285
	private function internal_verify_xml_rpc_signature() {
5286
		// It's not for us
5287
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5288
			return false;
5289
		}
5290
5291
		$signature_details = array(
5292
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5293
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5294
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5295
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5296
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5297
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5298
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5299
		);
5300
5301
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
5302
		if (
5303
			empty( $token_key )
5304
		||
5305
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5306
		) {
5307
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
5308
		}
5309
5310
		if ( '0' === $user_id ) {
5311
			$token_type = 'blog';
5312
			$user_id = 0;
5313
		} else {
5314
			$token_type = 'user';
5315
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5316
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
5317
			}
5318
			$user_id = (int) $user_id;
5319
5320
			$user = new WP_User( $user_id );
5321
			if ( ! $user || ! $user->exists() ) {
5322
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
5323
			}
5324
		}
5325
5326
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
5327
		if ( is_wp_error( $token ) ) {
5328
			$token->add_data( compact( 'signature_details' ) );
5329
			return $token;
5330
		} elseif ( ! $token ) {
5331
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
5332
		}
5333
5334
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5335
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5336
			$post_data   = $_POST;
5337
			$file_hashes = array();
5338
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5339
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5340
					continue;
5341
				}
5342
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5343
				$file_hashes[$post_data_key] = $post_data_value;
5344
			}
5345
5346
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5347
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5348
				$post_data[$post_data_key] = $post_data_value;
5349
			}
5350
5351
			ksort( $post_data );
5352
5353
			$body = http_build_query( stripslashes_deep( $post_data ) );
5354
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5355
			$body = file_get_contents( 'php://input' );
5356
		} else {
5357
			$body = null;
5358
		}
5359
5360
		$signature = $jetpack_signature->sign_current_request(
5361
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5362
		);
5363
5364
		$signature_details['url'] = $jetpack_signature->current_request_url;
5365
5366
		if ( ! $signature ) {
5367
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
5368
		} else if ( is_wp_error( $signature ) ) {
5369
			return $signature;
5370
		}
5371
5372
		$timestamp = (int) $_GET['timestamp'];
5373
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5374
5375
		// Use up the nonce regardless of whether the signature matches.
5376
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5377
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
5378
		}
5379
5380
		// Be careful about what you do with this debugging data.
5381
		// If a malicious requester has access to the expected signature,
5382
		// bad things might be possible.
5383
		$signature_details['expected'] = $signature;
5384
5385
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5386
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
5387
		}
5388
5389
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5390
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5391
			if ( ! empty( $_GET['onboarding'] ) ) {
5392
				$jpo = $_GET;
5393
			} else {
5394
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5395
			}
5396
5397
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5398
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5399
5400
			if (
5401
				isset( $jpo_user ) && isset( $jpo_token ) &&
5402
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5403
				isset( $_GET['rest_route'] ) &&
5404
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5405
			) {
5406
				$jpUser = get_user_by( 'email', $jpo_user );
5407
				if ( is_a( $jpUser, 'WP_User' ) ) {
5408
					wp_set_current_user( $jpUser->ID );
5409
					$user_can = is_multisite()
5410
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5411
						: current_user_can( 'manage_options' );
5412
					if ( $user_can ) {
5413
						$token_type = 'user';
5414
						$token->external_user_id = $jpUser->ID;
5415
					}
5416
				}
5417
			}
5418
		}
5419
5420
		return array(
5421
			'type'      => $token_type,
5422
			'token_key' => $token_key,
5423
			'user_id'   => $token->external_user_id,
5424
		);
5425
	}
5426
5427
	/**
5428
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5429
	 */
5430
	function authenticate_jetpack( $user, $username, $password ) {
5431
		if ( is_a( $user, 'WP_User' ) ) {
5432
			return $user;
5433
		}
5434
5435
		$token_details = $this->verify_xml_rpc_signature();
5436
5437
		if ( ! $token_details ) {
5438
			return $user;
5439
		}
5440
5441
		if ( 'user' !== $token_details['type'] ) {
5442
			return $user;
5443
		}
5444
5445
		if ( ! $token_details['user_id'] ) {
5446
			return $user;
5447
		}
5448
5449
		nocache_headers();
5450
5451
		return new WP_User( $token_details['user_id'] );
5452
	}
5453
5454
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5455
	// Uses the existing XMLRPC request signing implementation.
5456
	function wp_rest_authenticate( $user ) {
5457
		if ( ! empty( $user ) ) {
5458
			// Another authentication method is in effect.
5459
			return $user;
5460
		}
5461
5462
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5463
			// Nothing to do for this authentication method.
5464
			return null;
5465
		}
5466
5467
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5468
			// Nothing to do for this authentication method.
5469
			return null;
5470
		}
5471
5472
		// Ensure that we always have the request body available.  At this
5473
		// point, the WP REST API code to determine the request body has not
5474
		// run yet.  That code may try to read from 'php://input' later, but
5475
		// this can only be done once per request in PHP versions prior to 5.6.
5476
		// So we will go ahead and perform this read now if needed, and save
5477
		// the request body where both the Jetpack signature verification code
5478
		// and the WP REST API code can see it.
5479
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5480
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5481
		}
5482
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5483
5484
		// Only support specific request parameters that have been tested and
5485
		// are known to work with signature verification.  A different method
5486
		// can be passed to the WP REST API via the '?_method=' parameter if
5487
		// needed.
5488
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5489
			$this->rest_authentication_status = new WP_Error(
5490
				'rest_invalid_request',
5491
				__( 'This request method is not supported.', 'jetpack' ),
5492
				array( 'status' => 400 )
5493
			);
5494
			return null;
5495
		}
5496
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5497
			$this->rest_authentication_status = new WP_Error(
5498
				'rest_invalid_request',
5499
				__( 'This request method does not support body parameters.', 'jetpack' ),
5500
				array( 'status' => 400 )
5501
			);
5502
			return null;
5503
		}
5504
5505
		$verified = $this->verify_xml_rpc_signature();
5506
5507
		if (
5508
			$verified &&
5509
			isset( $verified['type'] ) &&
5510
			'user' === $verified['type'] &&
5511
			! empty( $verified['user_id'] )
5512
		) {
5513
			// Authentication successful.
5514
			$this->rest_authentication_status = true;
5515
			return $verified['user_id'];
5516
		}
5517
5518
		// Something else went wrong.  Probably a signature error.
5519
		$this->rest_authentication_status = new WP_Error(
5520
			'rest_invalid_signature',
5521
			__( 'The request is not signed correctly.', 'jetpack' ),
5522
			array( 'status' => 400 )
5523
		);
5524
		return null;
5525
	}
5526
5527
	/**
5528
	 * Report authentication status to the WP REST API.
5529
	 *
5530
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5531
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5532
	 */
5533
	public function wp_rest_authentication_errors( $value ) {
5534
		if ( $value !== null ) {
5535
			return $value;
5536
		}
5537
		return $this->rest_authentication_status;
5538
	}
5539
5540
	function add_nonce( $timestamp, $nonce ) {
5541
		global $wpdb;
5542
		static $nonces_used_this_request = array();
5543
5544
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5545
			return $nonces_used_this_request["$timestamp:$nonce"];
5546
		}
5547
5548
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5549
		$timestamp = (int) $timestamp;
5550
		$nonce     = esc_sql( $nonce );
5551
5552
		// Raw query so we can avoid races: add_option will also update
5553
		$show_errors = $wpdb->show_errors( false );
5554
5555
		$old_nonce = $wpdb->get_row(
5556
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5557
		);
5558
5559
		if ( is_null( $old_nonce ) ) {
5560
			$return = $wpdb->query(
5561
				$wpdb->prepare(
5562
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5563
					"jetpack_nonce_{$timestamp}_{$nonce}",
5564
					time(),
5565
					'no'
5566
				)
5567
			);
5568
		} else {
5569
			$return = false;
5570
		}
5571
5572
		$wpdb->show_errors( $show_errors );
5573
5574
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5575
5576
		return $return;
5577
	}
5578
5579
	/**
5580
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5581
	 * Capture it here so we can verify the signature later.
5582
	 */
5583
	function xmlrpc_methods( $methods ) {
5584
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5585
		return $methods;
5586
	}
5587
5588
	function public_xmlrpc_methods( $methods ) {
5589
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5590
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5591
		}
5592
		return $methods;
5593
	}
5594
5595
	function jetpack_getOptions( $args ) {
5596
		global $wp_xmlrpc_server;
5597
5598
		$wp_xmlrpc_server->escape( $args );
5599
5600
		$username	= $args[1];
5601
		$password	= $args[2];
5602
5603
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5604
			return $wp_xmlrpc_server->error;
5605
		}
5606
5607
		$options = array();
5608
		$user_data = $this->get_connected_user_data();
5609
		if ( is_array( $user_data ) ) {
5610
			$options['jetpack_user_id'] = array(
5611
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5612
				'readonly'      => true,
5613
				'value'         => $user_data['ID'],
5614
			);
5615
			$options['jetpack_user_login'] = array(
5616
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5617
				'readonly'      => true,
5618
				'value'         => $user_data['login'],
5619
			);
5620
			$options['jetpack_user_email'] = array(
5621
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5622
				'readonly'      => true,
5623
				'value'         => $user_data['email'],
5624
			);
5625
			$options['jetpack_user_site_count'] = array(
5626
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5627
				'readonly'      => true,
5628
				'value'         => $user_data['site_count'],
5629
			);
5630
		}
5631
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5632
		$args = stripslashes_deep( $args );
5633
		return $wp_xmlrpc_server->wp_getOptions( $args );
5634
	}
5635
5636
	function xmlrpc_options( $options ) {
5637
		$jetpack_client_id = false;
5638
		if ( self::is_active() ) {
5639
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5640
		}
5641
		$options['jetpack_version'] = array(
5642
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5643
				'readonly'      => true,
5644
				'value'         => JETPACK__VERSION,
5645
		);
5646
5647
		$options['jetpack_client_id'] = array(
5648
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5649
				'readonly'      => true,
5650
				'value'         => $jetpack_client_id,
5651
		);
5652
		return $options;
5653
	}
5654
5655
	public static function clean_nonces( $all = false ) {
5656
		global $wpdb;
5657
5658
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5659
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5660
5661
		if ( true !== $all ) {
5662
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5663
			$sql_args[] = time() - 3600;
5664
		}
5665
5666
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5667
5668
		$sql = $wpdb->prepare( $sql, $sql_args );
5669
5670
		for ( $i = 0; $i < 1000; $i++ ) {
5671
			if ( ! $wpdb->query( $sql ) ) {
5672
				break;
5673
			}
5674
		}
5675
	}
5676
5677
	/**
5678
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5679
	 * SET: state( $key, $value );
5680
	 * GET: $value = state( $key );
5681
	 *
5682
	 * @param string $key
5683
	 * @param string $value
5684
	 * @param bool $restate private
5685
	 */
5686
	public static function state( $key = null, $value = null, $restate = false ) {
5687
		static $state = array();
5688
		static $path, $domain;
5689
		if ( ! isset( $path ) ) {
5690
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5691
			$admin_url = Jetpack::admin_url();
5692
			$bits      = wp_parse_url( $admin_url );
5693
5694
			if ( is_array( $bits ) ) {
5695
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5696
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5697
			} else {
5698
				$path = $domain = null;
5699
			}
5700
		}
5701
5702
		// Extract state from cookies and delete cookies
5703
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5704
			$yum = $_COOKIE[ 'jetpackState' ];
5705
			unset( $_COOKIE[ 'jetpackState' ] );
5706
			foreach ( $yum as $k => $v ) {
5707
				if ( strlen( $v ) )
5708
					$state[ $k ] = $v;
5709
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5710
			}
5711
		}
5712
5713
		if ( $restate ) {
5714
			foreach ( $state as $k => $v ) {
5715
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5716
			}
5717
			return;
5718
		}
5719
5720
		// Get a state variable
5721
		if ( isset( $key ) && ! isset( $value ) ) {
5722
			if ( array_key_exists( $key, $state ) )
5723
				return $state[ $key ];
5724
			return null;
5725
		}
5726
5727
		// Set a state variable
5728
		if ( isset ( $key ) && isset( $value ) ) {
5729
			if( is_array( $value ) && isset( $value[0] ) ) {
5730
				$value = $value[0];
5731
			}
5732
			$state[ $key ] = $value;
5733
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5734
		}
5735
	}
5736
5737
	public static function restate() {
5738
		Jetpack::state( null, null, true );
5739
	}
5740
5741
	public static function check_privacy( $file ) {
5742
		static $is_site_publicly_accessible = null;
5743
5744
		if ( is_null( $is_site_publicly_accessible ) ) {
5745
			$is_site_publicly_accessible = false;
5746
5747
			Jetpack::load_xml_rpc_client();
5748
			$rpc = new Jetpack_IXR_Client();
5749
5750
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5751
			if ( $success ) {
5752
				$response = $rpc->getResponse();
5753
				if ( $response ) {
5754
					$is_site_publicly_accessible = true;
5755
				}
5756
			}
5757
5758
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5759
		}
5760
5761
		if ( $is_site_publicly_accessible ) {
5762
			return;
5763
		}
5764
5765
		$module_slug = self::get_module_slug( $file );
5766
5767
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5768
		if ( ! $privacy_checks ) {
5769
			$privacy_checks = $module_slug;
5770
		} else {
5771
			$privacy_checks .= ",$module_slug";
5772
		}
5773
5774
		Jetpack::state( 'privacy_checks', $privacy_checks );
5775
	}
5776
5777
	/**
5778
	 * Helper method for multicall XMLRPC.
5779
	 */
5780
	public static function xmlrpc_async_call() {
5781
		global $blog_id;
5782
		static $clients = array();
5783
5784
		$client_blog_id = is_multisite() ? $blog_id : 0;
5785
5786
		if ( ! isset( $clients[$client_blog_id] ) ) {
5787
			Jetpack::load_xml_rpc_client();
5788
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5789
			if ( function_exists( 'ignore_user_abort' ) ) {
5790
				ignore_user_abort( true );
5791
			}
5792
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5793
		}
5794
5795
		$args = func_get_args();
5796
5797
		if ( ! empty( $args[0] ) ) {
5798
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5799
		} elseif ( is_multisite() ) {
5800
			foreach ( $clients as $client_blog_id => $client ) {
5801
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5802
					continue;
5803
				}
5804
5805
				$switch_success = switch_to_blog( $client_blog_id, true );
5806
				if ( ! $switch_success ) {
5807
					continue;
5808
				}
5809
5810
				flush();
5811
				$client->query();
5812
5813
				restore_current_blog();
5814
			}
5815
		} else {
5816
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5817
				flush();
5818
				$clients[0]->query();
5819
			}
5820
		}
5821
	}
5822
5823
	public static function staticize_subdomain( $url ) {
5824
5825
		// Extract hostname from URL
5826
		$host = parse_url( $url, PHP_URL_HOST );
5827
5828
		// Explode hostname on '.'
5829
		$exploded_host = explode( '.', $host );
5830
5831
		// Retrieve the name and TLD
5832
		if ( count( $exploded_host ) > 1 ) {
5833
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5834
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5835
			// Rebuild domain excluding subdomains
5836
			$domain = $name . '.' . $tld;
5837
		} else {
5838
			$domain = $host;
5839
		}
5840
		// Array of Automattic domains
5841
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5842
5843
		// Return $url if not an Automattic domain
5844
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5845
			return $url;
5846
		}
5847
5848
		if ( is_ssl() ) {
5849
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5850
		}
5851
5852
		srand( crc32( basename( $url ) ) );
5853
		$static_counter = rand( 0, 2 );
5854
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5855
5856
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5857
	}
5858
5859
/* JSON API Authorization */
5860
5861
	/**
5862
	 * Handles the login action for Authorizing the JSON API
5863
	 */
5864
	function login_form_json_api_authorization() {
5865
		$this->verify_json_api_authorization_request();
5866
5867
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5868
5869
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5870
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5871
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5872
	}
5873
5874
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5875
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5876
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5877
			return $url;
5878
		}
5879
5880
		$parsed_url = parse_url( $url );
5881
		$url = strtok( $url, '?' );
5882
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5883
		if ( ! empty( $parsed_url['query'] ) )
5884
			$url .= "&{$parsed_url['query']}";
5885
5886
		return $url;
5887
	}
5888
5889
	// Make sure the POSTed request is handled by the same action
5890
	function preserve_action_in_login_form_for_json_api_authorization() {
5891
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5892
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5893
	}
5894
5895
	// If someone logs in to approve API access, store the Access Code in usermeta
5896
	function store_json_api_authorization_token( $user_login, $user ) {
5897
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5898
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5899
		$token = wp_generate_password( 32, false );
5900
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5901
	}
5902
5903
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5904
	function allow_wpcom_public_api_domain( $domains ) {
5905
		$domains[] = 'public-api.wordpress.com';
5906
		return $domains;
5907
	}
5908
5909
	static function is_redirect_encoded( $redirect_url ) {
5910
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5911
	}
5912
5913
	// Add all wordpress.com environments to the safe redirect whitelist
5914
	function allow_wpcom_environments( $domains ) {
5915
		$domains[] = 'wordpress.com';
5916
		$domains[] = 'wpcalypso.wordpress.com';
5917
		$domains[] = 'horizon.wordpress.com';
5918
		$domains[] = 'calypso.localhost';
5919
		return $domains;
5920
	}
5921
5922
	// Add the Access Code details to the public-api.wordpress.com redirect
5923
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5924
		return add_query_arg(
5925
			urlencode_deep(
5926
				array(
5927
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5928
					'jetpack-user-id' => (int) $user->ID,
5929
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5930
				)
5931
			),
5932
			$redirect_to
5933
		);
5934
	}
5935
5936
5937
	/**
5938
	 * Verifies the request by checking the signature
5939
	 *
5940
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5941
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5942
	 *
5943
	 * @param null|array $environment
5944
	 */
5945
	function verify_json_api_authorization_request( $environment = null ) {
5946
		$environment = is_null( $environment )
5947
			? $_REQUEST
5948
			: $environment;
5949
5950
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5951
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5952
		if ( ! $token || empty( $token->secret ) ) {
5953
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5954
		}
5955
5956
		$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' );
5957
5958
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5959
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5960
			/**
5961
			 * Jetpack authorisation request Error.
5962
			 *
5963
			 * @since 7.5.0
5964
			 *
5965
			 */
5966
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5967
			$die_error = sprintf(
5968
				/* translators: %s is a URL */
5969
				__( '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' ),
5970
				'https://jetpack.com/support/double-encoding/'
5971
			);
5972
		}
5973
5974
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5975
5976
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5977
			$signature = $jetpack_signature->sign_request(
5978
				$environment['token'],
5979
				$environment['timestamp'],
5980
				$environment['nonce'],
5981
				'',
5982
				'GET',
5983
				$environment['jetpack_json_api_original_query'],
5984
				null,
5985
				true
5986
			);
5987
		} else {
5988
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5989
		}
5990
5991
		if ( ! $signature ) {
5992
			wp_die( $die_error );
5993
		} else if ( is_wp_error( $signature ) ) {
5994
			wp_die( $die_error );
5995
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5996
			if ( is_ssl() ) {
5997
				// 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
5998
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5999
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6000
					wp_die( $die_error );
6001
				}
6002
			} else {
6003
				wp_die( $die_error );
6004
			}
6005
		}
6006
6007
		$timestamp = (int) $environment['timestamp'];
6008
		$nonce     = stripslashes( (string) $environment['nonce'] );
6009
6010
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
6011
			// De-nonce the nonce, at least for 5 minutes.
6012
			// 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)
6013
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6014
			if ( $old_nonce_time < time() - 300 ) {
6015
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
6016
			}
6017
		}
6018
6019
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6020
		$data_filters = array(
6021
			'state'        => 'opaque',
6022
			'client_id'    => 'int',
6023
			'client_title' => 'string',
6024
			'client_image' => 'url',
6025
		);
6026
6027
		foreach ( $data_filters as $key => $sanitation ) {
6028
			if ( ! isset( $data->$key ) ) {
6029
				wp_die( $die_error );
6030
			}
6031
6032
			switch ( $sanitation ) {
6033
			case 'int' :
6034
				$this->json_api_authorization_request[$key] = (int) $data->$key;
6035
				break;
6036
			case 'opaque' :
6037
				$this->json_api_authorization_request[$key] = (string) $data->$key;
6038
				break;
6039
			case 'string' :
6040
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6041
				break;
6042
			case 'url' :
6043
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6044
				break;
6045
			}
6046
		}
6047
6048
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6049
			wp_die( $die_error );
6050
		}
6051
	}
6052
6053
	function login_message_json_api_authorization( $message ) {
6054
		return '<p class="message">' . sprintf(
6055
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
6056
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6057
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6058
	}
6059
6060
	/**
6061
	 * Get $content_width, but with a <s>twist</s> filter.
6062
	 */
6063
	public static function get_content_width() {
6064
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6065
			? $GLOBALS['content_width']
6066
			: false;
6067
		/**
6068
		 * Filter the Content Width value.
6069
		 *
6070
		 * @since 2.2.3
6071
		 *
6072
		 * @param string $content_width Content Width value.
6073
		 */
6074
		return apply_filters( 'jetpack_content_width', $content_width );
6075
	}
6076
6077
	/**
6078
	 * Pings the WordPress.com Mirror Site for the specified options.
6079
	 *
6080
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6081
	 *
6082
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6083
	 */
6084
	public function get_cloud_site_options( $option_names ) {
6085
		$option_names = array_filter( (array) $option_names, 'is_string' );
6086
6087
		Jetpack::load_xml_rpc_client();
6088
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6089
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6090
		if ( $xml->isError() ) {
6091
			return array(
6092
				'error_code' => $xml->getErrorCode(),
6093
				'error_msg'  => $xml->getErrorMessage(),
6094
			);
6095
		}
6096
		$cloud_site_options = $xml->getResponse();
6097
6098
		return $cloud_site_options;
6099
	}
6100
6101
	/**
6102
	 * Checks if the site is currently in an identity crisis.
6103
	 *
6104
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6105
	 */
6106
	public static function check_identity_crisis() {
6107
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6108
			return false;
6109
		}
6110
6111
		return Jetpack_Options::get_option( 'sync_error_idc' );
6112
	}
6113
6114
	/**
6115
	 * Checks whether the home and siteurl specifically are whitelisted
6116
	 * Written so that we don't have re-check $key and $value params every time
6117
	 * we want to check if this site is whitelisted, for example in footer.php
6118
	 *
6119
	 * @since  3.8.0
6120
	 * @return bool True = already whitelisted False = not whitelisted
6121
	 */
6122
	public static function is_staging_site() {
6123
		$is_staging = false;
6124
6125
		$known_staging = array(
6126
			'urls' => array(
6127
				'#\.staging\.wpengine\.com$#i', // WP Engine
6128
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6129
				'#\.stage\.site$#i'             // DreamPress
6130
			),
6131
			'constants' => array(
6132
				'IS_WPE_SNAPSHOT',      // WP Engine
6133
				'KINSTA_DEV_ENV',       // Kinsta.com
6134
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6135
				'JETPACK_STAGING_MODE', // Generic
6136
			)
6137
		);
6138
		/**
6139
		 * Filters the flags of known staging sites.
6140
		 *
6141
		 * @since 3.9.0
6142
		 *
6143
		 * @param array $known_staging {
6144
		 *     An array of arrays that each are used to check if the current site is staging.
6145
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6146
		 *     @type array $constants PHP constants of known staging/developement environments.
6147
		 *  }
6148
		 */
6149
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6150
6151
		if ( isset( $known_staging['urls'] ) ) {
6152
			foreach ( $known_staging['urls'] as $url ){
6153
				if ( preg_match( $url, site_url() ) ) {
6154
					$is_staging = true;
6155
					break;
6156
				}
6157
			}
6158
		}
6159
6160
		if ( isset( $known_staging['constants'] ) ) {
6161
			foreach ( $known_staging['constants'] as $constant ) {
6162
				if ( defined( $constant ) && constant( $constant ) ) {
6163
					$is_staging = true;
6164
				}
6165
			}
6166
		}
6167
6168
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6169
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6170
			$is_staging = true;
6171
		}
6172
6173
		/**
6174
		 * Filters is_staging_site check.
6175
		 *
6176
		 * @since 3.9.0
6177
		 *
6178
		 * @param bool $is_staging If the current site is a staging site.
6179
		 */
6180
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6181
	}
6182
6183
	/**
6184
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6185
	 *
6186
	 * @since 4.4.0
6187
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6188
	 *
6189
	 * @return bool
6190
	 */
6191
	public static function validate_sync_error_idc_option() {
6192
		$is_valid = false;
6193
6194
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6195
		if ( false === $idc_allowed ) {
6196
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6197
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6198
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6199
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6200
				$transient_duration = HOUR_IN_SECONDS;
6201
			} else {
6202
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6203
				$idc_allowed = '1';
6204
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6205
			}
6206
6207
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6208
		}
6209
6210
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6211
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6212
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6213
			$local_options = self::get_sync_error_idc_option();
6214
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6215
				$is_valid = true;
6216
			}
6217
		}
6218
6219
		/**
6220
		 * Filters whether the sync_error_idc option is valid.
6221
		 *
6222
		 * @since 4.4.0
6223
		 *
6224
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6225
		 */
6226
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6227
6228
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6229
			// Since the option exists, and did not validate, delete it
6230
			Jetpack_Options::delete_option( 'sync_error_idc' );
6231
		}
6232
6233
		return $is_valid;
6234
	}
6235
6236
	/**
6237
	 * Normalizes a url by doing three things:
6238
	 *  - Strips protocol
6239
	 *  - Strips www
6240
	 *  - Adds a trailing slash
6241
	 *
6242
	 * @since 4.4.0
6243
	 * @param string $url
6244
	 * @return WP_Error|string
6245
	 */
6246
	public static function normalize_url_protocol_agnostic( $url ) {
6247
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6248
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6249
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6250
		}
6251
6252
		// Strip www and protocols
6253
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6254
		return $url;
6255
	}
6256
6257
	/**
6258
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6259
	 *
6260
	 * @since 4.4.0
6261
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6262
	 *
6263
	 * @param array $response
6264
	 * @return array Array of the local urls, wpcom urls, and error code
6265
	 */
6266
	public static function get_sync_error_idc_option( $response = array() ) {
6267
		// Since the local options will hit the database directly, store the values
6268
		// in a transient to allow for autoloading and caching on subsequent views.
6269
		$local_options = get_transient( 'jetpack_idc_local' );
6270
		if ( false === $local_options ) {
6271
			$local_options = array(
6272
				'home'    => Functions::home_url(),
6273
				'siteurl' => Functions::site_url(),
6274
			);
6275
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6276
		}
6277
6278
		$options = array_merge( $local_options, $response );
6279
6280
		$returned_values = array();
6281
		foreach( $options as $key => $option ) {
6282
			if ( 'error_code' === $key ) {
6283
				$returned_values[ $key ] = $option;
6284
				continue;
6285
			}
6286
6287
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6288
				continue;
6289
			}
6290
6291
			$returned_values[ $key ] = $normalized_url;
6292
		}
6293
6294
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6295
6296
		return $returned_values;
6297
	}
6298
6299
	/**
6300
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6301
	 * If set to true, the site will be put into staging mode.
6302
	 *
6303
	 * @since 4.3.2
6304
	 * @return bool
6305
	 */
6306
	public static function sync_idc_optin() {
6307
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6308
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6309
		} else {
6310
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6311
		}
6312
6313
		/**
6314
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6315
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6316
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6317
		 *
6318
		 * @since 4.3.2
6319
		 *
6320
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6321
		 */
6322
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6323
	}
6324
6325
	/**
6326
	 * Maybe Use a .min.css stylesheet, maybe not.
6327
	 *
6328
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6329
	 */
6330
	public static function maybe_min_asset( $url, $path, $plugin ) {
6331
		// Short out on things trying to find actual paths.
6332
		if ( ! $path || empty( $plugin ) ) {
6333
			return $url;
6334
		}
6335
6336
		$path = ltrim( $path, '/' );
6337
6338
		// Strip out the abspath.
6339
		$base = dirname( plugin_basename( $plugin ) );
6340
6341
		// Short out on non-Jetpack assets.
6342
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6343
			return $url;
6344
		}
6345
6346
		// File name parsing.
6347
		$file              = "{$base}/{$path}";
6348
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6349
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6350
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6351
		$extension         = array_shift( $file_name_parts_r );
6352
6353
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6354
			// Already pointing at the minified version.
6355
			if ( 'min' === $file_name_parts_r[0] ) {
6356
				return $url;
6357
			}
6358
6359
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6360
			if ( file_exists( $min_full_path ) ) {
6361
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6362
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6363
				if ( 'css' === $extension ) {
6364
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6365
					self::$min_assets[ $key ] = $path;
6366
				}
6367
			}
6368
		}
6369
6370
		return $url;
6371
	}
6372
6373
	/**
6374
	 * If the asset is minified, let's flag .min as the suffix.
6375
	 *
6376
	 * Attached to `style_loader_src` filter.
6377
	 *
6378
	 * @param string $tag The tag that would link to the external asset.
6379
	 * @param string $handle The registered handle of the script in question.
6380
	 * @param string $href The url of the asset in question.
6381
	 */
6382
	public static function set_suffix_on_min( $src, $handle ) {
6383
		if ( false === strpos( $src, '.min.css' ) ) {
6384
			return $src;
6385
		}
6386
6387
		if ( ! empty( self::$min_assets ) ) {
6388
			foreach ( self::$min_assets as $file => $path ) {
6389
				if ( false !== strpos( $src, $file ) ) {
6390
					wp_style_add_data( $handle, 'suffix', '.min' );
6391
					return $src;
6392
				}
6393
			}
6394
		}
6395
6396
		return $src;
6397
	}
6398
6399
	/**
6400
	 * Maybe inlines a stylesheet.
6401
	 *
6402
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6403
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6404
	 *
6405
	 * Attached to `style_loader_tag` filter.
6406
	 *
6407
	 * @param string $tag The tag that would link to the external asset.
6408
	 * @param string $handle The registered handle of the script in question.
6409
	 *
6410
	 * @return string
6411
	 */
6412
	public static function maybe_inline_style( $tag, $handle ) {
6413
		global $wp_styles;
6414
		$item = $wp_styles->registered[ $handle ];
6415
6416
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6417
			return $tag;
6418
		}
6419
6420
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6421
			$href = $matches[1];
6422
			// Strip off query string
6423
			if ( $pos = strpos( $href, '?' ) ) {
6424
				$href = substr( $href, 0, $pos );
6425
			}
6426
			// Strip off fragment
6427
			if ( $pos = strpos( $href, '#' ) ) {
6428
				$href = substr( $href, 0, $pos );
6429
			}
6430
		} else {
6431
			return $tag;
6432
		}
6433
6434
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6435
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6436
			return $tag;
6437
		}
6438
6439
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6440
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6441
			// And this isn't the pass that actually deals with the RTL version...
6442
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6443
				// Short out, as the RTL version will deal with it in a moment.
6444
				return $tag;
6445
			}
6446
		}
6447
6448
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6449
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6450
		if ( $css ) {
6451
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6452
			if ( empty( $item->extra['after'] ) ) {
6453
				wp_add_inline_style( $handle, $css );
6454
			} else {
6455
				array_unshift( $item->extra['after'], $css );
6456
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6457
			}
6458
		}
6459
6460
		return $tag;
6461
	}
6462
6463
	/**
6464
	 * Loads a view file from the views
6465
	 *
6466
	 * Data passed in with the $data parameter will be available in the
6467
	 * template file as $data['value']
6468
	 *
6469
	 * @param string $template - Template file to load
6470
	 * @param array $data - Any data to pass along to the template
6471
	 * @return boolean - If template file was found
6472
	 **/
6473
	public function load_view( $template, $data = array() ) {
6474
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6475
6476
		if( file_exists( $views_dir . $template ) ) {
6477
			require_once( $views_dir . $template );
6478
			return true;
6479
		}
6480
6481
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6482
		return false;
6483
	}
6484
6485
	/**
6486
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6487
	 */
6488
	public function deprecated_hooks() {
6489
		global $wp_filter;
6490
6491
		/*
6492
		 * Format:
6493
		 * deprecated_filter_name => replacement_name
6494
		 *
6495
		 * If there is no replacement, use null for replacement_name
6496
		 */
6497
		$deprecated_list = array(
6498
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6499
			'wpl_sharing_2014_1'                                     => null,
6500
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6501
			'jetpack_identity_crisis_options_to_check'               => null,
6502
			'update_option_jetpack_single_user_site'                 => null,
6503
			'audio_player_default_colors'                            => null,
6504
			'add_option_jetpack_featured_images_enabled'             => null,
6505
			'add_option_jetpack_update_details'                      => null,
6506
			'add_option_jetpack_updates'                             => null,
6507
			'add_option_jetpack_network_name'                        => null,
6508
			'add_option_jetpack_network_allow_new_registrations'     => null,
6509
			'add_option_jetpack_network_add_new_users'               => null,
6510
			'add_option_jetpack_network_site_upload_space'           => null,
6511
			'add_option_jetpack_network_upload_file_types'           => null,
6512
			'add_option_jetpack_network_enable_administration_menus' => null,
6513
			'add_option_jetpack_is_multi_site'                       => null,
6514
			'add_option_jetpack_is_main_network'                     => null,
6515
			'add_option_jetpack_main_network_site'                   => null,
6516
			'jetpack_sync_all_registered_options'                    => null,
6517
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6518
			'jetpack_is_post_mailable'                               => null,
6519
			'jetpack_seo_site_host'                                  => null,
6520
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6521
			'jetpack_holiday_snow_option_name'                       => null,
6522
			'jetpack_holiday_chance_of_snow'                         => null,
6523
			'jetpack_holiday_snow_js_url'                            => null,
6524
			'jetpack_is_holiday_snow_season'                         => null,
6525
			'jetpack_holiday_snow_option_updated'                    => null,
6526
			'jetpack_holiday_snowing'                                => null,
6527
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6528
			'jetpack_cache_plans'                                    => null,
6529
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6530
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6531
			'jetpack_enable_site_verification'                       => null,
6532
			'can_display_jetpack_manage_notice'                      => null,
6533
			// Removed in Jetpack 7.3.0
6534
			'atd_load_scripts'                                       => null,
6535
			'atd_http_post_timeout'                                  => null,
6536
			'atd_http_post_error'                                    => null,
6537
			'atd_service_domain'                                     => null,
6538
		);
6539
6540
		// This is a silly loop depth. Better way?
6541
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6542
			if ( has_action( $hook ) ) {
6543
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6544
					foreach( $values AS $hooked ) {
6545
						if ( is_callable( $hooked['function'] ) ) {
6546
							$function_name = 'an anonymous function';
6547
						} else {
6548
							$function_name = $hooked['function'];
6549
						}
6550
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6551
					}
6552
				}
6553
			}
6554
		}
6555
	}
6556
6557
	/**
6558
	 * Converts any url in a stylesheet, to the correct absolute url.
6559
	 *
6560
	 * Considerations:
6561
	 *  - Normal, relative URLs     `feh.png`
6562
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6563
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6564
	 *  - Absolute URLs             `http://domain.com/feh.png`
6565
	 *  - Domain root relative URLs `/feh.png`
6566
	 *
6567
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6568
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6569
	 *
6570
	 * @return mixed|string
6571
	 */
6572
	public static function absolutize_css_urls( $css, $css_file_url ) {
6573
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6574
		$css_dir = dirname( $css_file_url );
6575
		$p       = parse_url( $css_dir );
6576
		$domain  = sprintf(
6577
					'%1$s//%2$s%3$s%4$s',
6578
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6579
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6580
					$p['host'],
6581
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6582
				);
6583
6584
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6585
			$find = $replace = array();
6586
			foreach ( $matches as $match ) {
6587
				$url = trim( $match['path'], "'\" \t" );
6588
6589
				// If this is a data url, we don't want to mess with it.
6590
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6591
					continue;
6592
				}
6593
6594
				// If this is an absolute or protocol-agnostic url,
6595
				// we don't want to mess with it.
6596
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6597
					continue;
6598
				}
6599
6600
				switch ( substr( $url, 0, 1 ) ) {
6601
					case '/':
6602
						$absolute = $domain . $url;
6603
						break;
6604
					default:
6605
						$absolute = $css_dir . '/' . $url;
6606
				}
6607
6608
				$find[]    = $match[0];
6609
				$replace[] = sprintf( 'url("%s")', $absolute );
6610
			}
6611
			$css = str_replace( $find, $replace, $css );
6612
		}
6613
6614
		return $css;
6615
	}
6616
6617
	/**
6618
	 * This methods removes all of the registered css files on the front end
6619
	 * from Jetpack in favor of using a single file. In effect "imploding"
6620
	 * all the files into one file.
6621
	 *
6622
	 * Pros:
6623
	 * - Uses only ONE css asset connection instead of 15
6624
	 * - Saves a minimum of 56k
6625
	 * - Reduces server load
6626
	 * - Reduces time to first painted byte
6627
	 *
6628
	 * Cons:
6629
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6630
	 *		should not cause any issues with themes.
6631
	 * - Plugins/themes dequeuing styles no longer do anything. See
6632
	 *		jetpack_implode_frontend_css filter for a workaround
6633
	 *
6634
	 * For some situations developers may wish to disable css imploding and
6635
	 * instead operate in legacy mode where each file loads seperately and
6636
	 * can be edited individually or dequeued. This can be accomplished with
6637
	 * the following line:
6638
	 *
6639
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6640
	 *
6641
	 * @since 3.2
6642
	 **/
6643
	public function implode_frontend_css( $travis_test = false ) {
6644
		$do_implode = true;
6645
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6646
			$do_implode = false;
6647
		}
6648
6649
		// Do not implode CSS when the page loads via the AMP plugin.
6650
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6651
			$do_implode = false;
6652
		}
6653
6654
		/**
6655
		 * Allow CSS to be concatenated into a single jetpack.css file.
6656
		 *
6657
		 * @since 3.2.0
6658
		 *
6659
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6660
		 */
6661
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6662
6663
		// Do not use the imploded file when default behavior was altered through the filter
6664
		if ( ! $do_implode ) {
6665
			return;
6666
		}
6667
6668
		// We do not want to use the imploded file in dev mode, or if not connected
6669
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6670
			if ( ! $travis_test ) {
6671
				return;
6672
			}
6673
		}
6674
6675
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6676
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6677
			return;
6678
		}
6679
6680
		/*
6681
		 * Now we assume Jetpack is connected and able to serve the single
6682
		 * file.
6683
		 *
6684
		 * In the future there will be a check here to serve the file locally
6685
		 * or potentially from the Jetpack CDN
6686
		 *
6687
		 * For now:
6688
		 * - Enqueue a single imploded css file
6689
		 * - Zero out the style_loader_tag for the bundled ones
6690
		 * - Be happy, drink scotch
6691
		 */
6692
6693
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6694
6695
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6696
6697
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6698
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6699
	}
6700
6701
	function concat_remove_style_loader_tag( $tag, $handle ) {
6702
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6703
			$tag = '';
6704
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6705
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6706
			}
6707
		}
6708
6709
		return $tag;
6710
	}
6711
6712
	/**
6713
	 * Add an async attribute to scripts that can be loaded asynchronously.
6714
	 * https://www.w3schools.com/tags/att_script_async.asp
6715
	 *
6716
	 * @since 7.7.0
6717
	 *
6718
	 * @param string $tag    The <script> tag for the enqueued script.
6719
	 * @param string $handle The script's registered handle.
6720
	 * @param string $src    The script's source URL.
6721
	 */
6722
	public function script_add_async( $tag, $handle, $src ) {
6723
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6724
			return preg_replace( '/^<script /i', '<script async ', $tag );
6725
		}
6726
6727
		return $tag;
6728
	}
6729
6730
	/*
6731
	 * Check the heartbeat data
6732
	 *
6733
	 * Organizes the heartbeat data by severity.  For example, if the site
6734
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6735
	 *
6736
	 * Data will be added to "caution" array, if it either:
6737
	 *  - Out of date Jetpack version
6738
	 *  - Out of date WP version
6739
	 *  - Out of date PHP version
6740
	 *
6741
	 * $return array $filtered_data
6742
	 */
6743
	public static function jetpack_check_heartbeat_data() {
6744
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6745
6746
		$good    = array();
6747
		$caution = array();
6748
		$bad     = array();
6749
6750
		foreach ( $raw_data as $stat => $value ) {
6751
6752
			// Check jetpack version
6753
			if ( 'version' == $stat ) {
6754
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6755
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6756
					continue;
6757
				}
6758
			}
6759
6760
			// Check WP version
6761
			if ( 'wp-version' == $stat ) {
6762
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6763
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6764
					continue;
6765
				}
6766
			}
6767
6768
			// Check PHP version
6769
			if ( 'php-version' == $stat ) {
6770
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6771
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6772
					continue;
6773
				}
6774
			}
6775
6776
			// Check ID crisis
6777
			if ( 'identitycrisis' == $stat ) {
6778
				if ( 'yes' == $value ) {
6779
					$bad[ $stat ] = $value;
6780
					continue;
6781
				}
6782
			}
6783
6784
			// The rest are good :)
6785
			$good[ $stat ] = $value;
6786
		}
6787
6788
		$filtered_data = array(
6789
			'good'    => $good,
6790
			'caution' => $caution,
6791
			'bad'     => $bad
6792
		);
6793
6794
		return $filtered_data;
6795
	}
6796
6797
6798
	/*
6799
	 * This method is used to organize all options that can be reset
6800
	 * without disconnecting Jetpack.
6801
	 *
6802
	 * It is used in class.jetpack-cli.php to reset options
6803
	 *
6804
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6805
	 *
6806
	 * @return array of options to delete.
6807
	 */
6808
	public static function get_jetpack_options_for_reset() {
6809
		return Jetpack_Options::get_options_for_reset();
6810
	}
6811
6812
	/*
6813
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6814
	 * so we can bring them directly to their site in calypso.
6815
	 *
6816
	 * @param string | url
6817
	 * @return string | url without the guff
6818
	 */
6819
	public static function build_raw_urls( $url ) {
6820
		$strip_http = '/.*?:\/\//i';
6821
		$url = preg_replace( $strip_http, '', $url  );
6822
		$url = str_replace( '/', '::', $url );
6823
		return $url;
6824
	}
6825
6826
	/**
6827
	 * Stores and prints out domains to prefetch for page speed optimization.
6828
	 *
6829
	 * @param mixed $new_urls
6830
	 */
6831
	public static function dns_prefetch( $new_urls = null ) {
6832
		static $prefetch_urls = array();
6833
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6834
			echo "\r\n";
6835
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6836
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6837
			}
6838
		} elseif ( ! empty( $new_urls ) ) {
6839
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6840
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6841
			}
6842
			foreach ( (array) $new_urls as $this_new_url ) {
6843
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6844
			}
6845
			$prefetch_urls = array_unique( $prefetch_urls );
6846
		}
6847
	}
6848
6849
	public function wp_dashboard_setup() {
6850
		if ( self::is_active() ) {
6851
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6852
		}
6853
6854
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6855
			$jetpack_logo = new Jetpack_Logo();
6856
			$widget_title = sprintf(
6857
				wp_kses(
6858
					/* translators: Placeholder is a Jetpack logo. */
6859
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6860
					array( 'span' => array() )
6861
				),
6862
				$jetpack_logo->get_jp_emblem( true )
6863
			);
6864
6865
			wp_add_dashboard_widget(
6866
				'jetpack_summary_widget',
6867
				$widget_title,
6868
				array( __CLASS__, 'dashboard_widget' )
6869
			);
6870
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6871
6872
			// If we're inactive and not in development mode, sort our box to the top.
6873
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6874
				global $wp_meta_boxes;
6875
6876
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6877
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6878
6879
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6880
			}
6881
		}
6882
	}
6883
6884
	/**
6885
	 * @param mixed $result Value for the user's option
6886
	 * @return mixed
6887
	 */
6888
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6889
		if ( ! is_array( $sorted ) ) {
6890
			return $sorted;
6891
		}
6892
6893
		foreach ( $sorted as $box_context => $ids ) {
6894
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6895
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6896
				continue;
6897
			}
6898
6899
			$ids_array = explode( ',', $ids );
6900
			$key = array_search( 'dashboard_stats', $ids_array );
6901
6902
			if ( false !== $key ) {
6903
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6904
				$ids_array[ $key ] = 'jetpack_summary_widget';
6905
				$sorted[ $box_context ] = implode( ',', $ids_array );
6906
				// We've found it, stop searching, and just return.
6907
				break;
6908
			}
6909
		}
6910
6911
		return $sorted;
6912
	}
6913
6914
	public static function dashboard_widget() {
6915
		/**
6916
		 * Fires when the dashboard is loaded.
6917
		 *
6918
		 * @since 3.4.0
6919
		 */
6920
		do_action( 'jetpack_dashboard_widget' );
6921
	}
6922
6923
	public static function dashboard_widget_footer() {
6924
		?>
6925
		<footer>
6926
6927
		<div class="protect">
6928
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6929
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6930
				<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>
6931
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6932
				<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' ); ?>">
6933
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6934
				</a>
6935
			<?php else : ?>
6936
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6937
			<?php endif; ?>
6938
		</div>
6939
6940
		<div class="akismet">
6941
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6942
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6943
				<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>
6944
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6945
				<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">
6946
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6947
				</a>
6948
			<?php else : ?>
6949
				<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>
6950
			<?php endif; ?>
6951
		</div>
6952
6953
		</footer>
6954
		<?php
6955
	}
6956
6957
	/*
6958
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6959
	 */
6960
	function jetpack_icon_user_connected( $columns ) {
6961
		$columns['user_jetpack'] = '';
6962
		return $columns;
6963
	}
6964
6965
	/*
6966
	 * Show Jetpack icon if the user is linked.
6967
	 */
6968
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6969
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6970
			$jetpack_logo = new Jetpack_Logo();
6971
			$emblem_html = sprintf(
6972
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6973
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6974
				$jetpack_logo->get_jp_emblem()
6975
			);
6976
			return $emblem_html;
6977
		}
6978
6979
		return $val;
6980
	}
6981
6982
	/*
6983
	 * Style the Jetpack user column
6984
	 */
6985
	function jetpack_user_col_style() {
6986
		global $current_screen;
6987
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6988
			<style>
6989
				.fixed .column-user_jetpack {
6990
					width: 21px;
6991
				}
6992
				.jp-emblem-user-admin svg {
6993
					width: 20px;
6994
					height: 20px;
6995
				}
6996
				.jp-emblem-user-admin path {
6997
					fill: #00BE28;
6998
				}
6999
			</style>
7000
		<?php }
7001
	}
7002
7003
	/**
7004
	 * Checks if Akismet is active and working.
7005
	 *
7006
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7007
	 * that implied usage of methods present since more recent version.
7008
	 * See https://github.com/Automattic/jetpack/pull/9585
7009
	 *
7010
	 * @since  5.1.0
7011
	 *
7012
	 * @return bool True = Akismet available. False = Aksimet not available.
7013
	 */
7014
	public static function is_akismet_active() {
7015
		static $status = null;
7016
7017
		if ( ! is_null( $status ) ) {
7018
			return $status;
7019
		}
7020
7021
		// Check if a modern version of Akismet is active.
7022
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7023
			$status = false;
7024
			return $status;
7025
		}
7026
7027
		// Make sure there is a key known to Akismet at all before verifying key.
7028
		$akismet_key = Akismet::get_api_key();
7029
		if ( ! $akismet_key ) {
7030
			$status = false;
7031
			return $status;
7032
		}
7033
7034
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7035
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7036
7037
		// 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.
7038
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7039
		// We cache the result of the Akismet key verification for ten minutes.
7040
		if ( ! $akismet_key_state || $recheck ) {
7041
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7042
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7043
		}
7044
7045
		$status = 'valid' === $akismet_key_state;
7046
7047
		return $status;
7048
	}
7049
7050
	/**
7051
	 * @deprecated
7052
	 *
7053
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7054
	 */
7055
	public static function is_function_in_backtrace() {
7056
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7057
	}
7058
7059
	/**
7060
	 * Given a minified path, and a non-minified path, will return
7061
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7062
	 *
7063
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7064
	 * root Jetpack directory.
7065
	 *
7066
	 * @since 5.6.0
7067
	 *
7068
	 * @param string $min_path
7069
	 * @param string $non_min_path
7070
	 * @return string The URL to the file
7071
	 */
7072
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7073
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7074
	}
7075
7076
	/**
7077
	 * Checks for whether Jetpack Backup & Scan is enabled.
7078
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7079
	 * @return bool|int|mixed
7080
	 */
7081
	public static function is_rewind_enabled() {
7082
		if ( ! Jetpack::is_active() ) {
7083
			return false;
7084
		}
7085
7086
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7087
		if ( false === $rewind_enabled ) {
7088
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7089
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7090
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7091
				&& ! empty( $rewind_data['state'] )
7092
				&& 'active' === $rewind_data['state'] )
7093
				? 1
7094
				: 0;
7095
7096
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7097
		}
7098
		return $rewind_enabled;
7099
	}
7100
7101
	/**
7102
	 * Return Calypso environment value; used for developing Jetpack and pairing
7103
	 * it with different Calypso enrionments, such as localhost.
7104
	 *
7105
	 * @since 7.4.0
7106
	 *
7107
	 * @return string Calypso environment
7108
	 */
7109
	public static function get_calypso_env() {
7110
		if ( isset( $_GET['calypso_env'] ) ) {
7111
			return sanitize_key( $_GET['calypso_env'] );
7112
		}
7113
7114
		if ( getenv( 'CALYPSO_ENV' ) ) {
7115
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7116
		}
7117
7118
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7119
			return sanitize_key( CALYPSO_ENV );
7120
		}
7121
7122
		return '';
7123
	}
7124
7125
	/**
7126
	 * Checks whether or not TOS has been agreed upon.
7127
	 * Will return true if a user has clicked to register, or is already connected.
7128
	 */
7129
	public static function jetpack_tos_agreed() {
7130
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7131
	}
7132
7133
	/**
7134
	 * Handles activating default modules as well general cleanup for the new connection.
7135
	 *
7136
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7137
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7138
	 * @param boolean $send_state_messages          Whether to send state messages.
7139
	 * @return void
7140
	 */
7141
	public static function handle_post_authorization_actions(
7142
		$activate_sso = false,
7143
		$redirect_on_activation_error = false,
7144
		$send_state_messages = true
7145
	) {
7146
		$other_modules = $activate_sso
7147
			? array( 'sso' )
7148
			: array();
7149
7150
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7151
			Jetpack::delete_active_modules();
7152
7153
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7154
		} else {
7155
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7156
		}
7157
7158
		// Since this is a fresh connection, be sure to clear out IDC options
7159
		Jetpack_IDC::clear_all_idc_options();
7160
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7161
7162
		// Start nonce cleaner
7163
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7164
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7165
7166
		if ( $send_state_messages ) {
7167
			Jetpack::state( 'message', 'authorized' );
7168
		}
7169
	}
7170
7171
	/**
7172
	 * Returns a boolean for whether backups UI should be displayed or not.
7173
	 *
7174
	 * @return bool Should backups UI be displayed?
7175
	 */
7176
	public static function show_backups_ui() {
7177
		/**
7178
		 * Whether UI for backups should be displayed.
7179
		 *
7180
		 * @since 6.5.0
7181
		 *
7182
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7183
		 */
7184
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7185
	}
7186
7187
	/*
7188
	 * Deprecated manage functions
7189
	 */
7190
	function prepare_manage_jetpack_notice() {
7191
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7192
	}
7193
	function manage_activate_screen() {
7194
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7195
	}
7196
	function admin_jetpack_manage_notice() {
7197
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7198
	}
7199
	function opt_out_jetpack_manage_url() {
7200
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7201
	}
7202
	function opt_in_jetpack_manage_url() {
7203
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7204
	}
7205
	function opt_in_jetpack_manage_notice() {
7206
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7207
	}
7208
	function can_display_jetpack_manage_notice() {
7209
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7210
	}
7211
7212
	/**
7213
	 * Clean leftoveruser meta.
7214
	 *
7215
	 * Delete Jetpack-related user meta when it is no longer needed.
7216
	 *
7217
	 * @since 7.3.0
7218
	 *
7219
	 * @param int $user_id User ID being updated.
7220
	 */
7221
	public static function user_meta_cleanup( $user_id ) {
7222
		$meta_keys = array(
7223
			// AtD removed from Jetpack 7.3
7224
			'AtD_options',
7225
			'AtD_check_when',
7226
			'AtD_guess_lang',
7227
			'AtD_ignored_phrases',
7228
		);
7229
7230
		foreach ( $meta_keys as $meta_key ) {
7231
			if ( get_user_meta( $user_id, $meta_key ) ) {
7232
				delete_user_meta( $user_id, $meta_key );
7233
			}
7234
		}
7235
	}
7236
7237
	function is_active_and_not_development_mode( $maybe ) {
7238
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7239
			return false;
7240
		}
7241
		return true;
7242
	}
7243
7244
}
7245