Completed
Pull Request — master (#13217)
by Marin
27:42 queued 20:43
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

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