Completed
Push — update/instant-search-results-... ( 83e479...39737e )
by
unknown
32:55 queued 25:28
created

class.jetpack.php (2 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
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @return $success bool true for success, false for failure.
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		$this->connection_manager = new Connection_Manager();
578
		$this->connection_manager->init();
579
580
		/*
581
		 * Load things that should only be in Network Admin.
582
		 *
583
		 * For now blow away everything else until a more full
584
		 * understanding of what is needed at the network level is
585
		 * available
586
		 */
587
		if ( is_multisite() ) {
588
			$network = Jetpack_Network::init();
589
			$network->set_connection( $this->connection_manager );
590
		}
591
592
		add_filter(
593
			'jetpack_signature_check_token',
594
			array( __CLASS__, 'verify_onboarding_token' ),
595
			10,
596
			3
597
		);
598
599
		/**
600
		 * Prepare Gutenberg Editor functionality
601
		 */
602
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
603
		Jetpack_Gutenberg::init();
604
		Jetpack_Gutenberg::load_independent_blocks();
605
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
606
607
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
608
609
		// Unlink user before deleting the user from WP.com.
610
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
612
613
		// Initialize remote file upload request handlers.
614
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
615
		$is_jetpack_xmlrpc_request = isset( $_GET['for'] ) && 'jetpack' === $_GET['for'] && Constants::get_constant( 'XMLRPC_REQUEST' );
616 View Code Duplication
		if (
617
			! $is_jetpack_xmlrpc_request
618
			&& is_admin()
619
			&& isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification
620
			&& (
621
				'jetpack_upload_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
622
				|| 'jetpack_update_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
623
			)
624
		) {
625
			$this->add_remote_request_handlers();
626
		}
627
628
		if ( Jetpack::is_active() ) {
629
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
630
631
			Jetpack_Heartbeat::init();
632
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
633
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
634
				Jetpack_Search_Performance_Logger::init();
635
			}
636
		}
637
638
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
639
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
640
641
		add_action( 'admin_init', array( $this, 'admin_init' ) );
642
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
643
644
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
645
646
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
647
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
648
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
649
650
		// returns HTTPS support status
651
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
652
653
		// JITM AJAX callback function
654
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
655
656
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
657
658
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
659
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
660
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
661
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
662
663
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
664
665
		/**
666
		 * These actions run checks to load additional files.
667
		 * They check for external files or plugins, so they need to run as late as possible.
668
		 */
669
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
670
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
671
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
672
673
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
674
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
675
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
676
677
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
678
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
679
680
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
681
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
682
683
		// A filter to control all just in time messages
684
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
685
686
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
687
688
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
689
		// We should make sure to only do this for front end links.
690
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
691
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
692
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
693
694
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
695
			//so they point moderation links on emails to Calypso
696
			jetpack_require_lib( 'functions.wp-notify' );
697
		}
698
699
		// Hide edit post link if mobile app.
700
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
701
			add_filter( 'edit_post_link', '__return_empty_string' );
702
		}
703
704
		// Update the Jetpack plan from API on heartbeats
705
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
706
707
		/**
708
		 * This is the hack to concatenate all css files into one.
709
		 * For description and reasoning see the implode_frontend_css method
710
		 *
711
		 * Super late priority so we catch all the registered styles
712
		 */
713
		if( !is_admin() ) {
714
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
715
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
716
		}
717
718
719
		/**
720
		 * These are sync actions that we need to keep track of for jitms
721
		 */
722
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
723
724
		// Actually push the stats on shutdown.
725
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
726
			add_action( 'shutdown', array( $this, 'push_stats' ) );
727
		}
728
729
		/*
730
		 * Load some scripts asynchronously.
731
		 */
732
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
733
	}
734
735
	/**
736
	 * Sets up the XMLRPC request handlers.
737
	 *
738
	 * @deprecated since 7.7.0
739
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
740
	 *
741
	 * @param Array                 $request_params Incoming request parameters.
742
	 * @param Boolean               $is_active      Whether the connection is currently active.
743
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
744
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
745
	 */
746
	public function setup_xmlrpc_handlers(
747
		$request_params,
748
		$is_active,
749
		$is_signed,
750
		Jetpack_XMLRPC_Server $xmlrpc_server = null
751
	) {
752
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
753
		return $this->connection_manager->setup_xmlrpc_handlers(
754
			$request_params,
755
			$is_active,
756
			$is_signed,
757
			$xmlrpc_server
758
		);
759
	}
760
761
	/**
762
	 * Initialize REST API registration connector.
763
	 *
764
	 * @deprecated since 7.7.0
765
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
766
	 */
767
	public function initialize_rest_api_registration_connector() {
768
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
769
		$this->connection_manager->initialize_rest_api_registration_connector();
770
	}
771
772
	/**
773
	 * This is ported over from the manage module, which has been deprecated and baked in here.
774
	 *
775
	 * @param $domains
776
	 */
777
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
778
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
779
	}
780
781
	/**
782
	 * Return $domains, with 'wordpress.com' appended.
783
	 * This is ported over from the manage module, which has been deprecated and baked in here.
784
	 *
785
	 * @param $domains
786
	 * @return array
787
	 */
788
	function allow_wpcom_domain( $domains ) {
789
		if ( empty( $domains ) ) {
790
			$domains = array();
791
		}
792
		$domains[] = 'wordpress.com';
793
		return array_unique( $domains );
794
	}
795
796
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
797
		$post = get_post( $post_id );
798
799
		if ( empty( $post ) ) {
800
			return $default_url;
801
		}
802
803
		$post_type = $post->post_type;
804
805
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
806
		// https://en.support.wordpress.com/custom-post-types/
807
		$allowed_post_types = array(
808
			'post' => 'post',
809
			'page' => 'page',
810
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
811
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
812
		);
813
814
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
815
			return $default_url;
816
		}
817
818
		$path_prefix = $allowed_post_types[ $post_type ];
819
820
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
821
822
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
823
	}
824
825
	function point_edit_comment_links_to_calypso( $url ) {
826
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
827
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
828
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
829
			Jetpack::build_raw_urls( get_home_url() ),
830
			$query_args['amp;c']
831
		) );
832
	}
833
834
	function jetpack_track_last_sync_callback( $params ) {
835
		/**
836
		 * Filter to turn off jitm caching
837
		 *
838
		 * @since 5.4.0
839
		 *
840
		 * @param bool false Whether to cache just in time messages
841
		 */
842
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
843
			return $params;
844
		}
845
846
		if ( is_array( $params ) && isset( $params[0] ) ) {
847
			$option = $params[0];
848
			if ( 'active_plugins' === $option ) {
849
				// use the cache if we can, but not terribly important if it gets evicted
850
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
851
			}
852
		}
853
854
		return $params;
855
	}
856
857
	function jetpack_connection_banner_callback() {
858
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
859
860
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
861
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
862
			wp_send_json_success();
863
		}
864
865
		wp_die();
866
	}
867
868
	/**
869
	 * Removes all XML-RPC methods that are not `jetpack.*`.
870
	 * Only used in our alternate XML-RPC endpoint, where we want to
871
	 * ensure that Core and other plugins' methods are not exposed.
872
	 *
873
	 * @deprecated since 7.7.0
874
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
875
	 *
876
	 * @param array $methods A list of registered WordPress XMLRPC methods.
877
	 * @return array Filtered $methods
878
	 */
879
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
880
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
881
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
882
	}
883
884
	/**
885
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
886
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
887
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
888
	 * which is accessible via a different URI. Most of the below is copied directly
889
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
890
	 *
891
	 * @deprecated since 7.7.0
892
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
893
	 */
894
	public function alternate_xmlrpc() {
895
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
896
		$this->connection_manager->alternate_xmlrpc();
897
	}
898
899
	/**
900
	 * The callback for the JITM ajax requests.
901
	 */
902
	function jetpack_jitm_ajax_callback() {
903
		// Check for nonce
904
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
905
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
906
		}
907
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
908
			$module_slug = $_REQUEST['jitmModule'];
909
			Jetpack::log( 'activate', $module_slug );
910
			Jetpack::activate_module( $module_slug, false, false );
911
			Jetpack::state( 'message', 'no_message' );
912
913
			//A Jetpack module is being activated through a JITM, track it
914
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
915
			$this->do_stats( 'server_side' );
916
917
			wp_send_json_success();
918
		}
919
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
920
			// get the hide_jitm options array
921
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
922
			$module_slug = $_REQUEST['jitmModule'];
923
924
			if( ! $jetpack_hide_jitm ) {
925
				$jetpack_hide_jitm = array(
926
					$module_slug => 'hide'
927
				);
928
			} else {
929
				$jetpack_hide_jitm[$module_slug] = 'hide';
930
			}
931
932
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
933
934
			//jitm is being dismissed forever, track it
935
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
936
			$this->do_stats( 'server_side' );
937
938
			wp_send_json_success();
939
		}
940 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
941
			$module_slug = $_REQUEST['jitmModule'];
942
943
			// User went to WordPress.com, track this
944
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
945
			$this->do_stats( 'server_side' );
946
947
			wp_send_json_success();
948
		}
949 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
950
			$track = $_REQUEST['jitmModule'];
951
952
			// User is viewing JITM, track it.
953
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
954
			$this->do_stats( 'server_side' );
955
956
			wp_send_json_success();
957
		}
958
	}
959
960
	/**
961
	 * If there are any stats that need to be pushed, but haven't been, push them now.
962
	 */
963
	function push_stats() {
964
		if ( ! empty( $this->stats ) ) {
965
			$this->do_stats( 'server_side' );
966
		}
967
	}
968
969
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
970
		switch( $cap ) {
971
			case 'jetpack_connect' :
972
			case 'jetpack_reconnect' :
973
				if ( Jetpack::is_development_mode() ) {
974
					$caps = array( 'do_not_allow' );
975
					break;
976
				}
977
				/**
978
				 * Pass through. If it's not development mode, these should match disconnect.
979
				 * Let users disconnect if it's development mode, just in case things glitch.
980
				 */
981
			case 'jetpack_disconnect' :
982
				/**
983
				 * In multisite, can individual site admins manage their own connection?
984
				 *
985
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
986
				 */
987
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
988
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
989
						/**
990
						 * We need to update the option name -- it's terribly unclear which
991
						 * direction the override goes.
992
						 *
993
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
994
						 */
995
						$caps = array( 'do_not_allow' );
996
						break;
997
					}
998
				}
999
1000
				$caps = array( 'manage_options' );
1001
				break;
1002
			case 'jetpack_manage_modules' :
1003
			case 'jetpack_activate_modules' :
1004
			case 'jetpack_deactivate_modules' :
1005
				$caps = array( 'manage_options' );
1006
				break;
1007
			case 'jetpack_configure_modules' :
1008
				$caps = array( 'manage_options' );
1009
				break;
1010
			case 'jetpack_manage_autoupdates' :
1011
				$caps = array(
1012
					'manage_options',
1013
					'update_plugins',
1014
				);
1015
				break;
1016
			case 'jetpack_network_admin_page':
1017
			case 'jetpack_network_settings_page':
1018
				$caps = array( 'manage_network_plugins' );
1019
				break;
1020
			case 'jetpack_network_sites_page':
1021
				$caps = array( 'manage_sites' );
1022
				break;
1023
			case 'jetpack_admin_page' :
1024
				if ( Jetpack::is_development_mode() ) {
1025
					$caps = array( 'manage_options' );
1026
					break;
1027
				} else {
1028
					$caps = array( 'read' );
1029
				}
1030
				break;
1031
			case 'jetpack_connect_user' :
1032
				if ( Jetpack::is_development_mode() ) {
1033
					$caps = array( 'do_not_allow' );
1034
					break;
1035
				}
1036
				$caps = array( 'read' );
1037
				break;
1038
		}
1039
		return $caps;
1040
	}
1041
1042
	/**
1043
	 * Require a Jetpack authentication.
1044
	 *
1045
	 * @deprecated since 7.7.0
1046
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1047
	 */
1048
	public function require_jetpack_authentication() {
1049
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1050
		$this->connection_manager->require_jetpack_authentication();
1051
	}
1052
1053
	/**
1054
	 * Load language files
1055
	 * @action plugins_loaded
1056
	 */
1057
	public static function plugin_textdomain() {
1058
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1059
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1060
	}
1061
1062
	/**
1063
	 * Register assets for use in various modules and the Jetpack admin page.
1064
	 *
1065
	 * @uses wp_script_is, wp_register_script, plugins_url
1066
	 * @action wp_loaded
1067
	 * @return null
1068
	 */
1069
	public function register_assets() {
1070
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1071
			wp_register_script(
1072
				'spin',
1073
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1074
				false,
1075
				'1.3'
1076
			);
1077
		}
1078
1079 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1080
			wp_register_script(
1081
				'jquery.spin',
1082
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1083
				array( 'jquery', 'spin' ),
1084
				'1.3'
1085
			);
1086
		}
1087
1088 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1089
			wp_register_script(
1090
				'jetpack-gallery-settings',
1091
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1092
				array( 'media-views' ),
1093
				'20121225'
1094
			);
1095
		}
1096
1097 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1098
			wp_register_script(
1099
				'jetpack-twitter-timeline',
1100
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1101
				array( 'jquery' ),
1102
				'4.0.0',
1103
				true
1104
			);
1105
		}
1106
1107
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1108
			wp_register_script(
1109
				'jetpack-facebook-embed',
1110
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1111
				array( 'jquery' ),
1112
				null,
1113
				true
1114
			);
1115
1116
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1117
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1118
			if ( ! is_numeric( $fb_app_id ) ) {
1119
				$fb_app_id = '';
1120
			}
1121
			wp_localize_script(
1122
				'jetpack-facebook-embed',
1123
				'jpfbembed',
1124
				array(
1125
					'appid' => $fb_app_id,
1126
					'locale' => $this->get_locale(),
1127
				)
1128
			);
1129
		}
1130
1131
		/**
1132
		 * As jetpack_register_genericons is by default fired off a hook,
1133
		 * the hook may have already fired by this point.
1134
		 * So, let's just trigger it manually.
1135
		 */
1136
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1137
		jetpack_register_genericons();
1138
1139
		/**
1140
		 * Register the social logos
1141
		 */
1142
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1143
		jetpack_register_social_logos();
1144
1145 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1146
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1147
	}
1148
1149
	/**
1150
	 * Guess locale from language code.
1151
	 *
1152
	 * @param string $lang Language code.
1153
	 * @return string|bool
1154
	 */
1155 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1156
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1157
			return 'en_US';
1158
		}
1159
1160
		if ( ! class_exists( 'GP_Locales' ) ) {
1161
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1162
				return false;
1163
			}
1164
1165
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1166
		}
1167
1168
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1169
			// WP.com: get_locale() returns 'it'
1170
			$locale = GP_Locales::by_slug( $lang );
1171
		} else {
1172
			// Jetpack: get_locale() returns 'it_IT';
1173
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1174
		}
1175
1176
		if ( ! $locale ) {
1177
			return false;
1178
		}
1179
1180
		if ( empty( $locale->facebook_locale ) ) {
1181
			if ( empty( $locale->wp_locale ) ) {
1182
				return false;
1183
			} else {
1184
				// Facebook SDK is smart enough to fall back to en_US if a
1185
				// locale isn't supported. Since supported Facebook locales
1186
				// can fall out of sync, we'll attempt to use the known
1187
				// wp_locale value and rely on said fallback.
1188
				return $locale->wp_locale;
1189
			}
1190
		}
1191
1192
		return $locale->facebook_locale;
1193
	}
1194
1195
	/**
1196
	 * Get the locale.
1197
	 *
1198
	 * @return string|bool
1199
	 */
1200
	function get_locale() {
1201
		$locale = $this->guess_locale_from_lang( get_locale() );
1202
1203
		if ( ! $locale ) {
1204
			$locale = 'en_US';
1205
		}
1206
1207
		return $locale;
1208
	}
1209
1210
	/**
1211
	 * Device Pixels support
1212
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1213
	 */
1214
	function devicepx() {
1215
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1216
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1217
		}
1218
	}
1219
1220
	/**
1221
	 * Return the network_site_url so that .com knows what network this site is a part of.
1222
	 * @param  bool $option
1223
	 * @return string
1224
	 */
1225
	public function jetpack_main_network_site_option( $option ) {
1226
		return network_site_url();
1227
	}
1228
	/**
1229
	 * Network Name.
1230
	 */
1231
	static function network_name( $option = null ) {
1232
		global $current_site;
1233
		return $current_site->site_name;
1234
	}
1235
	/**
1236
	 * Does the network allow new user and site registrations.
1237
	 * @return string
1238
	 */
1239
	static function network_allow_new_registrations( $option = null ) {
1240
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1241
	}
1242
	/**
1243
	 * Does the network allow admins to add new users.
1244
	 * @return boolian
1245
	 */
1246
	static function network_add_new_users( $option = null ) {
1247
		return (bool) get_site_option( 'add_new_users' );
1248
	}
1249
	/**
1250
	 * File upload psace left per site in MB.
1251
	 *  -1 means NO LIMIT.
1252
	 * @return number
1253
	 */
1254
	static function network_site_upload_space( $option = null ) {
1255
		// value in MB
1256
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1257
	}
1258
1259
	/**
1260
	 * Network allowed file types.
1261
	 * @return string
1262
	 */
1263
	static function network_upload_file_types( $option = null ) {
1264
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1265
	}
1266
1267
	/**
1268
	 * Maximum file upload size set by the network.
1269
	 * @return number
1270
	 */
1271
	static function network_max_upload_file_size( $option = null ) {
1272
		// value in KB
1273
		return get_site_option( 'fileupload_maxk', 300 );
1274
	}
1275
1276
	/**
1277
	 * Lets us know if a site allows admins to manage the network.
1278
	 * @return array
1279
	 */
1280
	static function network_enable_administration_menus( $option = null ) {
1281
		return get_site_option( 'menu_items' );
1282
	}
1283
1284
	/**
1285
	 * If a user has been promoted to or demoted from admin, we need to clear the
1286
	 * jetpack_other_linked_admins transient.
1287
	 *
1288
	 * @since 4.3.2
1289
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1290
	 *
1291
	 * @param int    $user_id   The user ID whose role changed.
1292
	 * @param string $role      The new role.
1293
	 * @param array  $old_roles An array of the user's previous roles.
1294
	 */
1295
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1296
		if ( 'administrator' == $role
1297
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1298
			|| is_null( $old_roles )
1299
		) {
1300
			delete_transient( 'jetpack_other_linked_admins' );
1301
		}
1302
	}
1303
1304
	/**
1305
	 * Checks to see if there are any other users available to become primary
1306
	 * Users must both:
1307
	 * - Be linked to wpcom
1308
	 * - Be an admin
1309
	 *
1310
	 * @return mixed False if no other users are linked, Int if there are.
1311
	 */
1312
	static function get_other_linked_admins() {
1313
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1314
1315
		if ( false === $other_linked_users ) {
1316
			$admins = get_users( array( 'role' => 'administrator' ) );
1317
			if ( count( $admins ) > 1 ) {
1318
				$available = array();
1319
				foreach ( $admins as $admin ) {
1320
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1321
						$available[] = $admin->ID;
1322
					}
1323
				}
1324
1325
				$count_connected_admins = count( $available );
1326
				if ( count( $available ) > 1 ) {
1327
					$other_linked_users = $count_connected_admins;
1328
				} else {
1329
					$other_linked_users = 0;
1330
				}
1331
			} else {
1332
				$other_linked_users = 0;
1333
			}
1334
1335
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1336
		}
1337
1338
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1339
	}
1340
1341
	/**
1342
	 * Return whether we are dealing with a multi network setup or not.
1343
	 * The reason we are type casting this is because we want to avoid the situation where
1344
	 * the result is false since when is_main_network_option return false it cases
1345
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1346
	 * database which could be set to anything as opposed to what this function returns.
1347
	 * @param  bool  $option
1348
	 *
1349
	 * @return boolean
1350
	 */
1351
	public function is_main_network_option( $option ) {
1352
		// return '1' or ''
1353
		return (string) (bool) Jetpack::is_multi_network();
1354
	}
1355
1356
	/**
1357
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1358
	 *
1359
	 * @param  string  $option
1360
	 * @return boolean
1361
	 */
1362
	public function is_multisite( $option ) {
1363
		return (string) (bool) is_multisite();
1364
	}
1365
1366
	/**
1367
	 * Implemented since there is no core is multi network function
1368
	 * Right now there is no way to tell if we which network is the dominant network on the system
1369
	 *
1370
	 * @since  3.3
1371
	 * @return boolean
1372
	 */
1373 View Code Duplication
	public static function is_multi_network() {
1374
		global  $wpdb;
1375
1376
		// if we don't have a multi site setup no need to do any more
1377
		if ( ! is_multisite() ) {
1378
			return false;
1379
		}
1380
1381
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1382
		if ( $num_sites > 1 ) {
1383
			return true;
1384
		} else {
1385
			return false;
1386
		}
1387
	}
1388
1389
	/**
1390
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1391
	 * @return null
1392
	 */
1393
	function update_jetpack_main_network_site_option() {
1394
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1395
	}
1396
	/**
1397
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1398
	 *
1399
	 */
1400
	function update_jetpack_network_settings() {
1401
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1402
		// Only sync this info for the main network site.
1403
	}
1404
1405
	/**
1406
	 * Get back if the current site is single user site.
1407
	 *
1408
	 * @return bool
1409
	 */
1410 View Code Duplication
	public static function is_single_user_site() {
1411
		global $wpdb;
1412
1413
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1414
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1415
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1416
		}
1417
		return 1 === (int) $some_users;
1418
	}
1419
1420
	/**
1421
	 * Returns true if the site has file write access false otherwise.
1422
	 * @return string ( '1' | '0' )
1423
	 **/
1424
	public static function file_system_write_access() {
1425
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1426
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1427
		}
1428
1429
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1430
1431
		$filesystem_method = get_filesystem_method();
1432
		if ( $filesystem_method === 'direct' ) {
1433
			return 1;
1434
		}
1435
1436
		ob_start();
1437
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1438
		ob_end_clean();
1439
		if ( $filesystem_credentials_are_stored ) {
1440
			return 1;
1441
		}
1442
		return 0;
1443
	}
1444
1445
	/**
1446
	 * Finds out if a site is using a version control system.
1447
	 * @return string ( '1' | '0' )
1448
	 **/
1449
	public static function is_version_controlled() {
1450
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1451
		return (string) (int) Functions::is_version_controlled();
1452
	}
1453
1454
	/**
1455
	 * Determines whether the current theme supports featured images or not.
1456
	 * @return string ( '1' | '0' )
1457
	 */
1458
	public static function featured_images_enabled() {
1459
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1460
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1461
	}
1462
1463
	/**
1464
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1465
	 *
1466
	 * @deprecated 4.7 use get_avatar_url instead.
1467
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1468
	 * @param int $size Size of the avatar image
1469
	 * @param string $default URL to a default image to use if no avatar is available
1470
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1471
	 *
1472
	 * @return array
1473
	 */
1474
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1475
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1476
		return get_avatar_url( $id_or_email, array(
1477
			'size' => $size,
1478
			'default' => $default,
1479
			'force_default' => $force_display,
1480
		) );
1481
	}
1482
1483
	/**
1484
	 * jetpack_updates is saved in the following schema:
1485
	 *
1486
	 * array (
1487
	 *      'plugins'                       => (int) Number of plugin updates available.
1488
	 *      'themes'                        => (int) Number of theme updates available.
1489
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1490
	 *      'translations'                  => (int) Number of translation updates available.
1491
	 *      'total'                         => (int) Total of all available updates.
1492
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1493
	 * )
1494
	 * @return array
1495
	 */
1496
	public static function get_updates() {
1497
		$update_data = wp_get_update_data();
1498
1499
		// Stores the individual update counts as well as the total count.
1500
		if ( isset( $update_data['counts'] ) ) {
1501
			$updates = $update_data['counts'];
1502
		}
1503
1504
		// If we need to update WordPress core, let's find the latest version number.
1505 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1506
			$cur = get_preferred_from_update_core();
1507
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1508
				$updates['wp_update_version'] = $cur->current;
1509
			}
1510
		}
1511
		return isset( $updates ) ? $updates : array();
1512
	}
1513
1514
	public static function get_update_details() {
1515
		$update_details = array(
1516
			'update_core' => get_site_transient( 'update_core' ),
1517
			'update_plugins' => get_site_transient( 'update_plugins' ),
1518
			'update_themes' => get_site_transient( 'update_themes' ),
1519
		);
1520
		return $update_details;
1521
	}
1522
1523
	public static function refresh_update_data() {
1524
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1525
1526
	}
1527
1528
	public static function refresh_theme_data() {
1529
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1530
	}
1531
1532
	/**
1533
	 * Is Jetpack active?
1534
	 */
1535
	public static function is_active() {
1536
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1537
	}
1538
1539
	/**
1540
	 * Make an API call to WordPress.com for plan status
1541
	 *
1542
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1543
	 *
1544
	 * @return bool True if plan is updated, false if no update
1545
	 */
1546
	public static function refresh_active_plan_from_wpcom() {
1547
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1548
		return Jetpack_Plan::refresh_from_wpcom();
1549
	}
1550
1551
	/**
1552
	 * Get the plan that this Jetpack site is currently using
1553
	 *
1554
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1555
	 * @return array Active Jetpack plan details.
1556
	 */
1557
	public static function get_active_plan() {
1558
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1559
		return Jetpack_Plan::get();
1560
	}
1561
1562
	/**
1563
	 * Determine whether the active plan supports a particular feature
1564
	 *
1565
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1566
	 * @return bool True if plan supports feature, false if not.
1567
	 */
1568
	public static function active_plan_supports( $feature ) {
1569
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1570
		return Jetpack_Plan::supports( $feature );
1571
	}
1572
1573
	/**
1574
	 * Is Jetpack in development (offline) mode?
1575
	 */
1576 View Code Duplication
	public static function is_development_mode() {
1577
		$development_mode = false;
1578
1579
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1580
			$development_mode = JETPACK_DEV_DEBUG;
1581
		} elseif ( $site_url = site_url() ) {
1582
			$development_mode = false === strpos( $site_url, '.' );
1583
		}
1584
1585
		/**
1586
		 * Filters Jetpack's development mode.
1587
		 *
1588
		 * @see https://jetpack.com/support/development-mode/
1589
		 *
1590
		 * @since 2.2.1
1591
		 *
1592
		 * @param bool $development_mode Is Jetpack's development mode active.
1593
		 */
1594
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1595
		return $development_mode;
1596
	}
1597
1598
	/**
1599
	 * Whether the site is currently onboarding or not.
1600
	 * A site is considered as being onboarded if it currently has an onboarding token.
1601
	 *
1602
	 * @since 5.8
1603
	 *
1604
	 * @access public
1605
	 * @static
1606
	 *
1607
	 * @return bool True if the site is currently onboarding, false otherwise
1608
	 */
1609
	public static function is_onboarding() {
1610
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1611
	}
1612
1613
	/**
1614
	 * Determines reason for Jetpack development mode.
1615
	 */
1616
	public static function development_mode_trigger_text() {
1617
		if ( ! Jetpack::is_development_mode() ) {
1618
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1619
		}
1620
1621
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1622
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1623
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1624
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1625
		} else {
1626
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1627
		}
1628
1629
		return $notice;
1630
1631
	}
1632
	/**
1633
	* Get Jetpack development mode notice text and notice class.
1634
	*
1635
	* Mirrors the checks made in Jetpack::is_development_mode
1636
	*
1637
	*/
1638
	public static function show_development_mode_notice() {
1639 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1640
			$notice = sprintf(
1641
			/* translators: %s is a URL */
1642
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1643
				'https://jetpack.com/support/development-mode/'
1644
			);
1645
1646
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1647
1648
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1649
		}
1650
1651
		// Throw up a notice if using a development version and as for feedback.
1652
		if ( Jetpack::is_development_version() ) {
1653
			/* translators: %s is a URL */
1654
			$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/' );
1655
1656
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1657
		}
1658
		// Throw up a notice if using staging mode
1659
		if ( Jetpack::is_staging_site() ) {
1660
			/* translators: %s is a URL */
1661
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1662
1663
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1664
		}
1665
	}
1666
1667
	/**
1668
	 * Whether Jetpack's version maps to a public release, or a development version.
1669
	 */
1670
	public static function is_development_version() {
1671
		/**
1672
		 * Allows filtering whether this is a development version of Jetpack.
1673
		 *
1674
		 * This filter is especially useful for tests.
1675
		 *
1676
		 * @since 4.3.0
1677
		 *
1678
		 * @param bool $development_version Is this a develoment version of Jetpack?
1679
		 */
1680
		return (bool) apply_filters(
1681
			'jetpack_development_version',
1682
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1683
		);
1684
	}
1685
1686
	/**
1687
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1688
	 */
1689
	public static function is_user_connected( $user_id = false ) {
1690
		return self::connection()->is_user_connected( $user_id );
1691
	}
1692
1693
	/**
1694
	 * Get the wpcom user data of the current|specified connected user.
1695
	 */
1696
	public static function get_connected_user_data( $user_id = null ) {
1697
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1698
		if ( ! $user_id ) {
1699
			$user_id = get_current_user_id();
1700
		}
1701
1702
		$transient_key = "jetpack_connected_user_data_$user_id";
1703
1704
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1705
			return $cached_user_data;
1706
		}
1707
1708
		$xml = new Jetpack_IXR_Client( array(
1709
			'user_id' => $user_id,
1710
		) );
1711
		$xml->query( 'wpcom.getUser' );
1712
		if ( ! $xml->isError() ) {
1713
			$user_data = $xml->getResponse();
1714
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1715
			return $user_data;
1716
		}
1717
1718
		return false;
1719
	}
1720
1721
	/**
1722
	 * Get the wpcom email of the current|specified connected user.
1723
	 */
1724 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1725
		if ( ! $user_id ) {
1726
			$user_id = get_current_user_id();
1727
		}
1728
1729
		$xml = new Jetpack_IXR_Client( array(
1730
			'user_id' => $user_id,
1731
		) );
1732
		$xml->query( 'wpcom.getUserEmail' );
1733
		if ( ! $xml->isError() ) {
1734
			return $xml->getResponse();
1735
		}
1736
		return false;
1737
	}
1738
1739
	/**
1740
	 * Get the wpcom email of the master user.
1741
	 */
1742
	public static function get_master_user_email() {
1743
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1744
		if ( $master_user_id ) {
1745
			return self::get_connected_user_email( $master_user_id );
1746
		}
1747
		return '';
1748
	}
1749
1750
	/**
1751
	 * Whether the current user is the connection owner.
1752
	 *
1753
	 * @deprecated since 7.7
1754
	 *
1755
	 * @return bool Whether the current user is the connection owner.
1756
	 */
1757
	public function current_user_is_connection_owner() {
1758
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1759
		return self::connection()->is_connection_owner();
1760
	}
1761
1762
	/**
1763
	 * Gets current user IP address.
1764
	 *
1765
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1766
	 *
1767
	 * @return string                  Current user IP address.
1768
	 */
1769
	public static function current_user_ip( $check_all_headers = false ) {
1770
		if ( $check_all_headers ) {
1771
			foreach ( array(
1772
				'HTTP_CF_CONNECTING_IP',
1773
				'HTTP_CLIENT_IP',
1774
				'HTTP_X_FORWARDED_FOR',
1775
				'HTTP_X_FORWARDED',
1776
				'HTTP_X_CLUSTER_CLIENT_IP',
1777
				'HTTP_FORWARDED_FOR',
1778
				'HTTP_FORWARDED',
1779
				'HTTP_VIA',
1780
			) as $key ) {
1781
				if ( ! empty( $_SERVER[ $key ] ) ) {
1782
					return $_SERVER[ $key ];
1783
				}
1784
			}
1785
		}
1786
1787
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1788
	}
1789
1790
	/**
1791
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1792
	 */
1793
	function extra_oembed_providers() {
1794
		// Cloudup: https://dev.cloudup.com/#oembed
1795
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1796
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1797
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1798
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1799
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1800
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1801
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1802
	}
1803
1804
	/**
1805
	 * Synchronize connected user role changes
1806
	 */
1807
	function user_role_change( $user_id ) {
1808
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1809
		Users::user_role_change( $user_id );
1810
	}
1811
1812
	/**
1813
	 * Loads the currently active modules.
1814
	 */
1815
	public static function load_modules() {
1816
		if (
1817
			! self::is_active()
1818
			&& ! self::is_development_mode()
1819
			&& ! self::is_onboarding()
1820
			&& (
1821
				! is_multisite()
1822
				|| ! get_site_option( 'jetpack_protect_active' )
1823
			)
1824
		) {
1825
			return;
1826
		}
1827
1828
		$version = Jetpack_Options::get_option( 'version' );
1829 View Code Duplication
		if ( ! $version ) {
1830
			$version = $old_version = JETPACK__VERSION . ':' . time();
1831
			/** This action is documented in class.jetpack.php */
1832
			do_action( 'updating_jetpack_version', $version, false );
1833
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1834
		}
1835
		list( $version ) = explode( ':', $version );
1836
1837
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1838
1839
		$modules_data = array();
1840
1841
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1842
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1843
			$updated_modules = array();
1844
			foreach ( $modules as $module ) {
1845
				$modules_data[ $module ] = Jetpack::get_module( $module );
1846
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1847
					continue;
1848
				}
1849
1850
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1851
					continue;
1852
				}
1853
1854
				$updated_modules[] = $module;
1855
			}
1856
1857
			$modules = array_diff( $modules, $updated_modules );
1858
		}
1859
1860
		$is_development_mode = Jetpack::is_development_mode();
1861
1862
		foreach ( $modules as $index => $module ) {
1863
			// If we're in dev mode, disable modules requiring a connection
1864
			if ( $is_development_mode ) {
1865
				// Prime the pump if we need to
1866
				if ( empty( $modules_data[ $module ] ) ) {
1867
					$modules_data[ $module ] = Jetpack::get_module( $module );
1868
				}
1869
				// If the module requires a connection, but we're in local mode, don't include it.
1870
				if ( $modules_data[ $module ]['requires_connection'] ) {
1871
					continue;
1872
				}
1873
			}
1874
1875
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1876
				continue;
1877
			}
1878
1879
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1880
				unset( $modules[ $index ] );
1881
				self::update_active_modules( array_values( $modules ) );
1882
				continue;
1883
			}
1884
1885
			/**
1886
			 * Fires when a specific module is loaded.
1887
			 * The dynamic part of the hook, $module, is the module slug.
1888
			 *
1889
			 * @since 1.1.0
1890
			 */
1891
			do_action( 'jetpack_module_loaded_' . $module );
1892
		}
1893
1894
		/**
1895
		 * Fires when all the modules are loaded.
1896
		 *
1897
		 * @since 1.1.0
1898
		 */
1899
		do_action( 'jetpack_modules_loaded' );
1900
1901
		// 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.
1902
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1903
	}
1904
1905
	/**
1906
	 * Check if Jetpack's REST API compat file should be included
1907
	 * @action plugins_loaded
1908
	 * @return null
1909
	 */
1910
	public function check_rest_api_compat() {
1911
		/**
1912
		 * Filters the list of REST API compat files to be included.
1913
		 *
1914
		 * @since 2.2.5
1915
		 *
1916
		 * @param array $args Array of REST API compat files to include.
1917
		 */
1918
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1919
1920
		if ( function_exists( 'bbpress' ) )
1921
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1922
1923
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1924
			require_once $_jetpack_rest_api_compat_include;
1925
	}
1926
1927
	/**
1928
	 * Gets all plugins currently active in values, regardless of whether they're
1929
	 * traditionally activated or network activated.
1930
	 *
1931
	 * @todo Store the result in core's object cache maybe?
1932
	 */
1933
	public static function get_active_plugins() {
1934
		$active_plugins = (array) get_option( 'active_plugins', array() );
1935
1936
		if ( is_multisite() ) {
1937
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1938
			// whereas active_plugins stores them in the values.
1939
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1940
			if ( $network_plugins ) {
1941
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1942
			}
1943
		}
1944
1945
		sort( $active_plugins );
1946
1947
		return array_unique( $active_plugins );
1948
	}
1949
1950
	/**
1951
	 * Gets and parses additional plugin data to send with the heartbeat data
1952
	 *
1953
	 * @since 3.8.1
1954
	 *
1955
	 * @return array Array of plugin data
1956
	 */
1957
	public static function get_parsed_plugin_data() {
1958
		if ( ! function_exists( 'get_plugins' ) ) {
1959
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1960
		}
1961
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1962
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1963
		$active_plugins = Jetpack::get_active_plugins();
1964
1965
		$plugins = array();
1966
		foreach ( $all_plugins as $path => $plugin_data ) {
1967
			$plugins[ $path ] = array(
1968
					'is_active' => in_array( $path, $active_plugins ),
1969
					'file'      => $path,
1970
					'name'      => $plugin_data['Name'],
1971
					'version'   => $plugin_data['Version'],
1972
					'author'    => $plugin_data['Author'],
1973
			);
1974
		}
1975
1976
		return $plugins;
1977
	}
1978
1979
	/**
1980
	 * Gets and parses theme data to send with the heartbeat data
1981
	 *
1982
	 * @since 3.8.1
1983
	 *
1984
	 * @return array Array of theme data
1985
	 */
1986
	public static function get_parsed_theme_data() {
1987
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1988
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1989
1990
		$themes = array();
1991
		foreach ( $all_themes as $slug => $theme_data ) {
1992
			$theme_headers = array();
1993
			foreach ( $header_keys as $header_key ) {
1994
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1995
			}
1996
1997
			$themes[ $slug ] = array(
1998
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1999
					'slug' => $slug,
2000
					'theme_root' => $theme_data->get_theme_root_uri(),
2001
					'parent' => $theme_data->parent(),
2002
					'headers' => $theme_headers
2003
			);
2004
		}
2005
2006
		return $themes;
2007
	}
2008
2009
	/**
2010
	 * Checks whether a specific plugin is active.
2011
	 *
2012
	 * We don't want to store these in a static variable, in case
2013
	 * there are switch_to_blog() calls involved.
2014
	 */
2015
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2016
		return in_array( $plugin, self::get_active_plugins() );
2017
	}
2018
2019
	/**
2020
	 * Check if Jetpack's Open Graph tags should be used.
2021
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2022
	 *
2023
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2024
	 * @action plugins_loaded
2025
	 * @return null
2026
	 */
2027
	public function check_open_graph() {
2028
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2029
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2030
		}
2031
2032
		$active_plugins = self::get_active_plugins();
2033
2034
		if ( ! empty( $active_plugins ) ) {
2035
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2036
				if ( in_array( $plugin, $active_plugins ) ) {
2037
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2038
					break;
2039
				}
2040
			}
2041
		}
2042
2043
		/**
2044
		 * Allow the addition of Open Graph Meta Tags to all pages.
2045
		 *
2046
		 * @since 2.0.3
2047
		 *
2048
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2049
		 */
2050
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2051
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2052
		}
2053
	}
2054
2055
	/**
2056
	 * Check if Jetpack's Twitter tags should be used.
2057
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2058
	 *
2059
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2060
	 * @action plugins_loaded
2061
	 * @return null
2062
	 */
2063
	public function check_twitter_tags() {
2064
2065
		$active_plugins = self::get_active_plugins();
2066
2067
		if ( ! empty( $active_plugins ) ) {
2068
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2069
				if ( in_array( $plugin, $active_plugins ) ) {
2070
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2071
					break;
2072
				}
2073
			}
2074
		}
2075
2076
		/**
2077
		 * Allow Twitter Card Meta tags to be disabled.
2078
		 *
2079
		 * @since 2.6.0
2080
		 *
2081
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2082
		 */
2083
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2084
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2085
		}
2086
	}
2087
2088
	/**
2089
	 * Allows plugins to submit security reports.
2090
 	 *
2091
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2092
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2093
	 * @param array   $args         See definitions above
2094
	 */
2095
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2096
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2097
	}
2098
2099
/* Jetpack Options API */
2100
2101
	public static function get_option_names( $type = 'compact' ) {
2102
		return Jetpack_Options::get_option_names( $type );
2103
	}
2104
2105
	/**
2106
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2107
 	 *
2108
	 * @param string $name    Option name
2109
	 * @param mixed  $default (optional)
2110
	 */
2111
	public static function get_option( $name, $default = false ) {
2112
		return Jetpack_Options::get_option( $name, $default );
2113
	}
2114
2115
	/**
2116
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2117
 	 *
2118
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2119
	 * @param string $name  Option name
2120
	 * @param mixed  $value Option value
2121
	 */
2122
	public static function update_option( $name, $value ) {
2123
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2124
		return Jetpack_Options::update_option( $name, $value );
2125
	}
2126
2127
	/**
2128
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2129
 	 *
2130
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2131
	 * @param array $array array( option name => option value, ... )
2132
	 */
2133
	public static function update_options( $array ) {
2134
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2135
		return Jetpack_Options::update_options( $array );
2136
	}
2137
2138
	/**
2139
	 * Deletes the given option.  May be passed multiple option names as an array.
2140
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2141
	 *
2142
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2143
	 * @param string|array $names
2144
	 */
2145
	public static function delete_option( $names ) {
2146
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2147
		return Jetpack_Options::delete_option( $names );
2148
	}
2149
2150
	/**
2151
	 * Enters a user token into the user_tokens option
2152
	 *
2153
	 * @param int $user_id
2154
	 * @param string $token
2155
	 * return bool
2156
	 */
2157
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2158
		// not designed for concurrent updates
2159
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2160
		if ( ! is_array( $user_tokens ) )
2161
			$user_tokens = array();
2162
		$user_tokens[$user_id] = $token;
2163
		if ( $is_master_user ) {
2164
			$master_user = $user_id;
2165
			$options     = compact( 'user_tokens', 'master_user' );
2166
		} else {
2167
			$options = compact( 'user_tokens' );
2168
		}
2169
		return Jetpack_Options::update_options( $options );
2170
	}
2171
2172
	/**
2173
	 * Returns an array of all PHP files in the specified absolute path.
2174
	 * Equivalent to glob( "$absolute_path/*.php" ).
2175
	 *
2176
	 * @param string $absolute_path The absolute path of the directory to search.
2177
	 * @return array Array of absolute paths to the PHP files.
2178
	 */
2179
	public static function glob_php( $absolute_path ) {
2180
		if ( function_exists( 'glob' ) ) {
2181
			return glob( "$absolute_path/*.php" );
2182
		}
2183
2184
		$absolute_path = untrailingslashit( $absolute_path );
2185
		$files = array();
2186
		if ( ! $dir = @opendir( $absolute_path ) ) {
2187
			return $files;
2188
		}
2189
2190
		while ( false !== $file = readdir( $dir ) ) {
2191
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2192
				continue;
2193
			}
2194
2195
			$file = "$absolute_path/$file";
2196
2197
			if ( ! is_file( $file ) ) {
2198
				continue;
2199
			}
2200
2201
			$files[] = $file;
2202
		}
2203
2204
		closedir( $dir );
2205
2206
		return $files;
2207
	}
2208
2209
	public static function activate_new_modules( $redirect = false ) {
2210
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2211
			return;
2212
		}
2213
2214
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2215 View Code Duplication
		if ( ! $jetpack_old_version ) {
2216
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2217
			/** This action is documented in class.jetpack.php */
2218
			do_action( 'updating_jetpack_version', $version, false );
2219
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2220
		}
2221
2222
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2223
2224
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2225
			return;
2226
		}
2227
2228
		$active_modules     = Jetpack::get_active_modules();
2229
		$reactivate_modules = array();
2230
		foreach ( $active_modules as $active_module ) {
2231
			$module = Jetpack::get_module( $active_module );
2232
			if ( ! isset( $module['changed'] ) ) {
2233
				continue;
2234
			}
2235
2236
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2237
				continue;
2238
			}
2239
2240
			$reactivate_modules[] = $active_module;
2241
			Jetpack::deactivate_module( $active_module );
2242
		}
2243
2244
		$new_version = JETPACK__VERSION . ':' . time();
2245
		/** This action is documented in class.jetpack.php */
2246
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2247
		Jetpack_Options::update_options(
2248
			array(
2249
				'version'     => $new_version,
2250
				'old_version' => $jetpack_old_version,
2251
			)
2252
		);
2253
2254
		Jetpack::state( 'message', 'modules_activated' );
2255
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2256
2257
		if ( $redirect ) {
2258
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2259
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2260
				$page = $_GET['page'];
2261
			}
2262
2263
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2264
			exit;
2265
		}
2266
	}
2267
2268
	/**
2269
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2270
	 * Make sure to tuck away module "library" files in a sub-directory.
2271
	 */
2272
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2273
		static $modules = null;
2274
2275
		if ( ! isset( $modules ) ) {
2276
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2277
			// Use the cache if we're on the front-end and it's available...
2278
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2279
				$modules = $available_modules_option[ JETPACK__VERSION ];
2280
			} else {
2281
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2282
2283
				$modules = array();
2284
2285
				foreach ( $files as $file ) {
2286
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2287
						continue;
2288
					}
2289
2290
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2291
				}
2292
2293
				Jetpack_Options::update_option( 'available_modules', array(
2294
					JETPACK__VERSION => $modules,
2295
				) );
2296
			}
2297
		}
2298
2299
		/**
2300
		 * Filters the array of modules available to be activated.
2301
		 *
2302
		 * @since 2.4.0
2303
		 *
2304
		 * @param array $modules Array of available modules.
2305
		 * @param string $min_version Minimum version number required to use modules.
2306
		 * @param string $max_version Maximum version number required to use modules.
2307
		 */
2308
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2309
2310
		if ( ! $min_version && ! $max_version ) {
2311
			return array_keys( $mods );
2312
		}
2313
2314
		$r = array();
2315
		foreach ( $mods as $slug => $introduced ) {
2316
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2317
				continue;
2318
			}
2319
2320
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2321
				continue;
2322
			}
2323
2324
			$r[] = $slug;
2325
		}
2326
2327
		return $r;
2328
	}
2329
2330
	/**
2331
	 * Default modules loaded on activation.
2332
	 */
2333
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2334
		$return = array();
2335
2336
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2337
			$module_data = Jetpack::get_module( $module );
2338
2339
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2340
				case 'yes' :
2341
					$return[] = $module;
2342
					break;
2343
				case 'public' :
2344
					if ( Jetpack_Options::get_option( 'public' ) ) {
2345
						$return[] = $module;
2346
					}
2347
					break;
2348
				case 'no' :
2349
				default :
2350
					break;
2351
			}
2352
		}
2353
		/**
2354
		 * Filters the array of default modules.
2355
		 *
2356
		 * @since 2.5.0
2357
		 *
2358
		 * @param array $return Array of default modules.
2359
		 * @param string $min_version Minimum version number required to use modules.
2360
		 * @param string $max_version Maximum version number required to use modules.
2361
		 */
2362
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2363
	}
2364
2365
	/**
2366
	 * Checks activated modules during auto-activation to determine
2367
	 * if any of those modules are being deprecated.  If so, close
2368
	 * them out, and add any replacement modules.
2369
	 *
2370
	 * Runs at priority 99 by default.
2371
	 *
2372
	 * This is run late, so that it can still activate a module if
2373
	 * the new module is a replacement for another that the user
2374
	 * currently has active, even if something at the normal priority
2375
	 * would kibosh everything.
2376
	 *
2377
	 * @since 2.6
2378
	 * @uses jetpack_get_default_modules filter
2379
	 * @param array $modules
2380
	 * @return array
2381
	 */
2382
	function handle_deprecated_modules( $modules ) {
2383
		$deprecated_modules = array(
2384
			'debug'            => null,  // Closed out and moved to the debugger library.
2385
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2386
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2387
		);
2388
2389
		// Don't activate SSO if they never completed activating WPCC.
2390
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2391
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2392
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2393
				$deprecated_modules['wpcc'] = null;
2394
			}
2395
		}
2396
2397
		foreach ( $deprecated_modules as $module => $replacement ) {
2398
			if ( Jetpack::is_module_active( $module ) ) {
2399
				self::deactivate_module( $module );
2400
				if ( $replacement ) {
2401
					$modules[] = $replacement;
2402
				}
2403
			}
2404
		}
2405
2406
		return array_unique( $modules );
2407
	}
2408
2409
	/**
2410
	 * Checks activated plugins during auto-activation to determine
2411
	 * if any of those plugins are in the list with a corresponding module
2412
	 * that is not compatible with the plugin. The module will not be allowed
2413
	 * to auto-activate.
2414
	 *
2415
	 * @since 2.6
2416
	 * @uses jetpack_get_default_modules filter
2417
	 * @param array $modules
2418
	 * @return array
2419
	 */
2420
	function filter_default_modules( $modules ) {
2421
2422
		$active_plugins = self::get_active_plugins();
2423
2424
		if ( ! empty( $active_plugins ) ) {
2425
2426
			// For each module we'd like to auto-activate...
2427
			foreach ( $modules as $key => $module ) {
2428
				// If there are potential conflicts for it...
2429
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2430
					// For each potential conflict...
2431
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2432
						// If that conflicting plugin is active...
2433
						if ( in_array( $plugin, $active_plugins ) ) {
2434
							// Remove that item from being auto-activated.
2435
							unset( $modules[ $key ] );
2436
						}
2437
					}
2438
				}
2439
			}
2440
		}
2441
2442
		return $modules;
2443
	}
2444
2445
	/**
2446
	 * Extract a module's slug from its full path.
2447
	 */
2448
	public static function get_module_slug( $file ) {
2449
		return str_replace( '.php', '', basename( $file ) );
2450
	}
2451
2452
	/**
2453
	 * Generate a module's path from its slug.
2454
	 */
2455
	public static function get_module_path( $slug ) {
2456
		/**
2457
		 * Filters the path of a modules.
2458
		 *
2459
		 * @since 7.4.0
2460
		 *
2461
		 * @param array $return The absolute path to a module's root php file
2462
		 * @param string $slug The module slug
2463
		 */
2464
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2465
	}
2466
2467
	/**
2468
	 * Load module data from module file. Headers differ from WordPress
2469
	 * plugin headers to avoid them being identified as standalone
2470
	 * plugins on the WordPress plugins page.
2471
	 */
2472
	public static function get_module( $module ) {
2473
		$headers = array(
2474
			'name'                      => 'Module Name',
2475
			'description'               => 'Module Description',
2476
			'sort'                      => 'Sort Order',
2477
			'recommendation_order'      => 'Recommendation Order',
2478
			'introduced'                => 'First Introduced',
2479
			'changed'                   => 'Major Changes In',
2480
			'deactivate'                => 'Deactivate',
2481
			'free'                      => 'Free',
2482
			'requires_connection'       => 'Requires Connection',
2483
			'auto_activate'             => 'Auto Activate',
2484
			'module_tags'               => 'Module Tags',
2485
			'feature'                   => 'Feature',
2486
			'additional_search_queries' => 'Additional Search Queries',
2487
			'plan_classes'              => 'Plans',
2488
		);
2489
2490
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2491
2492
		$mod = Jetpack::get_file_data( $file, $headers );
2493
		if ( empty( $mod['name'] ) ) {
2494
			return false;
2495
		}
2496
2497
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2498
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2499
		$mod['deactivate']              = empty( $mod['deactivate'] );
2500
		$mod['free']                    = empty( $mod['free'] );
2501
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2502
2503
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2504
			$mod['auto_activate'] = 'No';
2505
		} else {
2506
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2507
		}
2508
2509
		if ( $mod['module_tags'] ) {
2510
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2511
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2512
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2513
		} else {
2514
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2515
		}
2516
2517 View Code Duplication
		if ( $mod['plan_classes'] ) {
2518
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2519
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2520
		} else {
2521
			$mod['plan_classes'] = array( 'free' );
2522
		}
2523
2524 View Code Duplication
		if ( $mod['feature'] ) {
2525
			$mod['feature'] = explode( ',', $mod['feature'] );
2526
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2527
		} else {
2528
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2529
		}
2530
2531
		/**
2532
		 * Filters the feature array on a module.
2533
		 *
2534
		 * This filter allows you to control where each module is filtered: Recommended,
2535
		 * and the default "Other" listing.
2536
		 *
2537
		 * @since 3.5.0
2538
		 *
2539
		 * @param array   $mod['feature'] The areas to feature this module:
2540
		 *     'Recommended' shows on the main Jetpack admin screen.
2541
		 *     'Other' should be the default if no other value is in the array.
2542
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2543
		 * @param array   $mod All the currently assembled module data.
2544
		 */
2545
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2546
2547
		/**
2548
		 * Filter the returned data about a module.
2549
		 *
2550
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2551
		 * so please be careful.
2552
		 *
2553
		 * @since 3.6.0
2554
		 *
2555
		 * @param array   $mod    The details of the requested module.
2556
		 * @param string  $module The slug of the module, e.g. sharedaddy
2557
		 * @param string  $file   The path to the module source file.
2558
		 */
2559
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2560
	}
2561
2562
	/**
2563
	 * Like core's get_file_data implementation, but caches the result.
2564
	 */
2565
	public static function get_file_data( $file, $headers ) {
2566
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2567
		$file_name = basename( $file );
2568
2569
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2570
2571
		$file_data_option = get_transient( $cache_key );
2572
2573
		if ( false === $file_data_option ) {
2574
			$file_data_option = array();
2575
		}
2576
2577
		$key           = md5( $file_name . serialize( $headers ) );
2578
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2579
2580
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2581
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2582
			return $file_data_option[ $key ];
2583
		}
2584
2585
		$data = get_file_data( $file, $headers );
2586
2587
		$file_data_option[ $key ] = $data;
2588
2589
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2590
2591
		return $data;
2592
	}
2593
2594
2595
	/**
2596
	 * Return translated module tag.
2597
	 *
2598
	 * @param string $tag Tag as it appears in each module heading.
2599
	 *
2600
	 * @return mixed
2601
	 */
2602
	public static function translate_module_tag( $tag ) {
2603
		return jetpack_get_module_i18n_tag( $tag );
2604
	}
2605
2606
	/**
2607
	 * Get i18n strings as a JSON-encoded string
2608
	 *
2609
	 * @return string The locale as JSON
2610
	 */
2611
	public static function get_i18n_data_json() {
2612
2613
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2614
		// JSON files with the file they should be included for. This is an md5
2615
		// of '_inc/build/admin.js'.
2616
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2617
2618
		$i18n_json =
2619
				   JETPACK__PLUGIN_DIR
2620
				   . 'languages/json/jetpack-'
2621
				   . get_user_locale()
2622
				   . '-'
2623
				   . $path_md5
2624
				   . '.json';
2625
2626
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2627
			$locale_data = @file_get_contents( $i18n_json );
2628
			if ( $locale_data ) {
2629
				return $locale_data;
2630
			}
2631
		}
2632
2633
		// Return valid empty Jed locale
2634
		return '{ "locale_data": { "messages": { "": {} } } }';
2635
	}
2636
2637
	/**
2638
	 * Add locale data setup to wp-i18n
2639
	 *
2640
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2641
	 *
2642
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2643
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2644
	 *
2645
	 * This method provides a safe way to request the setup multiple times but add the script at
2646
	 * most once.
2647
	 *
2648
	 * @since 6.7.0
2649
	 *
2650
	 * @return void
2651
	 */
2652
	public static function setup_wp_i18n_locale_data() {
2653
		static $script_added = false;
2654
		if ( ! $script_added ) {
2655
			$script_added = true;
2656
			wp_add_inline_script(
2657
				'wp-i18n',
2658
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2659
			);
2660
		}
2661
	}
2662
2663
	/**
2664
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2665
	 *
2666
	 * @since 3.9.2
2667
	 *
2668
	 * @param array $modules
2669
	 *
2670
	 * @return string|void
2671
	 */
2672
	public static function get_translated_modules( $modules ) {
2673
		foreach ( $modules as $index => $module ) {
2674
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2675
			if ( isset( $module['name'] ) ) {
2676
				$modules[ $index ]['name'] = $i18n_module['name'];
2677
			}
2678
			if ( isset( $module['description'] ) ) {
2679
				$modules[ $index ]['description'] = $i18n_module['description'];
2680
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2681
			}
2682
		}
2683
		return $modules;
2684
	}
2685
2686
	/**
2687
	 * Get a list of activated modules as an array of module slugs.
2688
	 */
2689
	public static function get_active_modules() {
2690
		$active = Jetpack_Options::get_option( 'active_modules' );
2691
2692
		if ( ! is_array( $active ) ) {
2693
			$active = array();
2694
		}
2695
2696
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2697
			$active[] = 'vaultpress';
2698
		} else {
2699
			$active = array_diff( $active, array( 'vaultpress' ) );
2700
		}
2701
2702
		//If protect is active on the main site of a multisite, it should be active on all sites.
2703
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2704
			$active[] = 'protect';
2705
		}
2706
2707
		/**
2708
		 * Allow filtering of the active modules.
2709
		 *
2710
		 * Gives theme and plugin developers the power to alter the modules that
2711
		 * are activated on the fly.
2712
		 *
2713
		 * @since 5.8.0
2714
		 *
2715
		 * @param array $active Array of active module slugs.
2716
		 */
2717
		$active = apply_filters( 'jetpack_active_modules', $active );
2718
2719
		return array_unique( $active );
2720
	}
2721
2722
	/**
2723
	 * Check whether or not a Jetpack module is active.
2724
	 *
2725
	 * @param string $module The slug of a Jetpack module.
2726
	 * @return bool
2727
	 *
2728
	 * @static
2729
	 */
2730
	public static function is_module_active( $module ) {
2731
		return in_array( $module, self::get_active_modules() );
2732
	}
2733
2734
	public static function is_module( $module ) {
2735
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2736
	}
2737
2738
	/**
2739
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2740
	 *
2741
	 * @param bool $catch True to start catching, False to stop.
2742
	 *
2743
	 * @static
2744
	 */
2745
	public static function catch_errors( $catch ) {
2746
		static $display_errors, $error_reporting;
2747
2748
		if ( $catch ) {
2749
			$display_errors  = @ini_set( 'display_errors', 1 );
2750
			$error_reporting = @error_reporting( E_ALL );
2751
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2752
		} else {
2753
			@ini_set( 'display_errors', $display_errors );
2754
			@error_reporting( $error_reporting );
2755
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2756
		}
2757
	}
2758
2759
	/**
2760
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2761
	 */
2762
	public static function catch_errors_on_shutdown() {
2763
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2764
	}
2765
2766
	/**
2767
	 * Rewrite any string to make paths easier to read.
2768
	 *
2769
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2770
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2771
	 *
2772
	 * @param $string
2773
	 * @return mixed
2774
	 */
2775
	public static function alias_directories( $string ) {
2776
		// ABSPATH has a trailing slash.
2777
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2778
		// WP_CONTENT_DIR does not have a trailing slash.
2779
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2780
2781
		return $string;
2782
	}
2783
2784
	public static function activate_default_modules(
2785
		$min_version = false,
2786
		$max_version = false,
2787
		$other_modules = array(),
2788
		$redirect = true,
2789
		$send_state_messages = true
2790
	) {
2791
		$jetpack = Jetpack::init();
2792
2793
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2794
		$modules = array_merge( $other_modules, $modules );
2795
2796
		// Look for standalone plugins and disable if active.
2797
2798
		$to_deactivate = array();
2799
		foreach ( $modules as $module ) {
2800
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2801
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2802
			}
2803
		}
2804
2805
		$deactivated = array();
2806
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2807
			list( $probable_file, $probable_title ) = $deactivate_me;
2808
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2809
				$deactivated[] = $module;
2810
			}
2811
		}
2812
2813
		if ( $deactivated && $redirect ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2814
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2815
2816
			$url = add_query_arg(
2817
				array(
2818
					'action'   => 'activate_default_modules',
2819
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2820
				),
2821
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2822
			);
2823
			wp_safe_redirect( $url );
2824
			exit;
2825
		}
2826
2827
		/**
2828
		 * Fires before default modules are activated.
2829
		 *
2830
		 * @since 1.9.0
2831
		 *
2832
		 * @param string $min_version Minimum version number required to use modules.
2833
		 * @param string $max_version Maximum version number required to use modules.
2834
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2835
		 */
2836
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2837
2838
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2839
		if ( $send_state_messages ) {
2840
			Jetpack::restate();
2841
			Jetpack::catch_errors( true );
2842
		}
2843
2844
		$active = Jetpack::get_active_modules();
2845
2846
		foreach ( $modules as $module ) {
2847
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2848
				$active[] = $module;
2849
				self::update_active_modules( $active );
2850
				continue;
2851
			}
2852
2853
			if ( $send_state_messages && in_array( $module, $active ) ) {
2854
				$module_info = Jetpack::get_module( $module );
2855 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2856
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2857
					if ( $active_state = Jetpack::state( $state ) ) {
2858
						$active_state = explode( ',', $active_state );
2859
					} else {
2860
						$active_state = array();
2861
					}
2862
					$active_state[] = $module;
2863
					Jetpack::state( $state, implode( ',', $active_state ) );
2864
				}
2865
				continue;
2866
			}
2867
2868
			$file = Jetpack::get_module_path( $module );
2869
			if ( ! file_exists( $file ) ) {
2870
				continue;
2871
			}
2872
2873
			// we'll override this later if the plugin can be included without fatal error
2874
			if ( $redirect ) {
2875
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2876
			}
2877
2878
			if ( $send_state_messages ) {
2879
				Jetpack::state( 'error', 'module_activation_failed' );
2880
				Jetpack::state( 'module', $module );
2881
			}
2882
2883
			ob_start();
2884
			require_once $file;
2885
2886
			$active[] = $module;
2887
2888 View Code Duplication
			if ( $send_state_messages ) {
2889
2890
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2891
				if ( $active_state = Jetpack::state( $state ) ) {
2892
					$active_state = explode( ',', $active_state );
2893
				} else {
2894
					$active_state = array();
2895
				}
2896
				$active_state[] = $module;
2897
				Jetpack::state( $state, implode( ',', $active_state ) );
2898
			}
2899
2900
			Jetpack::update_active_modules( $active );
2901
2902
			ob_end_clean();
2903
		}
2904
2905
		if ( $send_state_messages ) {
2906
			Jetpack::state( 'error', false );
2907
			Jetpack::state( 'module', false );
2908
		}
2909
2910
		Jetpack::catch_errors( false );
2911
		/**
2912
		 * Fires when default modules are activated.
2913
		 *
2914
		 * @since 1.9.0
2915
		 *
2916
		 * @param string $min_version Minimum version number required to use modules.
2917
		 * @param string $max_version Maximum version number required to use modules.
2918
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2919
		 */
2920
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2921
	}
2922
2923
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2924
		/**
2925
		 * Fires before a module is activated.
2926
		 *
2927
		 * @since 2.6.0
2928
		 *
2929
		 * @param string $module Module slug.
2930
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2931
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2932
		 */
2933
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2934
2935
		$jetpack = Jetpack::init();
2936
2937
		if ( ! strlen( $module ) )
2938
			return false;
2939
2940
		if ( ! Jetpack::is_module( $module ) )
2941
			return false;
2942
2943
		// If it's already active, then don't do it again
2944
		$active = Jetpack::get_active_modules();
2945
		foreach ( $active as $act ) {
2946
			if ( $act == $module )
2947
				return true;
2948
		}
2949
2950
		$module_data = Jetpack::get_module( $module );
2951
2952
		if ( ! Jetpack::is_active() ) {
2953
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2954
				return false;
2955
2956
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2957
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2958
				return false;
2959
		}
2960
2961
		// Check and see if the old plugin is active
2962
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2963
			// Deactivate the old plugin
2964
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2965
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2966
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2967
				Jetpack::state( 'deactivated_plugins', $module );
2968
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2969
				exit;
2970
			}
2971
		}
2972
2973
		// Protect won't work with mis-configured IPs
2974
		if ( 'protect' === $module ) {
2975
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2976
			if ( ! jetpack_protect_get_ip() ) {
2977
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2978
				return false;
2979
			}
2980
		}
2981
2982
		if ( ! Jetpack_Plan::supports( $module ) ) {
2983
			return false;
2984
		}
2985
2986
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2987
		Jetpack::state( 'module', $module );
2988
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2989
2990
		Jetpack::catch_errors( true );
2991
		ob_start();
2992
		require Jetpack::get_module_path( $module );
2993
		/** This action is documented in class.jetpack.php */
2994
		do_action( 'jetpack_activate_module', $module );
2995
		$active[] = $module;
2996
		Jetpack::update_active_modules( $active );
2997
2998
		Jetpack::state( 'error', false ); // the override
2999
		ob_end_clean();
3000
		Jetpack::catch_errors( false );
3001
3002
		if ( $redirect ) {
3003
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3004
		}
3005
		if ( $exit ) {
3006
			exit;
3007
		}
3008
		return true;
3009
	}
3010
3011
	function activate_module_actions( $module ) {
3012
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3013
	}
3014
3015
	public static function deactivate_module( $module ) {
3016
		/**
3017
		 * Fires when a module is deactivated.
3018
		 *
3019
		 * @since 1.9.0
3020
		 *
3021
		 * @param string $module Module slug.
3022
		 */
3023
		do_action( 'jetpack_pre_deactivate_module', $module );
3024
3025
		$jetpack = Jetpack::init();
3026
3027
		$active = Jetpack::get_active_modules();
3028
		$new    = array_filter( array_diff( $active, (array) $module ) );
3029
3030
		return self::update_active_modules( $new );
3031
	}
3032
3033
	public static function enable_module_configurable( $module ) {
3034
		$module = Jetpack::get_module_slug( $module );
3035
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3036
	}
3037
3038
	/**
3039
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3040
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3041
	 *
3042
	 * @param string $module Module slug
3043
	 * @return string $url module configuration URL
3044
	 */
3045
	public static function module_configuration_url( $module ) {
3046
		$module = Jetpack::get_module_slug( $module );
3047
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3048
		/**
3049
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3050
		 *
3051
		 * @since 6.9.0
3052
		 *
3053
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3054
		 */
3055
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3056
3057
		return $url;
3058
	}
3059
3060
/* Installation */
3061
	public static function bail_on_activation( $message, $deactivate = true ) {
3062
?>
3063
<!doctype html>
3064
<html>
3065
<head>
3066
<meta charset="<?php bloginfo( 'charset' ); ?>">
3067
<style>
3068
* {
3069
	text-align: center;
3070
	margin: 0;
3071
	padding: 0;
3072
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3073
}
3074
p {
3075
	margin-top: 1em;
3076
	font-size: 18px;
3077
}
3078
</style>
3079
<body>
3080
<p><?php echo esc_html( $message ); ?></p>
3081
</body>
3082
</html>
3083
<?php
3084
		if ( $deactivate ) {
3085
			$plugins = get_option( 'active_plugins' );
3086
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3087
			$update  = false;
3088
			foreach ( $plugins as $i => $plugin ) {
3089
				if ( $plugin === $jetpack ) {
3090
					$plugins[$i] = false;
3091
					$update = true;
3092
				}
3093
			}
3094
3095
			if ( $update ) {
3096
				update_option( 'active_plugins', array_filter( $plugins ) );
3097
			}
3098
		}
3099
		exit;
3100
	}
3101
3102
	/**
3103
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3104
	 * @static
3105
	 */
3106
	public static function plugin_activation( $network_wide ) {
3107
		Jetpack_Options::update_option( 'activated', 1 );
3108
3109
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3110
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3111
		}
3112
3113
		if ( $network_wide )
3114
			Jetpack::state( 'network_nag', true );
3115
3116
		// For firing one-off events (notices) immediately after activation
3117
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3118
3119
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3120
3121
		Jetpack::plugin_initialize();
3122
	}
3123
3124
	public static function get_activation_source( $referer_url ) {
3125
3126
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3127
			return array( 'wp-cli', null );
3128
		}
3129
3130
		$referer = parse_url( $referer_url );
3131
3132
		$source_type = 'unknown';
3133
		$source_query = null;
3134
3135
		if ( ! is_array( $referer ) ) {
3136
			return array( $source_type, $source_query );
3137
		}
3138
3139
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3140
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3141
3142
		if ( isset( $referer['query'] ) ) {
3143
			parse_str( $referer['query'], $query_parts );
3144
		} else {
3145
			$query_parts = array();
3146
		}
3147
3148
		if ( $plugins_path === $referer['path'] ) {
3149
			$source_type = 'list';
3150
		} elseif ( $plugins_install_path === $referer['path'] ) {
3151
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3152
			switch( $tab ) {
3153
				case 'popular':
3154
					$source_type = 'popular';
3155
					break;
3156
				case 'recommended':
3157
					$source_type = 'recommended';
3158
					break;
3159
				case 'favorites':
3160
					$source_type = 'favorites';
3161
					break;
3162
				case 'search':
3163
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3164
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3165
					break;
3166
				default:
3167
					$source_type = 'featured';
3168
			}
3169
		}
3170
3171
		return array( $source_type, $source_query );
3172
	}
3173
3174
	/**
3175
	 * Runs before bumping version numbers up to a new version
3176
	 * @param  string $version    Version:timestamp
3177
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3178
	 * @return null              [description]
3179
	 */
3180
	public static function do_version_bump( $version, $old_version ) {
3181
		if ( ! $old_version ) { // For new sites
3182
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3183
		}
3184
	}
3185
3186
	/**
3187
	 * Sets the internal version number and activation state.
3188
	 * @static
3189
	 */
3190
	public static function plugin_initialize() {
3191
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3192
			Jetpack_Options::update_option( 'activated', 2 );
3193
		}
3194
3195 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3196
			$version = $old_version = JETPACK__VERSION . ':' . time();
3197
			/** This action is documented in class.jetpack.php */
3198
			do_action( 'updating_jetpack_version', $version, false );
3199
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3200
		}
3201
3202
		Jetpack::load_modules();
3203
3204
		Jetpack_Options::delete_option( 'do_activate' );
3205
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3206
	}
3207
3208
	/**
3209
	 * Removes all connection options
3210
	 * @static
3211
	 */
3212
	public static function plugin_deactivation( ) {
3213
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3214
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3215
			Jetpack_Network::init()->deactivate();
3216
		} else {
3217
			Jetpack::disconnect( false );
3218
			//Jetpack_Heartbeat::init()->deactivate();
3219
		}
3220
	}
3221
3222
	/**
3223
	 * Disconnects from the Jetpack servers.
3224
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3225
	 * @static
3226
	 */
3227
	public static function disconnect( $update_activated_state = true ) {
3228
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3229
		$connection = self::connection();
3230
		$connection->clean_nonces( true );
3231
3232
		// If the site is in an IDC because sync is not allowed,
3233
		// let's make sure to not disconnect the production site.
3234
		if ( ! self::validate_sync_error_idc_option() ) {
3235
			$tracking = new Tracking();
3236
			$tracking->record_user_event( 'disconnect_site', array() );
3237
3238
			$xml = new Jetpack_IXR_Client();
3239
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3240
		}
3241
3242
		Jetpack_Options::delete_option(
3243
			array(
3244
				'blog_token',
3245
				'user_token',
3246
				'user_tokens',
3247
				'master_user',
3248
				'time_diff',
3249
				'fallback_no_verify_ssl_certs',
3250
			)
3251
		);
3252
3253
		Jetpack_IDC::clear_all_idc_options();
3254
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3255
3256
		if ( $update_activated_state ) {
3257
			Jetpack_Options::update_option( 'activated', 4 );
3258
		}
3259
3260
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3261
			// Check then record unique disconnection if site has never been disconnected previously
3262
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3263
				$jetpack_unique_connection['disconnected'] = 1;
3264
			} else {
3265
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3266
					//track unique disconnect
3267
					$jetpack = Jetpack::init();
3268
3269
					$jetpack->stat( 'connections', 'unique-disconnect' );
3270
					$jetpack->do_stats( 'server_side' );
3271
				}
3272
				// increment number of times disconnected
3273
				$jetpack_unique_connection['disconnected'] += 1;
3274
			}
3275
3276
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3277
		}
3278
3279
		// Delete cached connected user data
3280
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3281
		delete_transient( $transient_key );
3282
3283
		// Delete all the sync related data. Since it could be taking up space.
3284
		Sender::get_instance()->uninstall();
3285
3286
		// Disable the Heartbeat cron
3287
		Jetpack_Heartbeat::init()->deactivate();
3288
	}
3289
3290
	/**
3291
	 * Unlinks the current user from the linked WordPress.com user.
3292
	 *
3293
	 * @deprecated since 7.7
3294
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3295
	 *
3296
	 * @param Integer $user_id the user identifier.
3297
	 * @return Boolean Whether the disconnection of the user was successful.
3298
	 */
3299
	public static function unlink_user( $user_id = null ) {
3300
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3301
		return Connection_Manager::disconnect_user( $user_id );
3302
	}
3303
3304
	/**
3305
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3306
	 */
3307
	public static function try_registration() {
3308
		// The user has agreed to the TOS at some point by now.
3309
		Jetpack_Options::update_option( 'tos_agreed', true );
3310
3311
		// Let's get some testing in beta versions and such.
3312
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3313
			// Before attempting to connect, let's make sure that the domains are viable.
3314
			$domains_to_check = array_unique( array(
3315
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3316
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3317
			) );
3318
			foreach ( $domains_to_check as $domain ) {
3319
				$result = self::connection()->is_usable_domain( $domain );
3320
				if ( is_wp_error( $result ) ) {
3321
					return $result;
3322
				}
3323
			}
3324
		}
3325
3326
		$result = Jetpack::register();
3327
3328
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3329
		if ( ! $result || is_wp_error( $result ) ) {
3330
			return $result;
3331
		} else {
3332
			return true;
3333
		}
3334
	}
3335
3336
	/**
3337
	 * Tracking an internal event log. Try not to put too much chaff in here.
3338
	 *
3339
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3340
	 */
3341
	public static function log( $code, $data = null ) {
3342
		// only grab the latest 200 entries
3343
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3344
3345
		// Append our event to the log
3346
		$log_entry = array(
3347
			'time'    => time(),
3348
			'user_id' => get_current_user_id(),
3349
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3350
			'code'    => $code,
3351
		);
3352
		// Don't bother storing it unless we've got some.
3353
		if ( ! is_null( $data ) ) {
3354
			$log_entry['data'] = $data;
3355
		}
3356
		$log[] = $log_entry;
3357
3358
		// Try add_option first, to make sure it's not autoloaded.
3359
		// @todo: Add an add_option method to Jetpack_Options
3360
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3361
			Jetpack_Options::update_option( 'log', $log );
3362
		}
3363
3364
		/**
3365
		 * Fires when Jetpack logs an internal event.
3366
		 *
3367
		 * @since 3.0.0
3368
		 *
3369
		 * @param array $log_entry {
3370
		 *	Array of details about the log entry.
3371
		 *
3372
		 *	@param string time Time of the event.
3373
		 *	@param int user_id ID of the user who trigerred the event.
3374
		 *	@param int blog_id Jetpack Blog ID.
3375
		 *	@param string code Unique name for the event.
3376
		 *	@param string data Data about the event.
3377
		 * }
3378
		 */
3379
		do_action( 'jetpack_log_entry', $log_entry );
3380
	}
3381
3382
	/**
3383
	 * Get the internal event log.
3384
	 *
3385
	 * @param $event (string) - only return the specific log events
3386
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3387
	 *
3388
	 * @return array of log events || WP_Error for invalid params
3389
	 */
3390
	public static function get_log( $event = false, $num = false ) {
3391
		if ( $event && ! is_string( $event ) ) {
3392
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3393
		}
3394
3395
		if ( $num && ! is_numeric( $num ) ) {
3396
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3397
		}
3398
3399
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3400
3401
		// If nothing set - act as it did before, otherwise let's start customizing the output
3402
		if ( ! $num && ! $event ) {
3403
			return $entire_log;
3404
		} else {
3405
			$entire_log = array_reverse( $entire_log );
3406
		}
3407
3408
		$custom_log_output = array();
3409
3410
		if ( $event ) {
3411
			foreach ( $entire_log as $log_event ) {
3412
				if ( $event == $log_event[ 'code' ] ) {
3413
					$custom_log_output[] = $log_event;
3414
				}
3415
			}
3416
		} else {
3417
			$custom_log_output = $entire_log;
3418
		}
3419
3420
		if ( $num ) {
3421
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3422
		}
3423
3424
		return $custom_log_output;
3425
	}
3426
3427
	/**
3428
	 * Log modification of important settings.
3429
	 */
3430
	public static function log_settings_change( $option, $old_value, $value ) {
3431
		switch( $option ) {
3432
			case 'jetpack_sync_non_public_post_stati':
3433
				self::log( $option, $value );
3434
				break;
3435
		}
3436
	}
3437
3438
	/**
3439
	 * Return stat data for WPCOM sync
3440
	 */
3441
	public static function get_stat_data( $encode = true, $extended = true ) {
3442
		$data = Jetpack_Heartbeat::generate_stats_array();
3443
3444
		if ( $extended ) {
3445
			$additional_data = self::get_additional_stat_data();
3446
			$data = array_merge( $data, $additional_data );
3447
		}
3448
3449
		if ( $encode ) {
3450
			return json_encode( $data );
3451
		}
3452
3453
		return $data;
3454
	}
3455
3456
	/**
3457
	 * Get additional stat data to sync to WPCOM
3458
	 */
3459
	public static function get_additional_stat_data( $prefix = '' ) {
3460
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3461
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3462
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3463
		$return["{$prefix}site-count"]     = 0;
3464
3465
		if ( function_exists( 'get_blog_count' ) ) {
3466
			$return["{$prefix}site-count"] = get_blog_count();
3467
		}
3468
		return $return;
3469
	}
3470
3471
	private static function get_site_user_count() {
3472
		global $wpdb;
3473
3474
		if ( function_exists( 'wp_is_large_network' ) ) {
3475
			if ( wp_is_large_network( 'users' ) ) {
3476
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3477
			}
3478
		}
3479
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3480
			// It wasn't there, so regenerate the data and save the transient
3481
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3482
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3483
		}
3484
		return $user_count;
3485
	}
3486
3487
	/* Admin Pages */
3488
3489
	function admin_init() {
3490
		// If the plugin is not connected, display a connect message.
3491
		if (
3492
			// the plugin was auto-activated and needs its candy
3493
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3494
		||
3495
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3496
			! Jetpack_Options::get_option( 'activated' )
3497
		) {
3498
			Jetpack::plugin_initialize();
3499
		}
3500
3501
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3502
			Jetpack_Connection_Banner::init();
3503
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3504
			// Upgrade: 1.1 -> 1.1.1
3505
			// Check and see if host can verify the Jetpack servers' SSL certificate
3506
			$args = array();
3507
			$connection = self::connection();
3508
			Client::_wp_remote_request(
3509
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3510
				$args,
3511
				true
3512
			);
3513
		}
3514
3515
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3516
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3517
		}
3518
3519
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3520
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3521
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3522
3523
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3524
			// Artificially throw errors in certain whitelisted cases during plugin activation
3525
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3526
		}
3527
3528
		// Add custom column in wp-admin/users.php to show whether user is linked.
3529
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3530
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3531
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3532
	}
3533
3534
	function admin_body_class( $admin_body_class = '' ) {
3535
		$classes = explode( ' ', trim( $admin_body_class ) );
3536
3537
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3538
3539
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3540
		return " $admin_body_class ";
3541
	}
3542
3543
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3544
		return $admin_body_class . ' jetpack-pagestyles ';
3545
	}
3546
3547
	/**
3548
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3549
	 * This function artificially throws errors for such cases (whitelisted).
3550
	 *
3551
	 * @param string $plugin The activated plugin.
3552
	 */
3553
	function throw_error_on_activate_plugin( $plugin ) {
3554
		$active_modules = Jetpack::get_active_modules();
3555
3556
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3557
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3558
			$throw = false;
3559
3560
			// Try and make sure it really was the stats plugin
3561
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3562
				if ( 'stats.php' == basename( $plugin ) ) {
3563
					$throw = true;
3564
				}
3565
			} else {
3566
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3567
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3568
					$throw = true;
3569
				}
3570
			}
3571
3572
			if ( $throw ) {
3573
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3574
			}
3575
		}
3576
	}
3577
3578
	function intercept_plugin_error_scrape_init() {
3579
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3580
	}
3581
3582
	function intercept_plugin_error_scrape( $action, $result ) {
3583
		if ( ! $result ) {
3584
			return;
3585
		}
3586
3587
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3588
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3589
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3590
			}
3591
		}
3592
	}
3593
3594
	function add_remote_request_handlers() {
3595
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3596
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3597
	}
3598
3599
	function remote_request_handlers() {
3600
		$action = current_filter();
3601
3602
		switch ( current_filter() ) {
3603
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3604
			$response = $this->upload_handler();
3605
			break;
3606
3607
		case 'wp_ajax_nopriv_jetpack_update_file' :
3608
			$response = $this->upload_handler( true );
3609
			break;
3610
		default :
3611
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3612
			break;
3613
		}
3614
3615
		if ( ! $response ) {
3616
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3617
		}
3618
3619
		if ( is_wp_error( $response ) ) {
3620
			$status_code       = $response->get_error_data();
3621
			$error             = $response->get_error_code();
3622
			$error_description = $response->get_error_message();
3623
3624
			if ( ! is_int( $status_code ) ) {
3625
				$status_code = 400;
3626
			}
3627
3628
			status_header( $status_code );
3629
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3630
		}
3631
3632
		status_header( 200 );
3633
		if ( true === $response ) {
3634
			exit;
3635
		}
3636
3637
		die( json_encode( (object) $response ) );
3638
	}
3639
3640
	/**
3641
	 * Uploads a file gotten from the global $_FILES.
3642
	 * If `$update_media_item` is true and `post_id` is defined
3643
	 * the attachment file of the media item (gotten through of the post_id)
3644
	 * will be updated instead of add a new one.
3645
	 *
3646
	 * @param  boolean $update_media_item - update media attachment
3647
	 * @return array - An array describing the uploadind files process
3648
	 */
3649
	function upload_handler( $update_media_item = false ) {
3650
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3651
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3652
		}
3653
3654
		$user = wp_authenticate( '', '' );
3655
		if ( ! $user || is_wp_error( $user ) ) {
3656
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3657
		}
3658
3659
		wp_set_current_user( $user->ID );
3660
3661
		if ( ! current_user_can( 'upload_files' ) ) {
3662
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3663
		}
3664
3665
		if ( empty( $_FILES ) ) {
3666
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3667
		}
3668
3669
		foreach ( array_keys( $_FILES ) as $files_key ) {
3670
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3671
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3672
			}
3673
		}
3674
3675
		$media_keys = array_keys( $_FILES['media'] );
3676
3677
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3678
		if ( ! $token || is_wp_error( $token ) ) {
3679
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3680
		}
3681
3682
		$uploaded_files = array();
3683
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3684
		unset( $GLOBALS['post'] );
3685
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3686
			$file = array();
3687
			foreach ( $media_keys as $media_key ) {
3688
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3689
			}
3690
3691
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3692
3693
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3694
			if ( $hmac_provided !== $hmac_file ) {
3695
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3696
				continue;
3697
			}
3698
3699
			$_FILES['.jetpack.upload.'] = $file;
3700
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3701
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3702
				$post_id = 0;
3703
			}
3704
3705
			if ( $update_media_item ) {
3706
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3707
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3708
				}
3709
3710
				$media_array = $_FILES['media'];
3711
3712
				$file_array['name'] = $media_array['name'][0];
3713
				$file_array['type'] = $media_array['type'][0];
3714
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3715
				$file_array['error'] = $media_array['error'][0];
3716
				$file_array['size'] = $media_array['size'][0];
3717
3718
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3719
3720
				if ( is_wp_error( $edited_media_item ) ) {
3721
					return $edited_media_item;
3722
				}
3723
3724
				$response = (object) array(
3725
					'id'   => (string) $post_id,
3726
					'file' => (string) $edited_media_item->post_title,
3727
					'url'  => (string) wp_get_attachment_url( $post_id ),
3728
					'type' => (string) $edited_media_item->post_mime_type,
3729
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3730
				);
3731
3732
				return (array) array( $response );
3733
			}
3734
3735
			$attachment_id = media_handle_upload(
3736
				'.jetpack.upload.',
3737
				$post_id,
3738
				array(),
3739
				array(
3740
					'action' => 'jetpack_upload_file',
3741
				)
3742
			);
3743
3744
			if ( ! $attachment_id ) {
3745
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3746
			} elseif ( is_wp_error( $attachment_id ) ) {
3747
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3748
			} else {
3749
				$attachment = get_post( $attachment_id );
3750
				$uploaded_files[$index] = (object) array(
3751
					'id'   => (string) $attachment_id,
3752
					'file' => $attachment->post_title,
3753
					'url'  => wp_get_attachment_url( $attachment_id ),
3754
					'type' => $attachment->post_mime_type,
3755
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3756
				);
3757
				// Zip files uploads are not supported unless they are done for installation purposed
3758
				// lets delete them in case something goes wrong in this whole process
3759
				if ( 'application/zip' === $attachment->post_mime_type ) {
3760
					// Schedule a cleanup for 2 hours from now in case of failed install.
3761
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3762
				}
3763
			}
3764
		}
3765
		if ( ! is_null( $global_post ) ) {
3766
			$GLOBALS['post'] = $global_post;
3767
		}
3768
3769
		return $uploaded_files;
3770
	}
3771
3772
	/**
3773
	 * Add help to the Jetpack page
3774
	 *
3775
	 * @since Jetpack (1.2.3)
3776
	 * @return false if not the Jetpack page
3777
	 */
3778
	function admin_help() {
3779
		$current_screen = get_current_screen();
3780
3781
		// Overview
3782
		$current_screen->add_help_tab(
3783
			array(
3784
				'id'		=> 'home',
3785
				'title'		=> __( 'Home', 'jetpack' ),
3786
				'content'	=>
3787
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3788
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3789
					'<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>',
3790
			)
3791
		);
3792
3793
		// Screen Content
3794
		if ( current_user_can( 'manage_options' ) ) {
3795
			$current_screen->add_help_tab(
3796
				array(
3797
					'id'		=> 'settings',
3798
					'title'		=> __( 'Settings', 'jetpack' ),
3799
					'content'	=>
3800
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3801
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3802
						'<ol>' .
3803
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3804
							'<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>' .
3805
						'</ol>' .
3806
						'<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>'
3807
				)
3808
			);
3809
		}
3810
3811
		// Help Sidebar
3812
		$current_screen->set_help_sidebar(
3813
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3814
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3815
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3816
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3817
		);
3818
	}
3819
3820
	function admin_menu_css() {
3821
		wp_enqueue_style( 'jetpack-icons' );
3822
	}
3823
3824
	function admin_menu_order() {
3825
		return true;
3826
	}
3827
3828 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3829
		$jp_menu_order = array();
3830
3831
		foreach ( $menu_order as $index => $item ) {
3832
			if ( $item != 'jetpack' ) {
3833
				$jp_menu_order[] = $item;
3834
			}
3835
3836
			if ( $index == 0 ) {
3837
				$jp_menu_order[] = 'jetpack';
3838
			}
3839
		}
3840
3841
		return $jp_menu_order;
3842
	}
3843
3844
	function admin_banner_styles() {
3845
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3846
3847
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3848
			wp_register_style(
3849
				'jetpack-dops-style',
3850
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3851
				array(),
3852
				JETPACK__VERSION
3853
			);
3854
		}
3855
3856
		wp_enqueue_style(
3857
			'jetpack',
3858
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3859
			array( 'jetpack-dops-style' ),
3860
			 JETPACK__VERSION . '-20121016'
3861
		);
3862
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3863
		wp_style_add_data( 'jetpack', 'suffix', $min );
3864
	}
3865
3866
	function plugin_action_links( $actions ) {
3867
3868
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3869
3870
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3871
			return array_merge(
3872
				$jetpack_home,
3873
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3874
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3875
				$actions
3876
				);
3877
			}
3878
3879
		return array_merge( $jetpack_home, $actions );
3880
	}
3881
3882
	/*
3883
	 * Registration flow:
3884
	 * 1 - ::admin_page_load() action=register
3885
	 * 2 - ::try_registration()
3886
	 * 3 - ::register()
3887
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3888
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3889
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3890
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3891
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3892
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3893
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3894
	 *       jetpack_id, jetpack_secret, jetpack_public
3895
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3896
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3897
	 * 5 - user logs in with WP.com account
3898
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3899
	 *		- Jetpack_Client_Server::authorize()
3900
	 *		- Jetpack_Client_Server::get_token()
3901
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3902
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3903
	 *			- which responds with access_token, token_type, scope
3904
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3905
	 *		- Jetpack::activate_default_modules()
3906
	 *     		- Deactivates deprecated plugins
3907
	 *     		- Activates all default modules
3908
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3909
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3910
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3911
	 *     Done!
3912
	 */
3913
3914
	/**
3915
	 * Handles the page load events for the Jetpack admin page
3916
	 */
3917
	function admin_page_load() {
3918
		$error = false;
3919
3920
		// Make sure we have the right body class to hook stylings for subpages off of.
3921
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3922
3923
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3924
			// Should only be used in intermediate redirects to preserve state across redirects
3925
			Jetpack::restate();
3926
		}
3927
3928
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3929
			// @todo: Add validation against a known whitelist
3930
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3931
			// User clicked in the iframe to link their accounts
3932
			if ( ! Jetpack::is_user_connected() ) {
3933
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3934
3935
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3936
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3937
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3938
3939
				if ( isset( $_GET['notes_iframe'] ) )
3940
					$connect_url .= '&notes_iframe';
3941
				wp_redirect( $connect_url );
3942
				exit;
3943
			} else {
3944
				if ( ! isset( $_GET['calypso_env'] ) ) {
3945
					Jetpack::state( 'message', 'already_authorized' );
3946
					wp_safe_redirect( Jetpack::admin_url() );
3947
					exit;
3948
				} else {
3949
					$connect_url = $this->build_connect_url( true, false, $from );
3950
					$connect_url .= '&already_authorized=true';
3951
					wp_redirect( $connect_url );
3952
					exit;
3953
				}
3954
			}
3955
		}
3956
3957
3958
		if ( isset( $_GET['action'] ) ) {
3959
			switch ( $_GET['action'] ) {
3960
			case 'authorize':
3961
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3962
					Jetpack::state( 'message', 'already_authorized' );
3963
					wp_safe_redirect( Jetpack::admin_url() );
3964
					exit;
3965
				}
3966
				Jetpack::log( 'authorize' );
3967
				$client_server = new Jetpack_Client_Server;
3968
				$client_server->client_authorize();
3969
				exit;
3970
			case 'register' :
3971
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3972
					$error = 'cheatin';
3973
					break;
3974
				}
3975
				check_admin_referer( 'jetpack-register' );
3976
				Jetpack::log( 'register' );
3977
				Jetpack::maybe_set_version_option();
3978
				$registered = Jetpack::try_registration();
3979
				if ( is_wp_error( $registered ) ) {
3980
					$error = $registered->get_error_code();
3981
					Jetpack::state( 'error', $error );
3982
					Jetpack::state( 'error', $registered->get_error_message() );
3983
3984
					/**
3985
					 * Jetpack registration Error.
3986
					 *
3987
					 * @since 7.5.0
3988
					 *
3989
					 * @param string|int $error The error code.
3990
					 * @param \WP_Error $registered The error object.
3991
					 */
3992
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3993
					break;
3994
				}
3995
3996
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3997
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3998
3999
				/**
4000
				 * Jetpack registration Success.
4001
				 *
4002
				 * @since 7.5.0
4003
				 *
4004
				 * @param string $from 'from' GET parameter;
4005
				 */
4006
				do_action( 'jetpack_connection_register_success', $from );
4007
4008
				$url = $this->build_connect_url( true, $redirect, $from );
4009
4010
				if ( ! empty( $_GET['onboarding'] ) ) {
4011
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4012
				}
4013
4014
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4015
					$url = add_query_arg( 'auth_approved', 'true', $url );
4016
				}
4017
4018
				wp_redirect( $url );
4019
				exit;
4020
			case 'activate' :
4021
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4022
					$error = 'cheatin';
4023
					break;
4024
				}
4025
4026
				$module = stripslashes( $_GET['module'] );
4027
				check_admin_referer( "jetpack_activate-$module" );
4028
				Jetpack::log( 'activate', $module );
4029
				if ( ! Jetpack::activate_module( $module ) ) {
4030
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4031
				}
4032
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4033
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4034
				exit;
4035
			case 'activate_default_modules' :
4036
				check_admin_referer( 'activate_default_modules' );
4037
				Jetpack::log( 'activate_default_modules' );
4038
				Jetpack::restate();
4039
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4040
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4041
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4042
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4043
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4044
				exit;
4045
			case 'disconnect' :
4046
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4047
					$error = 'cheatin';
4048
					break;
4049
				}
4050
4051
				check_admin_referer( 'jetpack-disconnect' );
4052
				Jetpack::log( 'disconnect' );
4053
				Jetpack::disconnect();
4054
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4055
				exit;
4056
			case 'reconnect' :
4057
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4058
					$error = 'cheatin';
4059
					break;
4060
				}
4061
4062
				check_admin_referer( 'jetpack-reconnect' );
4063
				Jetpack::log( 'reconnect' );
4064
				$this->disconnect();
4065
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4066
				exit;
4067 View Code Duplication
			case 'deactivate' :
4068
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4069
					$error = 'cheatin';
4070
					break;
4071
				}
4072
4073
				$modules = stripslashes( $_GET['module'] );
4074
				check_admin_referer( "jetpack_deactivate-$modules" );
4075
				foreach ( explode( ',', $modules ) as $module ) {
4076
					Jetpack::log( 'deactivate', $module );
4077
					Jetpack::deactivate_module( $module );
4078
					Jetpack::state( 'message', 'module_deactivated' );
4079
				}
4080
				Jetpack::state( 'module', $modules );
4081
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4082
				exit;
4083
			case 'unlink' :
4084
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4085
				check_admin_referer( 'jetpack-unlink' );
4086
				Jetpack::log( 'unlink' );
4087
				Connection_Manager::disconnect_user();
4088
				Jetpack::state( 'message', 'unlinked' );
4089
				if ( 'sub-unlink' == $redirect ) {
4090
					wp_safe_redirect( admin_url() );
4091
				} else {
4092
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4093
				}
4094
				exit;
4095
			case 'onboard' :
4096
				if ( ! current_user_can( 'manage_options' ) ) {
4097
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4098
				} else {
4099
					Jetpack::create_onboarding_token();
4100
					$url = $this->build_connect_url( true );
4101
4102
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4103
						$url = add_query_arg( 'onboarding', $token, $url );
4104
					}
4105
4106
					$calypso_env = $this->get_calypso_env();
4107
					if ( ! empty( $calypso_env ) ) {
4108
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4109
					}
4110
4111
					wp_redirect( $url );
4112
					exit;
4113
				}
4114
				exit;
4115
			default:
4116
				/**
4117
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4118
				 *
4119
				 * @since 2.6.0
4120
				 *
4121
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4122
				 */
4123
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4124
			}
4125
		}
4126
4127
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4128
			self::activate_new_modules( true );
4129
		}
4130
4131
		$message_code = Jetpack::state( 'message' );
4132
		if ( Jetpack::state( 'optin-manage' ) ) {
4133
			$activated_manage = $message_code;
4134
			$message_code = 'jetpack-manage';
4135
		}
4136
4137
		switch ( $message_code ) {
4138
		case 'jetpack-manage':
4139
			$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>';
4140
			if ( $activated_manage ) {
4141
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4142
			}
4143
			break;
4144
4145
		}
4146
4147
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4148
4149
		if ( ! empty( $deactivated_plugins ) ) {
4150
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4151
			$deactivated_titles  = array();
4152
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4153
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4154
					continue;
4155
				}
4156
4157
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4158
			}
4159
4160
			if ( $deactivated_titles ) {
4161
				if ( $this->message ) {
4162
					$this->message .= "<br /><br />\n";
4163
				}
4164
4165
				$this->message .= wp_sprintf(
4166
					_n(
4167
						'Jetpack contains the most recent version of the old %l plugin.',
4168
						'Jetpack contains the most recent versions of the old %l plugins.',
4169
						count( $deactivated_titles ),
4170
						'jetpack'
4171
					),
4172
					$deactivated_titles
4173
				);
4174
4175
				$this->message .= "<br />\n";
4176
4177
				$this->message .= _n(
4178
					'The old version has been deactivated and can be removed from your site.',
4179
					'The old versions have been deactivated and can be removed from your site.',
4180
					count( $deactivated_titles ),
4181
					'jetpack'
4182
				);
4183
			}
4184
		}
4185
4186
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4187
4188
		if ( $this->message || $this->error || $this->privacy_checks ) {
4189
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4190
		}
4191
4192
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4193
	}
4194
4195
	function admin_notices() {
4196
4197
		if ( $this->error ) {
4198
?>
4199
<div id="message" class="jetpack-message jetpack-err">
4200
	<div class="squeezer">
4201
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4202
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4203
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4204
<?php	endif; ?>
4205
	</div>
4206
</div>
4207
<?php
4208
		}
4209
4210
		if ( $this->message ) {
4211
?>
4212
<div id="message" class="jetpack-message">
4213
	<div class="squeezer">
4214
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4215
	</div>
4216
</div>
4217
<?php
4218
		}
4219
4220
		if ( $this->privacy_checks ) :
4221
			$module_names = $module_slugs = array();
4222
4223
			$privacy_checks = explode( ',', $this->privacy_checks );
4224
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4225
			foreach ( $privacy_checks as $module_slug ) {
4226
				$module = Jetpack::get_module( $module_slug );
4227
				if ( ! $module ) {
4228
					continue;
4229
				}
4230
4231
				$module_slugs[] = $module_slug;
4232
				$module_names[] = "<strong>{$module['name']}</strong>";
4233
			}
4234
4235
			$module_slugs = join( ',', $module_slugs );
4236
?>
4237
<div id="message" class="jetpack-message jetpack-err">
4238
	<div class="squeezer">
4239
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4240
		<p><?php
4241
			echo wp_kses(
4242
				wptexturize(
4243
					wp_sprintf(
4244
						_nx(
4245
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4246
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4247
							count( $privacy_checks ),
4248
							'%l = list of Jetpack module/feature names',
4249
							'jetpack'
4250
						),
4251
						$module_names
4252
					)
4253
				),
4254
				array( 'strong' => true )
4255
			);
4256
4257
			echo "\n<br />\n";
4258
4259
			echo wp_kses(
4260
				sprintf(
4261
					_nx(
4262
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4263
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4264
						count( $privacy_checks ),
4265
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4266
						'jetpack'
4267
					),
4268
					wp_nonce_url(
4269
						Jetpack::admin_url(
4270
							array(
4271
								'page'   => 'jetpack',
4272
								'action' => 'deactivate',
4273
								'module' => urlencode( $module_slugs ),
4274
							)
4275
						),
4276
						"jetpack_deactivate-$module_slugs"
4277
					),
4278
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4279
				),
4280
				array( 'a' => array( 'href' => true, 'title' => true ) )
4281
			);
4282
		?></p>
4283
	</div>
4284
</div>
4285
<?php endif;
4286
	}
4287
4288
	/**
4289
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4290
	 */
4291
	function stat( $group, $detail ) {
4292
		if ( ! isset( $this->stats[ $group ] ) )
4293
			$this->stats[ $group ] = array();
4294
		$this->stats[ $group ][] = $detail;
4295
	}
4296
4297
	/**
4298
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4299
	 */
4300
	function do_stats( $method = '' ) {
4301
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4302
			foreach ( $this->stats as $group => $stats ) {
4303
				if ( is_array( $stats ) && count( $stats ) ) {
4304
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4305
					if ( 'server_side' === $method ) {
4306
						self::do_server_side_stat( $args );
4307
					} else {
4308
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4309
					}
4310
				}
4311
				unset( $this->stats[ $group ] );
4312
			}
4313
		}
4314
	}
4315
4316
	/**
4317
	 * Runs stats code for a one-off, server-side.
4318
	 *
4319
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4320
	 *
4321
	 * @return bool If it worked.
4322
	 */
4323
	static function do_server_side_stat( $args ) {
4324
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4325
		if ( is_wp_error( $response ) )
4326
			return false;
4327
4328
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4329
			return false;
4330
4331
		return true;
4332
	}
4333
4334
	/**
4335
	 * Builds the stats url.
4336
	 *
4337
	 * @param $args array|string The arguments to append to the URL.
4338
	 *
4339
	 * @return string The URL to be pinged.
4340
	 */
4341
	static function build_stats_url( $args ) {
4342
		$defaults = array(
4343
			'v'    => 'wpcom2',
4344
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4345
		);
4346
		$args     = wp_parse_args( $args, $defaults );
4347
		/**
4348
		 * Filter the URL used as the Stats tracking pixel.
4349
		 *
4350
		 * @since 2.3.2
4351
		 *
4352
		 * @param string $url Base URL used as the Stats tracking pixel.
4353
		 */
4354
		$base_url = apply_filters(
4355
			'jetpack_stats_base_url',
4356
			'https://pixel.wp.com/g.gif'
4357
		);
4358
		$url      = add_query_arg( $args, $base_url );
4359
		return $url;
4360
	}
4361
4362
	/**
4363
	 * Get the role of the current user.
4364
	 *
4365
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4366
	 *
4367
	 * @access public
4368
	 * @static
4369
	 *
4370
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4371
	 */
4372
	public static function translate_current_user_to_role() {
4373
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4374
4375
		$roles = new Roles();
4376
		return $roles->translate_current_user_to_role();
4377
	}
4378
4379
	/**
4380
	 * Get the role of a particular user.
4381
	 *
4382
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4383
	 *
4384
	 * @access public
4385
	 * @static
4386
	 *
4387
	 * @param \WP_User $user User object.
4388
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4389
	 */
4390
	public static function translate_user_to_role( $user ) {
4391
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4392
4393
		$roles = new Roles();
4394
		return $roles->translate_user_to_role( $user );
4395
	}
4396
4397
	/**
4398
	 * Get the minimum capability for a role.
4399
	 *
4400
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4401
	 *
4402
	 * @access public
4403
	 * @static
4404
	 *
4405
	 * @param string $role Role name.
4406
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4407
	 */
4408
	public static function translate_role_to_cap( $role ) {
4409
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4410
4411
		$roles = new Roles();
4412
		return $roles->translate_role_to_cap( $role );
4413
	}
4414
4415
	static function sign_role( $role, $user_id = null ) {
4416
		if ( empty( $user_id ) ) {
4417
			$user_id = (int) get_current_user_id();
4418
		}
4419
4420
		if ( ! $user_id  ) {
4421
			return false;
4422
		}
4423
4424
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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