Completed
Push — master ( a9f7c3...bf825c )
by Marin
06:41
created

class.jetpack.php (3 issues)

Upgrade to new PHP Analysis Engine

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

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

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5414
			__( 'The request is not signed correctly.', 'jetpack' ),
5415
			array( 'status' => 400 )
5416
		);
5417
		return null;
5418
	}
5419
5420
	/**
5421
	 * Report authentication status to the WP REST API.
5422
	 *
5423
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5424
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5425
	 */
5426
	public function wp_rest_authentication_errors( $value ) {
5427
		if ( $value !== null ) {
5428
			return $value;
5429
		}
5430
		return $this->rest_authentication_status;
5431
	}
5432
5433
	/**
5434
	 * Add our nonce to this request.
5435
	 *
5436
	 * @deprecated since 7.7.0
5437
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5438
	 *
5439
	 * @param int    $timestamp Timestamp of the request.
5440
	 * @param string $nonce     Nonce string.
5441
	 */
5442
	public function add_nonce( $timestamp, $nonce ) {
5443
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5444
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5445
	}
5446
5447
	/**
5448
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5449
	 * Capture it here so we can verify the signature later.
5450
	 *
5451
	 * @deprecated since 7.7.0
5452
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5453
	 *
5454
	 * @param array $methods XMLRPC methods.
5455
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5456
	 */
5457
	public function xmlrpc_methods( $methods ) {
5458
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5459
		return $this->connection_manager->xmlrpc_methods( $methods );
5460
	}
5461
5462
	/**
5463
	 * Register additional public XMLRPC methods.
5464
	 *
5465
	 * @deprecated since 7.7.0
5466
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5467
	 *
5468
	 * @param array $methods Public XMLRPC methods.
5469
	 * @return array Public XMLRPC methods, with the getOptions one.
5470
	 */
5471
	public function public_xmlrpc_methods( $methods ) {
5472
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5473
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5474
	}
5475
5476
	/**
5477
	 * Handles a getOptions XMLRPC method call.
5478
	 *
5479
	 * @deprecated since 7.7.0
5480
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5481
	 *
5482
	 * @param array $args method call arguments.
5483
	 * @return array an amended XMLRPC server options array.
5484
	 */
5485
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5486
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5487
		return $this->connection_manager->jetpack_getOptions( $args );
5488
	}
5489
5490
	/**
5491
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5492
	 *
5493
	 * @deprecated since 7.7.0
5494
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5495
	 *
5496
	 * @param array $options Standard Core options.
5497
	 * @return array Amended options.
5498
	 */
5499
	public function xmlrpc_options( $options ) {
5500
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5501
		return $this->connection_manager->xmlrpc_options( $options );
5502
	}
5503
5504
	/**
5505
	 * Cleans nonces that were saved when calling ::add_nonce.
5506
	 *
5507
	 * @deprecated since 7.7.0
5508
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5509
	 *
5510
	 * @param bool $all whether to clean even non-expired nonces.
5511
	 */
5512
	public static function clean_nonces( $all = false ) {
5513
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5514
		return self::connection()->clean_nonces( $all );
5515
	}
5516
5517
	/**
5518
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5519
	 * SET: state( $key, $value );
5520
	 * GET: $value = state( $key );
5521
	 *
5522
	 * @param string $key
5523
	 * @param string $value
5524
	 * @param bool   $restate private
5525
	 */
5526
	public static function state( $key = null, $value = null, $restate = false ) {
5527
		static $state = array();
5528
		static $path, $domain;
5529
		if ( ! isset( $path ) ) {
5530
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5531
			$admin_url = self::admin_url();
5532
			$bits      = wp_parse_url( $admin_url );
5533
5534
			if ( is_array( $bits ) ) {
5535
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5536
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5537
			} else {
5538
				$path = $domain = null;
5539
			}
5540
		}
5541
5542
		// Extract state from cookies and delete cookies
5543
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5544
			$yum = $_COOKIE['jetpackState'];
5545
			unset( $_COOKIE['jetpackState'] );
5546
			foreach ( $yum as $k => $v ) {
5547
				if ( strlen( $v ) ) {
5548
					$state[ $k ] = $v;
5549
				}
5550
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5551
			}
5552
		}
5553
5554
		if ( $restate ) {
5555
			foreach ( $state as $k => $v ) {
5556
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5557
			}
5558
			return;
5559
		}
5560
5561
		// Get a state variable
5562
		if ( isset( $key ) && ! isset( $value ) ) {
5563
			if ( array_key_exists( $key, $state ) ) {
5564
				return $state[ $key ];
5565
			}
5566
			return null;
5567
		}
5568
5569
		// Set a state variable
5570
		if ( isset( $key ) && isset( $value ) ) {
5571
			if ( is_array( $value ) && isset( $value[0] ) ) {
5572
				$value = $value[0];
5573
			}
5574
			$state[ $key ] = $value;
5575
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5576
		}
5577
	}
5578
5579
	public static function restate() {
5580
		self::state( null, null, true );
5581
	}
5582
5583
	public static function check_privacy( $file ) {
5584
		static $is_site_publicly_accessible = null;
5585
5586
		if ( is_null( $is_site_publicly_accessible ) ) {
5587
			$is_site_publicly_accessible = false;
5588
5589
			$rpc = new Jetpack_IXR_Client();
5590
5591
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5592
			if ( $success ) {
5593
				$response = $rpc->getResponse();
5594
				if ( $response ) {
5595
					$is_site_publicly_accessible = true;
5596
				}
5597
			}
5598
5599
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5600
		}
5601
5602
		if ( $is_site_publicly_accessible ) {
5603
			return;
5604
		}
5605
5606
		$module_slug = self::get_module_slug( $file );
5607
5608
		$privacy_checks = self::state( 'privacy_checks' );
5609
		if ( ! $privacy_checks ) {
5610
			$privacy_checks = $module_slug;
5611
		} else {
5612
			$privacy_checks .= ",$module_slug";
5613
		}
5614
5615
		self::state( 'privacy_checks', $privacy_checks );
5616
	}
5617
5618
	/**
5619
	 * Helper method for multicall XMLRPC.
5620
	 */
5621
	public static function xmlrpc_async_call() {
5622
		global $blog_id;
5623
		static $clients = array();
5624
5625
		$client_blog_id = is_multisite() ? $blog_id : 0;
5626
5627
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5628
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5629
			if ( function_exists( 'ignore_user_abort' ) ) {
5630
				ignore_user_abort( true );
5631
			}
5632
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5633
		}
5634
5635
		$args = func_get_args();
5636
5637
		if ( ! empty( $args[0] ) ) {
5638
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5639
		} elseif ( is_multisite() ) {
5640
			foreach ( $clients as $client_blog_id => $client ) {
5641
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5642
					continue;
5643
				}
5644
5645
				$switch_success = switch_to_blog( $client_blog_id, true );
5646
				if ( ! $switch_success ) {
5647
					continue;
5648
				}
5649
5650
				flush();
5651
				$client->query();
5652
5653
				restore_current_blog();
5654
			}
5655
		} else {
5656
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5657
				flush();
5658
				$clients[0]->query();
5659
			}
5660
		}
5661
	}
5662
5663
	public static function staticize_subdomain( $url ) {
5664
5665
		// Extract hostname from URL
5666
		$host = parse_url( $url, PHP_URL_HOST );
5667
5668
		// Explode hostname on '.'
5669
		$exploded_host = explode( '.', $host );
5670
5671
		// Retrieve the name and TLD
5672
		if ( count( $exploded_host ) > 1 ) {
5673
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5674
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5675
			// Rebuild domain excluding subdomains
5676
			$domain = $name . '.' . $tld;
5677
		} else {
5678
			$domain = $host;
5679
		}
5680
		// Array of Automattic domains
5681
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5682
5683
		// Return $url if not an Automattic domain
5684
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5685
			return $url;
5686
		}
5687
5688
		if ( is_ssl() ) {
5689
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5690
		}
5691
5692
		srand( crc32( basename( $url ) ) );
5693
		$static_counter = rand( 0, 2 );
5694
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5695
5696
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5697
	}
5698
5699
	/* JSON API Authorization */
5700
5701
	/**
5702
	 * Handles the login action for Authorizing the JSON API
5703
	 */
5704
	function login_form_json_api_authorization() {
5705
		$this->verify_json_api_authorization_request();
5706
5707
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5708
5709
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5710
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5711
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5712
	}
5713
5714
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5715
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5716
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5717
			return $url;
5718
		}
5719
5720
		$parsed_url = parse_url( $url );
5721
		$url        = strtok( $url, '?' );
5722
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5723
		if ( ! empty( $parsed_url['query'] ) ) {
5724
			$url .= "&{$parsed_url['query']}";
5725
		}
5726
5727
		return $url;
5728
	}
5729
5730
	// Make sure the POSTed request is handled by the same action
5731
	function preserve_action_in_login_form_for_json_api_authorization() {
5732
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5733
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5734
	}
5735
5736
	// If someone logs in to approve API access, store the Access Code in usermeta
5737
	function store_json_api_authorization_token( $user_login, $user ) {
5738
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5739
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5740
		$token = wp_generate_password( 32, false );
5741
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5742
	}
5743
5744
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5745
	function allow_wpcom_public_api_domain( $domains ) {
5746
		$domains[] = 'public-api.wordpress.com';
5747
		return $domains;
5748
	}
5749
5750
	static function is_redirect_encoded( $redirect_url ) {
5751
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5752
	}
5753
5754
	// Add all wordpress.com environments to the safe redirect whitelist
5755
	function allow_wpcom_environments( $domains ) {
5756
		$domains[] = 'wordpress.com';
5757
		$domains[] = 'wpcalypso.wordpress.com';
5758
		$domains[] = 'horizon.wordpress.com';
5759
		$domains[] = 'calypso.localhost';
5760
		return $domains;
5761
	}
5762
5763
	// Add the Access Code details to the public-api.wordpress.com redirect
5764
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5765
		return add_query_arg(
5766
			urlencode_deep(
5767
				array(
5768
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5769
					'jetpack-user-id' => (int) $user->ID,
5770
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5771
				)
5772
			),
5773
			$redirect_to
5774
		);
5775
	}
5776
5777
5778
	/**
5779
	 * Verifies the request by checking the signature
5780
	 *
5781
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5782
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5783
	 *
5784
	 * @param null|array $environment
5785
	 */
5786
	function verify_json_api_authorization_request( $environment = null ) {
5787
		$environment = is_null( $environment )
5788
			? $_REQUEST
5789
			: $environment;
5790
5791
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5792
		$token                                     = Jetpack_Data::get_access_token( $envUserId, $envToken );
5793
		if ( ! $token || empty( $token->secret ) ) {
5794
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5795
		}
5796
5797
		$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' );
5798
5799
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5800
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5801
			/**
5802
			 * Jetpack authorisation request Error.
5803
			 *
5804
			 * @since 7.5.0
5805
			 */
5806
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5807
			$die_error = sprintf(
5808
				/* translators: %s is a URL */
5809
				__( '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' ),
5810
				'https://jetpack.com/support/double-encoding/'
5811
			);
5812
		}
5813
5814
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5815
5816
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5817
			$signature = $jetpack_signature->sign_request(
5818
				$environment['token'],
5819
				$environment['timestamp'],
5820
				$environment['nonce'],
5821
				'',
5822
				'GET',
5823
				$environment['jetpack_json_api_original_query'],
5824
				null,
5825
				true
5826
			);
5827
		} else {
5828
			$signature = $jetpack_signature->sign_current_request(
5829
				array(
5830
					'body'   => null,
5831
					'method' => 'GET',
5832
				)
5833
			);
5834
		}
5835
5836
		if ( ! $signature ) {
5837
			wp_die( $die_error );
5838
		} elseif ( is_wp_error( $signature ) ) {
5839
			wp_die( $die_error );
5840
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5841
			if ( is_ssl() ) {
5842
				// 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
5843
				$signature = $jetpack_signature->sign_current_request(
5844
					array(
5845
						'scheme' => 'http',
5846
						'body'   => null,
5847
						'method' => 'GET',
5848
					)
5849
				);
5850
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5851
					wp_die( $die_error );
5852
				}
5853
			} else {
5854
				wp_die( $die_error );
5855
			}
5856
		}
5857
5858
		$timestamp = (int) $environment['timestamp'];
5859
		$nonce     = stripslashes( (string) $environment['nonce'] );
5860
5861
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5862
			// De-nonce the nonce, at least for 5 minutes.
5863
			// 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)
5864
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5865
			if ( $old_nonce_time < time() - 300 ) {
5866
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5867
			}
5868
		}
5869
5870
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5871
		$data_filters = array(
5872
			'state'        => 'opaque',
5873
			'client_id'    => 'int',
5874
			'client_title' => 'string',
5875
			'client_image' => 'url',
5876
		);
5877
5878
		foreach ( $data_filters as $key => $sanitation ) {
5879
			if ( ! isset( $data->$key ) ) {
5880
				wp_die( $die_error );
5881
			}
5882
5883
			switch ( $sanitation ) {
5884
				case 'int':
5885
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5886
					break;
5887
				case 'opaque':
5888
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5889
					break;
5890
				case 'string':
5891
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5892
					break;
5893
				case 'url':
5894
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5895
					break;
5896
			}
5897
		}
5898
5899
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5900
			wp_die( $die_error );
5901
		}
5902
	}
5903
5904
	function login_message_json_api_authorization( $message ) {
5905
		return '<p class="message">' . sprintf(
5906
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5907
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5908
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5909
	}
5910
5911
	/**
5912
	 * Get $content_width, but with a <s>twist</s> filter.
5913
	 */
5914
	public static function get_content_width() {
5915
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5916
			? $GLOBALS['content_width']
5917
			: false;
5918
		/**
5919
		 * Filter the Content Width value.
5920
		 *
5921
		 * @since 2.2.3
5922
		 *
5923
		 * @param string $content_width Content Width value.
5924
		 */
5925
		return apply_filters( 'jetpack_content_width', $content_width );
5926
	}
5927
5928
	/**
5929
	 * Pings the WordPress.com Mirror Site for the specified options.
5930
	 *
5931
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5932
	 *
5933
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5934
	 */
5935
	public function get_cloud_site_options( $option_names ) {
5936
		$option_names = array_filter( (array) $option_names, 'is_string' );
5937
5938
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
5939
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5940
		if ( $xml->isError() ) {
5941
			return array(
5942
				'error_code' => $xml->getErrorCode(),
5943
				'error_msg'  => $xml->getErrorMessage(),
5944
			);
5945
		}
5946
		$cloud_site_options = $xml->getResponse();
5947
5948
		return $cloud_site_options;
5949
	}
5950
5951
	/**
5952
	 * Checks if the site is currently in an identity crisis.
5953
	 *
5954
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5955
	 */
5956
	public static function check_identity_crisis() {
5957
		if ( ! self::is_active() || self::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5958
			return false;
5959
		}
5960
5961
		return Jetpack_Options::get_option( 'sync_error_idc' );
5962
	}
5963
5964
	/**
5965
	 * Checks whether the home and siteurl specifically are whitelisted
5966
	 * Written so that we don't have re-check $key and $value params every time
5967
	 * we want to check if this site is whitelisted, for example in footer.php
5968
	 *
5969
	 * @since  3.8.0
5970
	 * @return bool True = already whitelisted False = not whitelisted
5971
	 */
5972
	public static function is_staging_site() {
5973
		$is_staging = false;
5974
5975
		$known_staging = array(
5976
			'urls'      => array(
5977
				'#\.staging\.wpengine\.com$#i', // WP Engine
5978
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5979
				'#\.stage\.site$#i',            // DreamPress
5980
			),
5981
			'constants' => array(
5982
				'IS_WPE_SNAPSHOT',      // WP Engine
5983
				'KINSTA_DEV_ENV',       // Kinsta.com
5984
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5985
				'JETPACK_STAGING_MODE', // Generic
5986
			),
5987
		);
5988
		/**
5989
		 * Filters the flags of known staging sites.
5990
		 *
5991
		 * @since 3.9.0
5992
		 *
5993
		 * @param array $known_staging {
5994
		 *     An array of arrays that each are used to check if the current site is staging.
5995
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5996
		 *     @type array $constants PHP constants of known staging/developement environments.
5997
		 *  }
5998
		 */
5999
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6000
6001
		if ( isset( $known_staging['urls'] ) ) {
6002
			foreach ( $known_staging['urls'] as $url ) {
6003
				if ( preg_match( $url, site_url() ) ) {
6004
					$is_staging = true;
6005
					break;
6006
				}
6007
			}
6008
		}
6009
6010
		if ( isset( $known_staging['constants'] ) ) {
6011
			foreach ( $known_staging['constants'] as $constant ) {
6012
				if ( defined( $constant ) && constant( $constant ) ) {
6013
					$is_staging = true;
6014
				}
6015
			}
6016
		}
6017
6018
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6019
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6020
			$is_staging = true;
6021
		}
6022
6023
		/**
6024
		 * Filters is_staging_site check.
6025
		 *
6026
		 * @since 3.9.0
6027
		 *
6028
		 * @param bool $is_staging If the current site is a staging site.
6029
		 */
6030
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6031
	}
6032
6033
	/**
6034
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6035
	 *
6036
	 * @since 4.4.0
6037
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6038
	 *
6039
	 * @return bool
6040
	 */
6041
	public static function validate_sync_error_idc_option() {
6042
		$is_valid = false;
6043
6044
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6045
		if ( false === $idc_allowed ) {
6046
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6047
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6048
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6049
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6050
				$transient_duration = HOUR_IN_SECONDS;
6051
			} else {
6052
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6053
				$idc_allowed        = '1';
6054
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6055
			}
6056
6057
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6058
		}
6059
6060
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6061
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6062
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6063
			$local_options = self::get_sync_error_idc_option();
6064
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6065
				$is_valid = true;
6066
			}
6067
		}
6068
6069
		/**
6070
		 * Filters whether the sync_error_idc option is valid.
6071
		 *
6072
		 * @since 4.4.0
6073
		 *
6074
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6075
		 */
6076
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6077
6078
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6079
			// Since the option exists, and did not validate, delete it
6080
			Jetpack_Options::delete_option( 'sync_error_idc' );
6081
		}
6082
6083
		return $is_valid;
6084
	}
6085
6086
	/**
6087
	 * Normalizes a url by doing three things:
6088
	 *  - Strips protocol
6089
	 *  - Strips www
6090
	 *  - Adds a trailing slash
6091
	 *
6092
	 * @since 4.4.0
6093
	 * @param string $url
6094
	 * @return WP_Error|string
6095
	 */
6096
	public static function normalize_url_protocol_agnostic( $url ) {
6097
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6098
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6099
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
6100
		}
6101
6102
		// Strip www and protocols
6103
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6104
		return $url;
6105
	}
6106
6107
	/**
6108
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6109
	 *
6110
	 * @since 4.4.0
6111
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6112
	 *
6113
	 * @param array $response
6114
	 * @return array Array of the local urls, wpcom urls, and error code
6115
	 */
6116
	public static function get_sync_error_idc_option( $response = array() ) {
6117
		// Since the local options will hit the database directly, store the values
6118
		// in a transient to allow for autoloading and caching on subsequent views.
6119
		$local_options = get_transient( 'jetpack_idc_local' );
6120
		if ( false === $local_options ) {
6121
			$local_options = array(
6122
				'home'    => Functions::home_url(),
6123
				'siteurl' => Functions::site_url(),
6124
			);
6125
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6126
		}
6127
6128
		$options = array_merge( $local_options, $response );
6129
6130
		$returned_values = array();
6131
		foreach ( $options as $key => $option ) {
6132
			if ( 'error_code' === $key ) {
6133
				$returned_values[ $key ] = $option;
6134
				continue;
6135
			}
6136
6137
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6138
				continue;
6139
			}
6140
6141
			$returned_values[ $key ] = $normalized_url;
6142
		}
6143
6144
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6145
6146
		return $returned_values;
6147
	}
6148
6149
	/**
6150
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6151
	 * If set to true, the site will be put into staging mode.
6152
	 *
6153
	 * @since 4.3.2
6154
	 * @return bool
6155
	 */
6156
	public static function sync_idc_optin() {
6157
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6158
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6159
		} else {
6160
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6161
		}
6162
6163
		/**
6164
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6165
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6166
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6167
		 *
6168
		 * @since 4.3.2
6169
		 *
6170
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6171
		 */
6172
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6173
	}
6174
6175
	/**
6176
	 * Maybe Use a .min.css stylesheet, maybe not.
6177
	 *
6178
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6179
	 */
6180
	public static function maybe_min_asset( $url, $path, $plugin ) {
6181
		// Short out on things trying to find actual paths.
6182
		if ( ! $path || empty( $plugin ) ) {
6183
			return $url;
6184
		}
6185
6186
		$path = ltrim( $path, '/' );
6187
6188
		// Strip out the abspath.
6189
		$base = dirname( plugin_basename( $plugin ) );
6190
6191
		// Short out on non-Jetpack assets.
6192
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6193
			return $url;
6194
		}
6195
6196
		// File name parsing.
6197
		$file              = "{$base}/{$path}";
6198
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6199
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6200
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6201
		$extension         = array_shift( $file_name_parts_r );
6202
6203
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6204
			// Already pointing at the minified version.
6205
			if ( 'min' === $file_name_parts_r[0] ) {
6206
				return $url;
6207
			}
6208
6209
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6210
			if ( file_exists( $min_full_path ) ) {
6211
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6212
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6213
				if ( 'css' === $extension ) {
6214
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6215
					self::$min_assets[ $key ] = $path;
6216
				}
6217
			}
6218
		}
6219
6220
		return $url;
6221
	}
6222
6223
	/**
6224
	 * If the asset is minified, let's flag .min as the suffix.
6225
	 *
6226
	 * Attached to `style_loader_src` filter.
6227
	 *
6228
	 * @param string $tag The tag that would link to the external asset.
6229
	 * @param string $handle The registered handle of the script in question.
6230
	 * @param string $href The url of the asset in question.
6231
	 */
6232
	public static function set_suffix_on_min( $src, $handle ) {
6233
		if ( false === strpos( $src, '.min.css' ) ) {
6234
			return $src;
6235
		}
6236
6237
		if ( ! empty( self::$min_assets ) ) {
6238
			foreach ( self::$min_assets as $file => $path ) {
6239
				if ( false !== strpos( $src, $file ) ) {
6240
					wp_style_add_data( $handle, 'suffix', '.min' );
6241
					return $src;
6242
				}
6243
			}
6244
		}
6245
6246
		return $src;
6247
	}
6248
6249
	/**
6250
	 * Maybe inlines a stylesheet.
6251
	 *
6252
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6253
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6254
	 *
6255
	 * Attached to `style_loader_tag` filter.
6256
	 *
6257
	 * @param string $tag The tag that would link to the external asset.
6258
	 * @param string $handle The registered handle of the script in question.
6259
	 *
6260
	 * @return string
6261
	 */
6262
	public static function maybe_inline_style( $tag, $handle ) {
6263
		global $wp_styles;
6264
		$item = $wp_styles->registered[ $handle ];
6265
6266
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6267
			return $tag;
6268
		}
6269
6270
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6271
			$href = $matches[1];
6272
			// Strip off query string
6273
			if ( $pos = strpos( $href, '?' ) ) {
6274
				$href = substr( $href, 0, $pos );
6275
			}
6276
			// Strip off fragment
6277
			if ( $pos = strpos( $href, '#' ) ) {
6278
				$href = substr( $href, 0, $pos );
6279
			}
6280
		} else {
6281
			return $tag;
6282
		}
6283
6284
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6285
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6286
			return $tag;
6287
		}
6288
6289
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6290
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6291
			// And this isn't the pass that actually deals with the RTL version...
6292
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6293
				// Short out, as the RTL version will deal with it in a moment.
6294
				return $tag;
6295
			}
6296
		}
6297
6298
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6299
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6300
		if ( $css ) {
6301
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6302
			if ( empty( $item->extra['after'] ) ) {
6303
				wp_add_inline_style( $handle, $css );
6304
			} else {
6305
				array_unshift( $item->extra['after'], $css );
6306
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6307
			}
6308
		}
6309
6310
		return $tag;
6311
	}
6312
6313
	/**
6314
	 * Loads a view file from the views
6315
	 *
6316
	 * Data passed in with the $data parameter will be available in the
6317
	 * template file as $data['value']
6318
	 *
6319
	 * @param string $template - Template file to load
6320
	 * @param array  $data - Any data to pass along to the template
6321
	 * @return boolean - If template file was found
6322
	 **/
6323
	public function load_view( $template, $data = array() ) {
6324
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6325
6326
		if ( file_exists( $views_dir . $template ) ) {
6327
			require_once $views_dir . $template;
6328
			return true;
6329
		}
6330
6331
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6332
		return false;
6333
	}
6334
6335
	/**
6336
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6337
	 */
6338
	public function deprecated_hooks() {
6339
		global $wp_filter;
6340
6341
		/*
6342
		 * Format:
6343
		 * deprecated_filter_name => replacement_name
6344
		 *
6345
		 * If there is no replacement, use null for replacement_name
6346
		 */
6347
		$deprecated_list = array(
6348
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6349
			'wpl_sharing_2014_1'                           => null,
6350
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6351
			'jetpack_identity_crisis_options_to_check'     => null,
6352
			'update_option_jetpack_single_user_site'       => null,
6353
			'audio_player_default_colors'                  => null,
6354
			'add_option_jetpack_featured_images_enabled'   => null,
6355
			'add_option_jetpack_update_details'            => null,
6356
			'add_option_jetpack_updates'                   => null,
6357
			'add_option_jetpack_network_name'              => null,
6358
			'add_option_jetpack_network_allow_new_registrations' => null,
6359
			'add_option_jetpack_network_add_new_users'     => null,
6360
			'add_option_jetpack_network_site_upload_space' => null,
6361
			'add_option_jetpack_network_upload_file_types' => null,
6362
			'add_option_jetpack_network_enable_administration_menus' => null,
6363
			'add_option_jetpack_is_multi_site'             => null,
6364
			'add_option_jetpack_is_main_network'           => null,
6365
			'add_option_jetpack_main_network_site'         => null,
6366
			'jetpack_sync_all_registered_options'          => null,
6367
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6368
			'jetpack_is_post_mailable'                     => null,
6369
			'jetpack_seo_site_host'                        => null,
6370
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6371
			'jetpack_holiday_snow_option_name'             => null,
6372
			'jetpack_holiday_chance_of_snow'               => null,
6373
			'jetpack_holiday_snow_js_url'                  => null,
6374
			'jetpack_is_holiday_snow_season'               => null,
6375
			'jetpack_holiday_snow_option_updated'          => null,
6376
			'jetpack_holiday_snowing'                      => null,
6377
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6378
			'jetpack_cache_plans'                          => null,
6379
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6380
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6381
			'jetpack_enable_site_verification'             => null,
6382
			'can_display_jetpack_manage_notice'            => null,
6383
			// Removed in Jetpack 7.3.0
6384
			'atd_load_scripts'                             => null,
6385
			'atd_http_post_timeout'                        => null,
6386
			'atd_http_post_error'                          => null,
6387
			'atd_service_domain'                           => null,
6388
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6389
		);
6390
6391
		// This is a silly loop depth. Better way?
6392
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6393
			if ( has_action( $hook ) ) {
6394
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6395
					foreach ( $values as $hooked ) {
6396
						if ( is_callable( $hooked['function'] ) ) {
6397
							$function_name = 'an anonymous function';
6398
						} else {
6399
							$function_name = $hooked['function'];
6400
						}
6401
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6402
					}
6403
				}
6404
			}
6405
		}
6406
	}
6407
6408
	/**
6409
	 * Converts any url in a stylesheet, to the correct absolute url.
6410
	 *
6411
	 * Considerations:
6412
	 *  - Normal, relative URLs     `feh.png`
6413
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6414
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6415
	 *  - Absolute URLs             `http://domain.com/feh.png`
6416
	 *  - Domain root relative URLs `/feh.png`
6417
	 *
6418
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6419
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6420
	 *
6421
	 * @return mixed|string
6422
	 */
6423
	public static function absolutize_css_urls( $css, $css_file_url ) {
6424
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6425
		$css_dir = dirname( $css_file_url );
6426
		$p       = parse_url( $css_dir );
6427
		$domain  = sprintf(
6428
			'%1$s//%2$s%3$s%4$s',
6429
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6430
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6431
			$p['host'],
6432
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6433
		);
6434
6435
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6436
			$find = $replace = array();
6437
			foreach ( $matches as $match ) {
6438
				$url = trim( $match['path'], "'\" \t" );
6439
6440
				// If this is a data url, we don't want to mess with it.
6441
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6442
					continue;
6443
				}
6444
6445
				// If this is an absolute or protocol-agnostic url,
6446
				// we don't want to mess with it.
6447
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6448
					continue;
6449
				}
6450
6451
				switch ( substr( $url, 0, 1 ) ) {
6452
					case '/':
6453
						$absolute = $domain . $url;
6454
						break;
6455
					default:
6456
						$absolute = $css_dir . '/' . $url;
6457
				}
6458
6459
				$find[]    = $match[0];
6460
				$replace[] = sprintf( 'url("%s")', $absolute );
6461
			}
6462
			$css = str_replace( $find, $replace, $css );
6463
		}
6464
6465
		return $css;
6466
	}
6467
6468
	/**
6469
	 * This methods removes all of the registered css files on the front end
6470
	 * from Jetpack in favor of using a single file. In effect "imploding"
6471
	 * all the files into one file.
6472
	 *
6473
	 * Pros:
6474
	 * - Uses only ONE css asset connection instead of 15
6475
	 * - Saves a minimum of 56k
6476
	 * - Reduces server load
6477
	 * - Reduces time to first painted byte
6478
	 *
6479
	 * Cons:
6480
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6481
	 *      should not cause any issues with themes.
6482
	 * - Plugins/themes dequeuing styles no longer do anything. See
6483
	 *      jetpack_implode_frontend_css filter for a workaround
6484
	 *
6485
	 * For some situations developers may wish to disable css imploding and
6486
	 * instead operate in legacy mode where each file loads seperately and
6487
	 * can be edited individually or dequeued. This can be accomplished with
6488
	 * the following line:
6489
	 *
6490
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6491
	 *
6492
	 * @since 3.2
6493
	 **/
6494
	public function implode_frontend_css( $travis_test = false ) {
6495
		$do_implode = true;
6496
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6497
			$do_implode = false;
6498
		}
6499
6500
		// Do not implode CSS when the page loads via the AMP plugin.
6501
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6502
			$do_implode = false;
6503
		}
6504
6505
		/**
6506
		 * Allow CSS to be concatenated into a single jetpack.css file.
6507
		 *
6508
		 * @since 3.2.0
6509
		 *
6510
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6511
		 */
6512
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6513
6514
		// Do not use the imploded file when default behavior was altered through the filter
6515
		if ( ! $do_implode ) {
6516
			return;
6517
		}
6518
6519
		// We do not want to use the imploded file in dev mode, or if not connected
6520
		if ( self::is_development_mode() || ! self::is_active() ) {
6521
			if ( ! $travis_test ) {
6522
				return;
6523
			}
6524
		}
6525
6526
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6527
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6528
			return;
6529
		}
6530
6531
		/*
6532
		 * Now we assume Jetpack is connected and able to serve the single
6533
		 * file.
6534
		 *
6535
		 * In the future there will be a check here to serve the file locally
6536
		 * or potentially from the Jetpack CDN
6537
		 *
6538
		 * For now:
6539
		 * - Enqueue a single imploded css file
6540
		 * - Zero out the style_loader_tag for the bundled ones
6541
		 * - Be happy, drink scotch
6542
		 */
6543
6544
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6545
6546
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6547
6548
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6549
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6550
	}
6551
6552
	function concat_remove_style_loader_tag( $tag, $handle ) {
6553
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6554
			$tag = '';
6555
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6556
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6557
			}
6558
		}
6559
6560
		return $tag;
6561
	}
6562
6563
	/**
6564
	 * Add an async attribute to scripts that can be loaded asynchronously.
6565
	 * https://www.w3schools.com/tags/att_script_async.asp
6566
	 *
6567
	 * @since 7.7.0
6568
	 *
6569
	 * @param string $tag    The <script> tag for the enqueued script.
6570
	 * @param string $handle The script's registered handle.
6571
	 * @param string $src    The script's source URL.
6572
	 */
6573
	public function script_add_async( $tag, $handle, $src ) {
6574
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6575
			return preg_replace( '/^<script /i', '<script async ', $tag );
6576
		}
6577
6578
		return $tag;
6579
	}
6580
6581
	/*
6582
	 * Check the heartbeat data
6583
	 *
6584
	 * Organizes the heartbeat data by severity.  For example, if the site
6585
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6586
	 *
6587
	 * Data will be added to "caution" array, if it either:
6588
	 *  - Out of date Jetpack version
6589
	 *  - Out of date WP version
6590
	 *  - Out of date PHP version
6591
	 *
6592
	 * $return array $filtered_data
6593
	 */
6594
	public static function jetpack_check_heartbeat_data() {
6595
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6596
6597
		$good    = array();
6598
		$caution = array();
6599
		$bad     = array();
6600
6601
		foreach ( $raw_data as $stat => $value ) {
6602
6603
			// Check jetpack version
6604
			if ( 'version' == $stat ) {
6605
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6606
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6607
					continue;
6608
				}
6609
			}
6610
6611
			// Check WP version
6612
			if ( 'wp-version' == $stat ) {
6613
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6614
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6615
					continue;
6616
				}
6617
			}
6618
6619
			// Check PHP version
6620
			if ( 'php-version' == $stat ) {
6621
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6622
					$caution[ $stat ] = $value . ' - min supported is 5.2.4';
6623
					continue;
6624
				}
6625
			}
6626
6627
			// Check ID crisis
6628
			if ( 'identitycrisis' == $stat ) {
6629
				if ( 'yes' == $value ) {
6630
					$bad[ $stat ] = $value;
6631
					continue;
6632
				}
6633
			}
6634
6635
			// The rest are good :)
6636
			$good[ $stat ] = $value;
6637
		}
6638
6639
		$filtered_data = array(
6640
			'good'    => $good,
6641
			'caution' => $caution,
6642
			'bad'     => $bad,
6643
		);
6644
6645
		return $filtered_data;
6646
	}
6647
6648
6649
	/*
6650
	 * This method is used to organize all options that can be reset
6651
	 * without disconnecting Jetpack.
6652
	 *
6653
	 * It is used in class.jetpack-cli.php to reset options
6654
	 *
6655
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6656
	 *
6657
	 * @return array of options to delete.
6658
	 */
6659
	public static function get_jetpack_options_for_reset() {
6660
		return Jetpack_Options::get_options_for_reset();
6661
	}
6662
6663
	/*
6664
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6665
	 * so we can bring them directly to their site in calypso.
6666
	 *
6667
	 * @param string | url
6668
	 * @return string | url without the guff
6669
	 */
6670
	public static function build_raw_urls( $url ) {
6671
		$strip_http = '/.*?:\/\//i';
6672
		$url        = preg_replace( $strip_http, '', $url );
6673
		$url        = str_replace( '/', '::', $url );
6674
		return $url;
6675
	}
6676
6677
	/**
6678
	 * Stores and prints out domains to prefetch for page speed optimization.
6679
	 *
6680
	 * @param mixed $new_urls
6681
	 */
6682
	public static function dns_prefetch( $new_urls = null ) {
6683
		static $prefetch_urls = array();
6684
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6685
			echo "\r\n";
6686
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6687
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6688
			}
6689
		} elseif ( ! empty( $new_urls ) ) {
6690
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6691
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6692
			}
6693
			foreach ( (array) $new_urls as $this_new_url ) {
6694
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6695
			}
6696
			$prefetch_urls = array_unique( $prefetch_urls );
6697
		}
6698
	}
6699
6700
	public function wp_dashboard_setup() {
6701
		if ( self::is_active() ) {
6702
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6703
		}
6704
6705
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6706
			$jetpack_logo = new Jetpack_Logo();
6707
			$widget_title = sprintf(
6708
				wp_kses(
6709
					/* translators: Placeholder is a Jetpack logo. */
6710
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6711
					array( 'span' => array() )
6712
				),
6713
				$jetpack_logo->get_jp_emblem( true )
6714
			);
6715
6716
			wp_add_dashboard_widget(
6717
				'jetpack_summary_widget',
6718
				$widget_title,
6719
				array( __CLASS__, 'dashboard_widget' )
6720
			);
6721
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6722
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6723
6724
			// If we're inactive and not in development mode, sort our box to the top.
6725
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6726
				global $wp_meta_boxes;
6727
6728
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6729
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6730
6731
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6732
			}
6733
		}
6734
	}
6735
6736
	/**
6737
	 * @param mixed $result Value for the user's option
6738
	 * @return mixed
6739
	 */
6740
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6741
		if ( ! is_array( $sorted ) ) {
6742
			return $sorted;
6743
		}
6744
6745
		foreach ( $sorted as $box_context => $ids ) {
6746
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6747
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6748
				continue;
6749
			}
6750
6751
			$ids_array = explode( ',', $ids );
6752
			$key       = array_search( 'dashboard_stats', $ids_array );
6753
6754
			if ( false !== $key ) {
6755
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6756
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6757
				$sorted[ $box_context ] = implode( ',', $ids_array );
6758
				// We've found it, stop searching, and just return.
6759
				break;
6760
			}
6761
		}
6762
6763
		return $sorted;
6764
	}
6765
6766
	public static function dashboard_widget() {
6767
		/**
6768
		 * Fires when the dashboard is loaded.
6769
		 *
6770
		 * @since 3.4.0
6771
		 */
6772
		do_action( 'jetpack_dashboard_widget' );
6773
	}
6774
6775
	public static function dashboard_widget_footer() {
6776
		?>
6777
		<footer>
6778
6779
		<div class="protect">
6780
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6781
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6782
				<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>
6783
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6784
				<a href="
6785
				<?php
6786
				echo esc_url(
6787
					wp_nonce_url(
6788
						self::admin_url(
6789
							array(
6790
								'action' => 'activate',
6791
								'module' => 'protect',
6792
							)
6793
						),
6794
						'jetpack_activate-protect'
6795
					)
6796
				);
6797
				?>
6798
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6799
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6800
				</a>
6801
			<?php else : ?>
6802
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6803
			<?php endif; ?>
6804
		</div>
6805
6806
		<div class="akismet">
6807
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6808
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6809
				<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>
6810
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6811
				<a href="
6812
				<?php
6813
				echo esc_url(
6814
					wp_nonce_url(
6815
						add_query_arg(
6816
							array(
6817
								'action' => 'activate',
6818
								'plugin' => 'akismet/akismet.php',
6819
							),
6820
							admin_url( 'plugins.php' )
6821
						),
6822
						'activate-plugin_akismet/akismet.php'
6823
					)
6824
				);
6825
				?>
6826
							" class="button button-jetpack">
6827
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6828
				</a>
6829
			<?php else : ?>
6830
				<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>
6831
			<?php endif; ?>
6832
		</div>
6833
6834
		</footer>
6835
		<?php
6836
	}
6837
6838
	/*
6839
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6840
	 */
6841
	function jetpack_icon_user_connected( $columns ) {
6842
		$columns['user_jetpack'] = '';
6843
		return $columns;
6844
	}
6845
6846
	/*
6847
	 * Show Jetpack icon if the user is linked.
6848
	 */
6849
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6850
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6851
			$jetpack_logo = new Jetpack_Logo();
6852
			$emblem_html  = sprintf(
6853
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6854
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6855
				$jetpack_logo->get_jp_emblem()
6856
			);
6857
			return $emblem_html;
6858
		}
6859
6860
		return $val;
6861
	}
6862
6863
	/*
6864
	 * Style the Jetpack user column
6865
	 */
6866
	function jetpack_user_col_style() {
6867
		global $current_screen;
6868
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6869
			?>
6870
			<style>
6871
				.fixed .column-user_jetpack {
6872
					width: 21px;
6873
				}
6874
				.jp-emblem-user-admin svg {
6875
					width: 20px;
6876
					height: 20px;
6877
				}
6878
				.jp-emblem-user-admin path {
6879
					fill: #00BE28;
6880
				}
6881
			</style>
6882
			<?php
6883
		}
6884
	}
6885
6886
	/**
6887
	 * Checks if Akismet is active and working.
6888
	 *
6889
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6890
	 * that implied usage of methods present since more recent version.
6891
	 * See https://github.com/Automattic/jetpack/pull/9585
6892
	 *
6893
	 * @since  5.1.0
6894
	 *
6895
	 * @return bool True = Akismet available. False = Aksimet not available.
6896
	 */
6897
	public static function is_akismet_active() {
6898
		static $status = null;
6899
6900
		if ( ! is_null( $status ) ) {
6901
			return $status;
6902
		}
6903
6904
		// Check if a modern version of Akismet is active.
6905
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6906
			$status = false;
6907
			return $status;
6908
		}
6909
6910
		// Make sure there is a key known to Akismet at all before verifying key.
6911
		$akismet_key = Akismet::get_api_key();
6912
		if ( ! $akismet_key ) {
6913
			$status = false;
6914
			return $status;
6915
		}
6916
6917
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6918
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6919
6920
		// 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.
6921
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6922
		// We cache the result of the Akismet key verification for ten minutes.
6923
		if ( ! $akismet_key_state || $recheck ) {
6924
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6925
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6926
		}
6927
6928
		$status = 'valid' === $akismet_key_state;
6929
6930
		return $status;
6931
	}
6932
6933
	/**
6934
	 * @deprecated
6935
	 *
6936
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6937
	 */
6938
	public static function is_function_in_backtrace() {
6939
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6940
	}
6941
6942
	/**
6943
	 * Given a minified path, and a non-minified path, will return
6944
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6945
	 *
6946
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6947
	 * root Jetpack directory.
6948
	 *
6949
	 * @since 5.6.0
6950
	 *
6951
	 * @param string $min_path
6952
	 * @param string $non_min_path
6953
	 * @return string The URL to the file
6954
	 */
6955
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6956
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6957
	}
6958
6959
	/**
6960
	 * Checks for whether Jetpack Backup & Scan is enabled.
6961
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6962
	 *
6963
	 * @return bool|int|mixed
6964
	 */
6965
	public static function is_rewind_enabled() {
6966
		if ( ! self::is_active() ) {
6967
			return false;
6968
		}
6969
6970
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6971
		if ( false === $rewind_enabled ) {
6972
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6973
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6974
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6975
				&& ! empty( $rewind_data['state'] )
6976
				&& 'active' === $rewind_data['state'] )
6977
				? 1
6978
				: 0;
6979
6980
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6981
		}
6982
		return $rewind_enabled;
6983
	}
6984
6985
	/**
6986
	 * Return Calypso environment value; used for developing Jetpack and pairing
6987
	 * it with different Calypso enrionments, such as localhost.
6988
	 *
6989
	 * @since 7.4.0
6990
	 *
6991
	 * @return string Calypso environment
6992
	 */
6993
	public static function get_calypso_env() {
6994
		if ( isset( $_GET['calypso_env'] ) ) {
6995
			return sanitize_key( $_GET['calypso_env'] );
6996
		}
6997
6998
		if ( getenv( 'CALYPSO_ENV' ) ) {
6999
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7000
		}
7001
7002
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7003
			return sanitize_key( CALYPSO_ENV );
7004
		}
7005
7006
		return '';
7007
	}
7008
7009
	/**
7010
	 * Checks whether or not TOS has been agreed upon.
7011
	 * Will return true if a user has clicked to register, or is already connected.
7012
	 */
7013
	public static function jetpack_tos_agreed() {
7014
		return Jetpack_Options::get_option( 'tos_agreed' ) || self::is_active();
7015
	}
7016
7017
	/**
7018
	 * Handles activating default modules as well general cleanup for the new connection.
7019
	 *
7020
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7021
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7022
	 * @param boolean $send_state_messages          Whether to send state messages.
7023
	 * @return void
7024
	 */
7025
	public static function handle_post_authorization_actions(
7026
		$activate_sso = false,
7027
		$redirect_on_activation_error = false,
7028
		$send_state_messages = true
7029
	) {
7030
		$other_modules = $activate_sso
7031
			? array( 'sso' )
7032
			: array();
7033
7034
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7035
			self::delete_active_modules();
7036
7037
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
999 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7038
		} else {
7039
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7040
		}
7041
7042
		// Since this is a fresh connection, be sure to clear out IDC options
7043
		Jetpack_IDC::clear_all_idc_options();
7044
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7045
7046
		// Start nonce cleaner
7047
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7048
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7049
7050
		if ( $send_state_messages ) {
7051
			self::state( 'message', 'authorized' );
7052
		}
7053
	}
7054
7055
	/**
7056
	 * Returns a boolean for whether backups UI should be displayed or not.
7057
	 *
7058
	 * @return bool Should backups UI be displayed?
7059
	 */
7060
	public static function show_backups_ui() {
7061
		/**
7062
		 * Whether UI for backups should be displayed.
7063
		 *
7064
		 * @since 6.5.0
7065
		 *
7066
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7067
		 */
7068
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7069
	}
7070
7071
	/*
7072
	 * Deprecated manage functions
7073
	 */
7074
	function prepare_manage_jetpack_notice() {
7075
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7076
	}
7077
	function manage_activate_screen() {
7078
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7079
	}
7080
	function admin_jetpack_manage_notice() {
7081
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7082
	}
7083
	function opt_out_jetpack_manage_url() {
7084
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7085
	}
7086
	function opt_in_jetpack_manage_url() {
7087
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7088
	}
7089
	function opt_in_jetpack_manage_notice() {
7090
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7091
	}
7092
	function can_display_jetpack_manage_notice() {
7093
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7094
	}
7095
7096
	/**
7097
	 * Clean leftoveruser meta.
7098
	 *
7099
	 * Delete Jetpack-related user meta when it is no longer needed.
7100
	 *
7101
	 * @since 7.3.0
7102
	 *
7103
	 * @param int $user_id User ID being updated.
7104
	 */
7105
	public static function user_meta_cleanup( $user_id ) {
7106
		$meta_keys = array(
7107
			// AtD removed from Jetpack 7.3
7108
			'AtD_options',
7109
			'AtD_check_when',
7110
			'AtD_guess_lang',
7111
			'AtD_ignored_phrases',
7112
		);
7113
7114
		foreach ( $meta_keys as $meta_key ) {
7115
			if ( get_user_meta( $user_id, $meta_key ) ) {
7116
				delete_user_meta( $user_id, $meta_key );
7117
			}
7118
		}
7119
	}
7120
7121
	function is_active_and_not_development_mode( $maybe ) {
7122
		if ( ! self::is_active() || self::is_development_mode() ) {
7123
			return false;
7124
		}
7125
		return true;
7126
	}
7127
}
7128