Completed
Push — master ( 2d9109...ca302c )
by Marin
08:24
created

class.jetpack.php (1 issue)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * 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
		if ( Jetpack::is_active() ) {
614
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
615
616
			Jetpack_Heartbeat::init();
617
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
618
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
619
				Jetpack_Search_Performance_Logger::init();
620
			}
621
		}
622
623
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
624
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
625
626
		add_action( 'admin_init', array( $this, 'admin_init' ) );
627
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
628
629
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
630
631
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
632
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
633
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
634
635
		// returns HTTPS support status
636
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
637
638
		// JITM AJAX callback function
639
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
640
641
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
642
643
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
644
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
645
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
646
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
647
648
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
649
650
		/**
651
		 * These actions run checks to load additional files.
652
		 * They check for external files or plugins, so they need to run as late as possible.
653
		 */
654
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
655
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
656
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
657
658
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
659
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
660
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
661
662
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
663
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
664
665
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
666
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
667
668
		// A filter to control all just in time messages
669
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
670
671
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
672
673
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
674
		// We should make sure to only do this for front end links.
675
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
676
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
677
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
678
679
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
680
			//so they point moderation links on emails to Calypso
681
			jetpack_require_lib( 'functions.wp-notify' );
682
		}
683
684
		// Hide edit post link if mobile app.
685
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
686
			add_filter( 'edit_post_link', '__return_empty_string' );
687
		}
688
689
		// Update the Jetpack plan from API on heartbeats
690
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
691
692
		/**
693
		 * This is the hack to concatenate all css files into one.
694
		 * For description and reasoning see the implode_frontend_css method
695
		 *
696
		 * Super late priority so we catch all the registered styles
697
		 */
698
		if( !is_admin() ) {
699
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
700
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
701
		}
702
703
704
		/**
705
		 * These are sync actions that we need to keep track of for jitms
706
		 */
707
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
708
709
		// Actually push the stats on shutdown.
710
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
711
			add_action( 'shutdown', array( $this, 'push_stats' ) );
712
		}
713
714
		/*
715
		 * Load some scripts asynchronously.
716
		 */
717
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
718
	}
719
720
	/**
721
	 * Sets up the XMLRPC request handlers.
722
	 *
723
	 * @todo Deprecate this method in favor of Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers().
724
	 *
725
	 * @param Array                 $request_params Incoming request parameters.
726
	 * @param Boolean               $is_active      Whether the connection is currently active.
727
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
728
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
729
	 */
730
	public function setup_xmlrpc_handlers(
731
		$request_params,
732
		$is_active,
733
		$is_signed,
734
		Jetpack_XMLRPC_Server $xmlrpc_server = null
735
	) {
736
		return $this->connection_manager->setup_xmlrpc_handlers(
737
			$request_params,
738
			$is_active,
739
			$is_signed,
740
			$xmlrpc_server
741
		);
742
	}
743
744
	/**
745
	 * Initialize REST API registration connector.
746
	 *
747
	 * @deprecated since 7.7.0
748
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
749
	 */
750
	public function initialize_rest_api_registration_connector() {
751
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
752
		$this->connection_manager->initialize_rest_api_registration_connector();
753
	}
754
755
	/**
756
	 * This is ported over from the manage module, which has been deprecated and baked in here.
757
	 *
758
	 * @param $domains
759
	 */
760
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
761
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
762
	}
763
764
	/**
765
	 * Return $domains, with 'wordpress.com' appended.
766
	 * This is ported over from the manage module, which has been deprecated and baked in here.
767
	 *
768
	 * @param $domains
769
	 * @return array
770
	 */
771
	function allow_wpcom_domain( $domains ) {
772
		if ( empty( $domains ) ) {
773
			$domains = array();
774
		}
775
		$domains[] = 'wordpress.com';
776
		return array_unique( $domains );
777
	}
778
779
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
780
		$post = get_post( $post_id );
781
782
		if ( empty( $post ) ) {
783
			return $default_url;
784
		}
785
786
		$post_type = $post->post_type;
787
788
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
789
		// https://en.support.wordpress.com/custom-post-types/
790
		$allowed_post_types = array(
791
			'post' => 'post',
792
			'page' => 'page',
793
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
794
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
795
		);
796
797
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
798
			return $default_url;
799
		}
800
801
		$path_prefix = $allowed_post_types[ $post_type ];
802
803
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
804
805
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
806
	}
807
808
	function point_edit_comment_links_to_calypso( $url ) {
809
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
810
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
811
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
812
			Jetpack::build_raw_urls( get_home_url() ),
813
			$query_args['amp;c']
814
		) );
815
	}
816
817
	function jetpack_track_last_sync_callback( $params ) {
818
		/**
819
		 * Filter to turn off jitm caching
820
		 *
821
		 * @since 5.4.0
822
		 *
823
		 * @param bool false Whether to cache just in time messages
824
		 */
825
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
826
			return $params;
827
		}
828
829
		if ( is_array( $params ) && isset( $params[0] ) ) {
830
			$option = $params[0];
831
			if ( 'active_plugins' === $option ) {
832
				// use the cache if we can, but not terribly important if it gets evicted
833
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
834
			}
835
		}
836
837
		return $params;
838
	}
839
840
	function jetpack_connection_banner_callback() {
841
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
842
843
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
844
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
845
			wp_send_json_success();
846
		}
847
848
		wp_die();
849
	}
850
851
	/**
852
	 * Removes all XML-RPC methods that are not `jetpack.*`.
853
	 * Only used in our alternate XML-RPC endpoint, where we want to
854
	 * ensure that Core and other plugins' methods are not exposed.
855
	 *
856
	 * @deprecated since 7.7.0
857
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
858
	 *
859
	 * @param array $methods A list of registered WordPress XMLRPC methods.
860
	 * @return array Filtered $methods
861
	 */
862
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
863
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
864
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
865
	}
866
867
	/**
868
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
869
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
870
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
871
	 * which is accessible via a different URI. Most of the below is copied directly
872
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
873
	 *
874
	 * @deprecated since 7.7.0
875
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
876
	 */
877
	public function alternate_xmlrpc() {
878
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
879
		$this->connection_manager->alternate_xmlrpc();
880
	}
881
882
	/**
883
	 * The callback for the JITM ajax requests.
884
	 */
885
	function jetpack_jitm_ajax_callback() {
886
		// Check for nonce
887
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
888
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
889
		}
890
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
891
			$module_slug = $_REQUEST['jitmModule'];
892
			Jetpack::log( 'activate', $module_slug );
893
			Jetpack::activate_module( $module_slug, false, false );
894
			Jetpack::state( 'message', 'no_message' );
895
896
			//A Jetpack module is being activated through a JITM, track it
897
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
898
			$this->do_stats( 'server_side' );
899
900
			wp_send_json_success();
901
		}
902
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
903
			// get the hide_jitm options array
904
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
905
			$module_slug = $_REQUEST['jitmModule'];
906
907
			if( ! $jetpack_hide_jitm ) {
908
				$jetpack_hide_jitm = array(
909
					$module_slug => 'hide'
910
				);
911
			} else {
912
				$jetpack_hide_jitm[$module_slug] = 'hide';
913
			}
914
915
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
916
917
			//jitm is being dismissed forever, track it
918
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
919
			$this->do_stats( 'server_side' );
920
921
			wp_send_json_success();
922
		}
923 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
924
			$module_slug = $_REQUEST['jitmModule'];
925
926
			// User went to WordPress.com, track this
927
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
928
			$this->do_stats( 'server_side' );
929
930
			wp_send_json_success();
931
		}
932 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
933
			$track = $_REQUEST['jitmModule'];
934
935
			// User is viewing JITM, track it.
936
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
937
			$this->do_stats( 'server_side' );
938
939
			wp_send_json_success();
940
		}
941
	}
942
943
	/**
944
	 * If there are any stats that need to be pushed, but haven't been, push them now.
945
	 */
946
	function push_stats() {
947
		if ( ! empty( $this->stats ) ) {
948
			$this->do_stats( 'server_side' );
949
		}
950
	}
951
952
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
953
		switch( $cap ) {
954
			case 'jetpack_connect' :
955
			case 'jetpack_reconnect' :
956
				if ( Jetpack::is_development_mode() ) {
957
					$caps = array( 'do_not_allow' );
958
					break;
959
				}
960
				/**
961
				 * Pass through. If it's not development mode, these should match disconnect.
962
				 * Let users disconnect if it's development mode, just in case things glitch.
963
				 */
964
			case 'jetpack_disconnect' :
965
				/**
966
				 * In multisite, can individual site admins manage their own connection?
967
				 *
968
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
969
				 */
970
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
971
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
972
						/**
973
						 * We need to update the option name -- it's terribly unclear which
974
						 * direction the override goes.
975
						 *
976
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
977
						 */
978
						$caps = array( 'do_not_allow' );
979
						break;
980
					}
981
				}
982
983
				$caps = array( 'manage_options' );
984
				break;
985
			case 'jetpack_manage_modules' :
986
			case 'jetpack_activate_modules' :
987
			case 'jetpack_deactivate_modules' :
988
				$caps = array( 'manage_options' );
989
				break;
990
			case 'jetpack_configure_modules' :
991
				$caps = array( 'manage_options' );
992
				break;
993
			case 'jetpack_manage_autoupdates' :
994
				$caps = array(
995
					'manage_options',
996
					'update_plugins',
997
				);
998
				break;
999
			case 'jetpack_network_admin_page':
1000
			case 'jetpack_network_settings_page':
1001
				$caps = array( 'manage_network_plugins' );
1002
				break;
1003
			case 'jetpack_network_sites_page':
1004
				$caps = array( 'manage_sites' );
1005
				break;
1006
			case 'jetpack_admin_page' :
1007
				if ( Jetpack::is_development_mode() ) {
1008
					$caps = array( 'manage_options' );
1009
					break;
1010
				} else {
1011
					$caps = array( 'read' );
1012
				}
1013
				break;
1014
			case 'jetpack_connect_user' :
1015
				if ( Jetpack::is_development_mode() ) {
1016
					$caps = array( 'do_not_allow' );
1017
					break;
1018
				}
1019
				$caps = array( 'read' );
1020
				break;
1021
		}
1022
		return $caps;
1023
	}
1024
1025
	/**
1026
	 * Require a Jetpack authentication.
1027
	 *
1028
	 * @deprecated since 7.7.0
1029
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1030
	 */
1031
	public function require_jetpack_authentication() {
1032
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1033
		$this->connection_manager->require_jetpack_authentication();
1034
	}
1035
1036
	/**
1037
	 * Load language files
1038
	 * @action plugins_loaded
1039
	 */
1040
	public static function plugin_textdomain() {
1041
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1042
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1043
	}
1044
1045
	/**
1046
	 * Register assets for use in various modules and the Jetpack admin page.
1047
	 *
1048
	 * @uses wp_script_is, wp_register_script, plugins_url
1049
	 * @action wp_loaded
1050
	 * @return null
1051
	 */
1052
	public function register_assets() {
1053
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1054
			wp_register_script(
1055
				'spin',
1056
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1057
				false,
1058
				'1.3'
1059
			);
1060
		}
1061
1062 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1063
			wp_register_script(
1064
				'jquery.spin',
1065
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1066
				array( 'jquery', 'spin' ),
1067
				'1.3'
1068
			);
1069
		}
1070
1071 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1072
			wp_register_script(
1073
				'jetpack-gallery-settings',
1074
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1075
				array( 'media-views' ),
1076
				'20121225'
1077
			);
1078
		}
1079
1080 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1081
			wp_register_script(
1082
				'jetpack-twitter-timeline',
1083
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1084
				array( 'jquery' ),
1085
				'4.0.0',
1086
				true
1087
			);
1088
		}
1089
1090
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1091
			wp_register_script(
1092
				'jetpack-facebook-embed',
1093
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1094
				array( 'jquery' ),
1095
				null,
1096
				true
1097
			);
1098
1099
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1100
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1101
			if ( ! is_numeric( $fb_app_id ) ) {
1102
				$fb_app_id = '';
1103
			}
1104
			wp_localize_script(
1105
				'jetpack-facebook-embed',
1106
				'jpfbembed',
1107
				array(
1108
					'appid' => $fb_app_id,
1109
					'locale' => $this->get_locale(),
1110
				)
1111
			);
1112
		}
1113
1114
		/**
1115
		 * As jetpack_register_genericons is by default fired off a hook,
1116
		 * the hook may have already fired by this point.
1117
		 * So, let's just trigger it manually.
1118
		 */
1119
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1120
		jetpack_register_genericons();
1121
1122
		/**
1123
		 * Register the social logos
1124
		 */
1125
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1126
		jetpack_register_social_logos();
1127
1128 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1129
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1130
	}
1131
1132
	/**
1133
	 * Guess locale from language code.
1134
	 *
1135
	 * @param string $lang Language code.
1136
	 * @return string|bool
1137
	 */
1138 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1139
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1140
			return 'en_US';
1141
		}
1142
1143
		if ( ! class_exists( 'GP_Locales' ) ) {
1144
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1145
				return false;
1146
			}
1147
1148
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1149
		}
1150
1151
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1152
			// WP.com: get_locale() returns 'it'
1153
			$locale = GP_Locales::by_slug( $lang );
1154
		} else {
1155
			// Jetpack: get_locale() returns 'it_IT';
1156
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1157
		}
1158
1159
		if ( ! $locale ) {
1160
			return false;
1161
		}
1162
1163
		if ( empty( $locale->facebook_locale ) ) {
1164
			if ( empty( $locale->wp_locale ) ) {
1165
				return false;
1166
			} else {
1167
				// Facebook SDK is smart enough to fall back to en_US if a
1168
				// locale isn't supported. Since supported Facebook locales
1169
				// can fall out of sync, we'll attempt to use the known
1170
				// wp_locale value and rely on said fallback.
1171
				return $locale->wp_locale;
1172
			}
1173
		}
1174
1175
		return $locale->facebook_locale;
1176
	}
1177
1178
	/**
1179
	 * Get the locale.
1180
	 *
1181
	 * @return string|bool
1182
	 */
1183
	function get_locale() {
1184
		$locale = $this->guess_locale_from_lang( get_locale() );
1185
1186
		if ( ! $locale ) {
1187
			$locale = 'en_US';
1188
		}
1189
1190
		return $locale;
1191
	}
1192
1193
	/**
1194
	 * Device Pixels support
1195
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1196
	 */
1197
	function devicepx() {
1198
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1199
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1200
		}
1201
	}
1202
1203
	/**
1204
	 * Return the network_site_url so that .com knows what network this site is a part of.
1205
	 * @param  bool $option
1206
	 * @return string
1207
	 */
1208
	public function jetpack_main_network_site_option( $option ) {
1209
		return network_site_url();
1210
	}
1211
	/**
1212
	 * Network Name.
1213
	 */
1214
	static function network_name( $option = null ) {
1215
		global $current_site;
1216
		return $current_site->site_name;
1217
	}
1218
	/**
1219
	 * Does the network allow new user and site registrations.
1220
	 * @return string
1221
	 */
1222
	static function network_allow_new_registrations( $option = null ) {
1223
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1224
	}
1225
	/**
1226
	 * Does the network allow admins to add new users.
1227
	 * @return boolian
1228
	 */
1229
	static function network_add_new_users( $option = null ) {
1230
		return (bool) get_site_option( 'add_new_users' );
1231
	}
1232
	/**
1233
	 * File upload psace left per site in MB.
1234
	 *  -1 means NO LIMIT.
1235
	 * @return number
1236
	 */
1237
	static function network_site_upload_space( $option = null ) {
1238
		// value in MB
1239
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1240
	}
1241
1242
	/**
1243
	 * Network allowed file types.
1244
	 * @return string
1245
	 */
1246
	static function network_upload_file_types( $option = null ) {
1247
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1248
	}
1249
1250
	/**
1251
	 * Maximum file upload size set by the network.
1252
	 * @return number
1253
	 */
1254
	static function network_max_upload_file_size( $option = null ) {
1255
		// value in KB
1256
		return get_site_option( 'fileupload_maxk', 300 );
1257
	}
1258
1259
	/**
1260
	 * Lets us know if a site allows admins to manage the network.
1261
	 * @return array
1262
	 */
1263
	static function network_enable_administration_menus( $option = null ) {
1264
		return get_site_option( 'menu_items' );
1265
	}
1266
1267
	/**
1268
	 * If a user has been promoted to or demoted from admin, we need to clear the
1269
	 * jetpack_other_linked_admins transient.
1270
	 *
1271
	 * @since 4.3.2
1272
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1273
	 *
1274
	 * @param int    $user_id   The user ID whose role changed.
1275
	 * @param string $role      The new role.
1276
	 * @param array  $old_roles An array of the user's previous roles.
1277
	 */
1278
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1279
		if ( 'administrator' == $role
1280
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1281
			|| is_null( $old_roles )
1282
		) {
1283
			delete_transient( 'jetpack_other_linked_admins' );
1284
		}
1285
	}
1286
1287
	/**
1288
	 * Checks to see if there are any other users available to become primary
1289
	 * Users must both:
1290
	 * - Be linked to wpcom
1291
	 * - Be an admin
1292
	 *
1293
	 * @return mixed False if no other users are linked, Int if there are.
1294
	 */
1295
	static function get_other_linked_admins() {
1296
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1297
1298
		if ( false === $other_linked_users ) {
1299
			$admins = get_users( array( 'role' => 'administrator' ) );
1300
			if ( count( $admins ) > 1 ) {
1301
				$available = array();
1302
				foreach ( $admins as $admin ) {
1303
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1304
						$available[] = $admin->ID;
1305
					}
1306
				}
1307
1308
				$count_connected_admins = count( $available );
1309
				if ( count( $available ) > 1 ) {
1310
					$other_linked_users = $count_connected_admins;
1311
				} else {
1312
					$other_linked_users = 0;
1313
				}
1314
			} else {
1315
				$other_linked_users = 0;
1316
			}
1317
1318
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1319
		}
1320
1321
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1322
	}
1323
1324
	/**
1325
	 * Return whether we are dealing with a multi network setup or not.
1326
	 * The reason we are type casting this is because we want to avoid the situation where
1327
	 * the result is false since when is_main_network_option return false it cases
1328
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1329
	 * database which could be set to anything as opposed to what this function returns.
1330
	 * @param  bool  $option
1331
	 *
1332
	 * @return boolean
1333
	 */
1334
	public function is_main_network_option( $option ) {
1335
		// return '1' or ''
1336
		return (string) (bool) Jetpack::is_multi_network();
1337
	}
1338
1339
	/**
1340
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1341
	 *
1342
	 * @param  string  $option
1343
	 * @return boolean
1344
	 */
1345
	public function is_multisite( $option ) {
1346
		return (string) (bool) is_multisite();
1347
	}
1348
1349
	/**
1350
	 * Implemented since there is no core is multi network function
1351
	 * Right now there is no way to tell if we which network is the dominant network on the system
1352
	 *
1353
	 * @since  3.3
1354
	 * @return boolean
1355
	 */
1356 View Code Duplication
	public static function is_multi_network() {
1357
		global  $wpdb;
1358
1359
		// if we don't have a multi site setup no need to do any more
1360
		if ( ! is_multisite() ) {
1361
			return false;
1362
		}
1363
1364
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1365
		if ( $num_sites > 1 ) {
1366
			return true;
1367
		} else {
1368
			return false;
1369
		}
1370
	}
1371
1372
	/**
1373
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1374
	 * @return null
1375
	 */
1376
	function update_jetpack_main_network_site_option() {
1377
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1378
	}
1379
	/**
1380
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1381
	 *
1382
	 */
1383
	function update_jetpack_network_settings() {
1384
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1385
		// Only sync this info for the main network site.
1386
	}
1387
1388
	/**
1389
	 * Get back if the current site is single user site.
1390
	 *
1391
	 * @return bool
1392
	 */
1393 View Code Duplication
	public static function is_single_user_site() {
1394
		global $wpdb;
1395
1396
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1397
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1398
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1399
		}
1400
		return 1 === (int) $some_users;
1401
	}
1402
1403
	/**
1404
	 * Returns true if the site has file write access false otherwise.
1405
	 * @return string ( '1' | '0' )
1406
	 **/
1407
	public static function file_system_write_access() {
1408
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1409
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1410
		}
1411
1412
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1413
1414
		$filesystem_method = get_filesystem_method();
1415
		if ( $filesystem_method === 'direct' ) {
1416
			return 1;
1417
		}
1418
1419
		ob_start();
1420
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1421
		ob_end_clean();
1422
		if ( $filesystem_credentials_are_stored ) {
1423
			return 1;
1424
		}
1425
		return 0;
1426
	}
1427
1428
	/**
1429
	 * Finds out if a site is using a version control system.
1430
	 * @return string ( '1' | '0' )
1431
	 **/
1432
	public static function is_version_controlled() {
1433
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1434
		return (string) (int) Functions::is_version_controlled();
1435
	}
1436
1437
	/**
1438
	 * Determines whether the current theme supports featured images or not.
1439
	 * @return string ( '1' | '0' )
1440
	 */
1441
	public static function featured_images_enabled() {
1442
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1443
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1444
	}
1445
1446
	/**
1447
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1448
	 *
1449
	 * @deprecated 4.7 use get_avatar_url instead.
1450
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1451
	 * @param int $size Size of the avatar image
1452
	 * @param string $default URL to a default image to use if no avatar is available
1453
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1454
	 *
1455
	 * @return array
1456
	 */
1457
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1458
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1459
		return get_avatar_url( $id_or_email, array(
1460
			'size' => $size,
1461
			'default' => $default,
1462
			'force_default' => $force_display,
1463
		) );
1464
	}
1465
1466
	/**
1467
	 * jetpack_updates is saved in the following schema:
1468
	 *
1469
	 * array (
1470
	 *      'plugins'                       => (int) Number of plugin updates available.
1471
	 *      'themes'                        => (int) Number of theme updates available.
1472
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1473
	 *      'translations'                  => (int) Number of translation updates available.
1474
	 *      'total'                         => (int) Total of all available updates.
1475
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1476
	 * )
1477
	 * @return array
1478
	 */
1479
	public static function get_updates() {
1480
		$update_data = wp_get_update_data();
1481
1482
		// Stores the individual update counts as well as the total count.
1483
		if ( isset( $update_data['counts'] ) ) {
1484
			$updates = $update_data['counts'];
1485
		}
1486
1487
		// If we need to update WordPress core, let's find the latest version number.
1488 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1489
			$cur = get_preferred_from_update_core();
1490
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1491
				$updates['wp_update_version'] = $cur->current;
1492
			}
1493
		}
1494
		return isset( $updates ) ? $updates : array();
1495
	}
1496
1497
	public static function get_update_details() {
1498
		$update_details = array(
1499
			'update_core' => get_site_transient( 'update_core' ),
1500
			'update_plugins' => get_site_transient( 'update_plugins' ),
1501
			'update_themes' => get_site_transient( 'update_themes' ),
1502
		);
1503
		return $update_details;
1504
	}
1505
1506
	public static function refresh_update_data() {
1507
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1508
1509
	}
1510
1511
	public static function refresh_theme_data() {
1512
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1513
	}
1514
1515
	/**
1516
	 * Is Jetpack active?
1517
	 */
1518
	public static function is_active() {
1519
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1520
	}
1521
1522
	/**
1523
	 * Make an API call to WordPress.com for plan status
1524
	 *
1525
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1526
	 *
1527
	 * @return bool True if plan is updated, false if no update
1528
	 */
1529
	public static function refresh_active_plan_from_wpcom() {
1530
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1531
		return Jetpack_Plan::refresh_from_wpcom();
1532
	}
1533
1534
	/**
1535
	 * Get the plan that this Jetpack site is currently using
1536
	 *
1537
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1538
	 * @return array Active Jetpack plan details.
1539
	 */
1540
	public static function get_active_plan() {
1541
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1542
		return Jetpack_Plan::get();
1543
	}
1544
1545
	/**
1546
	 * Determine whether the active plan supports a particular feature
1547
	 *
1548
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1549
	 * @return bool True if plan supports feature, false if not.
1550
	 */
1551
	public static function active_plan_supports( $feature ) {
1552
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1553
		return Jetpack_Plan::supports( $feature );
1554
	}
1555
1556
	/**
1557
	 * Is Jetpack in development (offline) mode?
1558
	 */
1559 View Code Duplication
	public static function is_development_mode() {
1560
		$development_mode = false;
1561
1562
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1563
			$development_mode = JETPACK_DEV_DEBUG;
1564
		} elseif ( $site_url = site_url() ) {
1565
			$development_mode = false === strpos( $site_url, '.' );
1566
		}
1567
1568
		/**
1569
		 * Filters Jetpack's development mode.
1570
		 *
1571
		 * @see https://jetpack.com/support/development-mode/
1572
		 *
1573
		 * @since 2.2.1
1574
		 *
1575
		 * @param bool $development_mode Is Jetpack's development mode active.
1576
		 */
1577
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1578
		return $development_mode;
1579
	}
1580
1581
	/**
1582
	 * Whether the site is currently onboarding or not.
1583
	 * A site is considered as being onboarded if it currently has an onboarding token.
1584
	 *
1585
	 * @since 5.8
1586
	 *
1587
	 * @access public
1588
	 * @static
1589
	 *
1590
	 * @return bool True if the site is currently onboarding, false otherwise
1591
	 */
1592
	public static function is_onboarding() {
1593
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1594
	}
1595
1596
	/**
1597
	 * Determines reason for Jetpack development mode.
1598
	 */
1599
	public static function development_mode_trigger_text() {
1600
		if ( ! Jetpack::is_development_mode() ) {
1601
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1602
		}
1603
1604
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1605
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1606
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1607
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1608
		} else {
1609
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1610
		}
1611
1612
		return $notice;
1613
1614
	}
1615
	/**
1616
	* Get Jetpack development mode notice text and notice class.
1617
	*
1618
	* Mirrors the checks made in Jetpack::is_development_mode
1619
	*
1620
	*/
1621
	public static function show_development_mode_notice() {
1622 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1623
			$notice = sprintf(
1624
			/* translators: %s is a URL */
1625
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1626
				'https://jetpack.com/support/development-mode/'
1627
			);
1628
1629
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1630
1631
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1632
		}
1633
1634
		// Throw up a notice if using a development version and as for feedback.
1635
		if ( Jetpack::is_development_version() ) {
1636
			/* translators: %s is a URL */
1637
			$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/' );
1638
1639
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1640
		}
1641
		// Throw up a notice if using staging mode
1642
		if ( Jetpack::is_staging_site() ) {
1643
			/* translators: %s is a URL */
1644
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1645
1646
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1647
		}
1648
	}
1649
1650
	/**
1651
	 * Whether Jetpack's version maps to a public release, or a development version.
1652
	 */
1653
	public static function is_development_version() {
1654
		/**
1655
		 * Allows filtering whether this is a development version of Jetpack.
1656
		 *
1657
		 * This filter is especially useful for tests.
1658
		 *
1659
		 * @since 4.3.0
1660
		 *
1661
		 * @param bool $development_version Is this a develoment version of Jetpack?
1662
		 */
1663
		return (bool) apply_filters(
1664
			'jetpack_development_version',
1665
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1666
		);
1667
	}
1668
1669
	/**
1670
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1671
	 */
1672
	public static function is_user_connected( $user_id = false ) {
1673
		return self::connection()->is_user_connected( $user_id );
1674
	}
1675
1676
	/**
1677
	 * Get the wpcom user data of the current|specified connected user.
1678
	 */
1679 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1680
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1681
		if ( ! $user_id ) {
1682
			$user_id = get_current_user_id();
1683
		}
1684
1685
		$transient_key = "jetpack_connected_user_data_$user_id";
1686
1687
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1688
			return $cached_user_data;
1689
		}
1690
1691
		Jetpack::load_xml_rpc_client();
1692
		$xml = new Jetpack_IXR_Client( array(
1693
			'user_id' => $user_id,
1694
		) );
1695
		$xml->query( 'wpcom.getUser' );
1696
		if ( ! $xml->isError() ) {
1697
			$user_data = $xml->getResponse();
1698
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1699
			return $user_data;
1700
		}
1701
1702
		return false;
1703
	}
1704
1705
	/**
1706
	 * Get the wpcom email of the current|specified connected user.
1707
	 */
1708 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1709
		if ( ! $user_id ) {
1710
			$user_id = get_current_user_id();
1711
		}
1712
		Jetpack::load_xml_rpc_client();
1713
		$xml = new Jetpack_IXR_Client( array(
1714
			'user_id' => $user_id,
1715
		) );
1716
		$xml->query( 'wpcom.getUserEmail' );
1717
		if ( ! $xml->isError() ) {
1718
			return $xml->getResponse();
1719
		}
1720
		return false;
1721
	}
1722
1723
	/**
1724
	 * Get the wpcom email of the master user.
1725
	 */
1726
	public static function get_master_user_email() {
1727
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1728
		if ( $master_user_id ) {
1729
			return self::get_connected_user_email( $master_user_id );
1730
		}
1731
		return '';
1732
	}
1733
1734
	/**
1735
	 * Whether the current user is the connection owner.
1736
	 *
1737
	 * @deprecated since 7.7
1738
	 *
1739
	 * @return bool Whether the current user is the connection owner.
1740
	 */
1741
	public function current_user_is_connection_owner() {
1742
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1743
		return self::connection()->is_connection_owner();
1744
	}
1745
1746
	/**
1747
	 * Gets current user IP address.
1748
	 *
1749
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1750
	 *
1751
	 * @return string                  Current user IP address.
1752
	 */
1753
	public static function current_user_ip( $check_all_headers = false ) {
1754
		if ( $check_all_headers ) {
1755
			foreach ( array(
1756
				'HTTP_CF_CONNECTING_IP',
1757
				'HTTP_CLIENT_IP',
1758
				'HTTP_X_FORWARDED_FOR',
1759
				'HTTP_X_FORWARDED',
1760
				'HTTP_X_CLUSTER_CLIENT_IP',
1761
				'HTTP_FORWARDED_FOR',
1762
				'HTTP_FORWARDED',
1763
				'HTTP_VIA',
1764
			) as $key ) {
1765
				if ( ! empty( $_SERVER[ $key ] ) ) {
1766
					return $_SERVER[ $key ];
1767
				}
1768
			}
1769
		}
1770
1771
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1772
	}
1773
1774
	/**
1775
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1776
	 */
1777
	function extra_oembed_providers() {
1778
		// Cloudup: https://dev.cloudup.com/#oembed
1779
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1780
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1781
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1782
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1783
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1784
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1785
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1786
	}
1787
1788
	/**
1789
	 * Synchronize connected user role changes
1790
	 */
1791
	function user_role_change( $user_id ) {
1792
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1793
		Users::user_role_change( $user_id );
1794
	}
1795
1796
	/**
1797
	 * Loads the currently active modules.
1798
	 */
1799
	public static function load_modules() {
1800
		if (
1801
			! self::is_active()
1802
			&& ! self::is_development_mode()
1803
			&& ! self::is_onboarding()
1804
			&& (
1805
				! is_multisite()
1806
				|| ! get_site_option( 'jetpack_protect_active' )
1807
			)
1808
		) {
1809
			return;
1810
		}
1811
1812
		$version = Jetpack_Options::get_option( 'version' );
1813 View Code Duplication
		if ( ! $version ) {
1814
			$version = $old_version = JETPACK__VERSION . ':' . time();
1815
			/** This action is documented in class.jetpack.php */
1816
			do_action( 'updating_jetpack_version', $version, false );
1817
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1818
		}
1819
		list( $version ) = explode( ':', $version );
1820
1821
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1822
1823
		$modules_data = array();
1824
1825
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1826
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1827
			$updated_modules = array();
1828
			foreach ( $modules as $module ) {
1829
				$modules_data[ $module ] = Jetpack::get_module( $module );
1830
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1831
					continue;
1832
				}
1833
1834
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1835
					continue;
1836
				}
1837
1838
				$updated_modules[] = $module;
1839
			}
1840
1841
			$modules = array_diff( $modules, $updated_modules );
1842
		}
1843
1844
		$is_development_mode = Jetpack::is_development_mode();
1845
1846
		foreach ( $modules as $index => $module ) {
1847
			// If we're in dev mode, disable modules requiring a connection
1848
			if ( $is_development_mode ) {
1849
				// Prime the pump if we need to
1850
				if ( empty( $modules_data[ $module ] ) ) {
1851
					$modules_data[ $module ] = Jetpack::get_module( $module );
1852
				}
1853
				// If the module requires a connection, but we're in local mode, don't include it.
1854
				if ( $modules_data[ $module ]['requires_connection'] ) {
1855
					continue;
1856
				}
1857
			}
1858
1859
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1860
				continue;
1861
			}
1862
1863
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1864
				unset( $modules[ $index ] );
1865
				self::update_active_modules( array_values( $modules ) );
1866
				continue;
1867
			}
1868
1869
			/**
1870
			 * Fires when a specific module is loaded.
1871
			 * The dynamic part of the hook, $module, is the module slug.
1872
			 *
1873
			 * @since 1.1.0
1874
			 */
1875
			do_action( 'jetpack_module_loaded_' . $module );
1876
		}
1877
1878
		/**
1879
		 * Fires when all the modules are loaded.
1880
		 *
1881
		 * @since 1.1.0
1882
		 */
1883
		do_action( 'jetpack_modules_loaded' );
1884
1885
		// 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.
1886
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1887
	}
1888
1889
	/**
1890
	 * Check if Jetpack's REST API compat file should be included
1891
	 * @action plugins_loaded
1892
	 * @return null
1893
	 */
1894
	public function check_rest_api_compat() {
1895
		/**
1896
		 * Filters the list of REST API compat files to be included.
1897
		 *
1898
		 * @since 2.2.5
1899
		 *
1900
		 * @param array $args Array of REST API compat files to include.
1901
		 */
1902
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1903
1904
		if ( function_exists( 'bbpress' ) )
1905
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1906
1907
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1908
			require_once $_jetpack_rest_api_compat_include;
1909
	}
1910
1911
	/**
1912
	 * Gets all plugins currently active in values, regardless of whether they're
1913
	 * traditionally activated or network activated.
1914
	 *
1915
	 * @todo Store the result in core's object cache maybe?
1916
	 */
1917
	public static function get_active_plugins() {
1918
		$active_plugins = (array) get_option( 'active_plugins', array() );
1919
1920
		if ( is_multisite() ) {
1921
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1922
			// whereas active_plugins stores them in the values.
1923
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1924
			if ( $network_plugins ) {
1925
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1926
			}
1927
		}
1928
1929
		sort( $active_plugins );
1930
1931
		return array_unique( $active_plugins );
1932
	}
1933
1934
	/**
1935
	 * Gets and parses additional plugin data to send with the heartbeat data
1936
	 *
1937
	 * @since 3.8.1
1938
	 *
1939
	 * @return array Array of plugin data
1940
	 */
1941
	public static function get_parsed_plugin_data() {
1942
		if ( ! function_exists( 'get_plugins' ) ) {
1943
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1944
		}
1945
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1946
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1947
		$active_plugins = Jetpack::get_active_plugins();
1948
1949
		$plugins = array();
1950
		foreach ( $all_plugins as $path => $plugin_data ) {
1951
			$plugins[ $path ] = array(
1952
					'is_active' => in_array( $path, $active_plugins ),
1953
					'file'      => $path,
1954
					'name'      => $plugin_data['Name'],
1955
					'version'   => $plugin_data['Version'],
1956
					'author'    => $plugin_data['Author'],
1957
			);
1958
		}
1959
1960
		return $plugins;
1961
	}
1962
1963
	/**
1964
	 * Gets and parses theme data to send with the heartbeat data
1965
	 *
1966
	 * @since 3.8.1
1967
	 *
1968
	 * @return array Array of theme data
1969
	 */
1970
	public static function get_parsed_theme_data() {
1971
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1972
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1973
1974
		$themes = array();
1975
		foreach ( $all_themes as $slug => $theme_data ) {
1976
			$theme_headers = array();
1977
			foreach ( $header_keys as $header_key ) {
1978
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1979
			}
1980
1981
			$themes[ $slug ] = array(
1982
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1983
					'slug' => $slug,
1984
					'theme_root' => $theme_data->get_theme_root_uri(),
1985
					'parent' => $theme_data->parent(),
1986
					'headers' => $theme_headers
1987
			);
1988
		}
1989
1990
		return $themes;
1991
	}
1992
1993
	/**
1994
	 * Checks whether a specific plugin is active.
1995
	 *
1996
	 * We don't want to store these in a static variable, in case
1997
	 * there are switch_to_blog() calls involved.
1998
	 */
1999
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2000
		return in_array( $plugin, self::get_active_plugins() );
2001
	}
2002
2003
	/**
2004
	 * Check if Jetpack's Open Graph tags should be used.
2005
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2006
	 *
2007
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2008
	 * @action plugins_loaded
2009
	 * @return null
2010
	 */
2011
	public function check_open_graph() {
2012
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2013
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2014
		}
2015
2016
		$active_plugins = self::get_active_plugins();
2017
2018
		if ( ! empty( $active_plugins ) ) {
2019
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2020
				if ( in_array( $plugin, $active_plugins ) ) {
2021
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2022
					break;
2023
				}
2024
			}
2025
		}
2026
2027
		/**
2028
		 * Allow the addition of Open Graph Meta Tags to all pages.
2029
		 *
2030
		 * @since 2.0.3
2031
		 *
2032
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2033
		 */
2034
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2035
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2036
		}
2037
	}
2038
2039
	/**
2040
	 * Check if Jetpack's Twitter tags should be used.
2041
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2042
	 *
2043
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2044
	 * @action plugins_loaded
2045
	 * @return null
2046
	 */
2047
	public function check_twitter_tags() {
2048
2049
		$active_plugins = self::get_active_plugins();
2050
2051
		if ( ! empty( $active_plugins ) ) {
2052
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2053
				if ( in_array( $plugin, $active_plugins ) ) {
2054
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2055
					break;
2056
				}
2057
			}
2058
		}
2059
2060
		/**
2061
		 * Allow Twitter Card Meta tags to be disabled.
2062
		 *
2063
		 * @since 2.6.0
2064
		 *
2065
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2066
		 */
2067
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2068
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2069
		}
2070
	}
2071
2072
	/**
2073
	 * Allows plugins to submit security reports.
2074
 	 *
2075
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2076
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2077
	 * @param array   $args         See definitions above
2078
	 */
2079
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2080
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2081
	}
2082
2083
/* Jetpack Options API */
2084
2085
	public static function get_option_names( $type = 'compact' ) {
2086
		return Jetpack_Options::get_option_names( $type );
2087
	}
2088
2089
	/**
2090
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2091
 	 *
2092
	 * @param string $name    Option name
2093
	 * @param mixed  $default (optional)
2094
	 */
2095
	public static function get_option( $name, $default = false ) {
2096
		return Jetpack_Options::get_option( $name, $default );
2097
	}
2098
2099
	/**
2100
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2101
 	 *
2102
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2103
	 * @param string $name  Option name
2104
	 * @param mixed  $value Option value
2105
	 */
2106
	public static function update_option( $name, $value ) {
2107
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2108
		return Jetpack_Options::update_option( $name, $value );
2109
	}
2110
2111
	/**
2112
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2113
 	 *
2114
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2115
	 * @param array $array array( option name => option value, ... )
2116
	 */
2117
	public static function update_options( $array ) {
2118
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2119
		return Jetpack_Options::update_options( $array );
2120
	}
2121
2122
	/**
2123
	 * Deletes the given option.  May be passed multiple option names as an array.
2124
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2125
	 *
2126
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2127
	 * @param string|array $names
2128
	 */
2129
	public static function delete_option( $names ) {
2130
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2131
		return Jetpack_Options::delete_option( $names );
2132
	}
2133
2134
	/**
2135
	 * Enters a user token into the user_tokens option
2136
	 *
2137
	 * @param int $user_id
2138
	 * @param string $token
2139
	 * return bool
2140
	 */
2141
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2142
		// not designed for concurrent updates
2143
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2144
		if ( ! is_array( $user_tokens ) )
2145
			$user_tokens = array();
2146
		$user_tokens[$user_id] = $token;
2147
		if ( $is_master_user ) {
2148
			$master_user = $user_id;
2149
			$options     = compact( 'user_tokens', 'master_user' );
2150
		} else {
2151
			$options = compact( 'user_tokens' );
2152
		}
2153
		return Jetpack_Options::update_options( $options );
2154
	}
2155
2156
	/**
2157
	 * Returns an array of all PHP files in the specified absolute path.
2158
	 * Equivalent to glob( "$absolute_path/*.php" ).
2159
	 *
2160
	 * @param string $absolute_path The absolute path of the directory to search.
2161
	 * @return array Array of absolute paths to the PHP files.
2162
	 */
2163
	public static function glob_php( $absolute_path ) {
2164
		if ( function_exists( 'glob' ) ) {
2165
			return glob( "$absolute_path/*.php" );
2166
		}
2167
2168
		$absolute_path = untrailingslashit( $absolute_path );
2169
		$files = array();
2170
		if ( ! $dir = @opendir( $absolute_path ) ) {
2171
			return $files;
2172
		}
2173
2174
		while ( false !== $file = readdir( $dir ) ) {
2175
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2176
				continue;
2177
			}
2178
2179
			$file = "$absolute_path/$file";
2180
2181
			if ( ! is_file( $file ) ) {
2182
				continue;
2183
			}
2184
2185
			$files[] = $file;
2186
		}
2187
2188
		closedir( $dir );
2189
2190
		return $files;
2191
	}
2192
2193
	public static function activate_new_modules( $redirect = false ) {
2194
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2195
			return;
2196
		}
2197
2198
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2199 View Code Duplication
		if ( ! $jetpack_old_version ) {
2200
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2201
			/** This action is documented in class.jetpack.php */
2202
			do_action( 'updating_jetpack_version', $version, false );
2203
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2204
		}
2205
2206
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2207
2208
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2209
			return;
2210
		}
2211
2212
		$active_modules     = Jetpack::get_active_modules();
2213
		$reactivate_modules = array();
2214
		foreach ( $active_modules as $active_module ) {
2215
			$module = Jetpack::get_module( $active_module );
2216
			if ( ! isset( $module['changed'] ) ) {
2217
				continue;
2218
			}
2219
2220
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2221
				continue;
2222
			}
2223
2224
			$reactivate_modules[] = $active_module;
2225
			Jetpack::deactivate_module( $active_module );
2226
		}
2227
2228
		$new_version = JETPACK__VERSION . ':' . time();
2229
		/** This action is documented in class.jetpack.php */
2230
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2231
		Jetpack_Options::update_options(
2232
			array(
2233
				'version'     => $new_version,
2234
				'old_version' => $jetpack_old_version,
2235
			)
2236
		);
2237
2238
		Jetpack::state( 'message', 'modules_activated' );
2239
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2240
2241
		if ( $redirect ) {
2242
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2243
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2244
				$page = $_GET['page'];
2245
			}
2246
2247
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2248
			exit;
2249
		}
2250
	}
2251
2252
	/**
2253
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2254
	 * Make sure to tuck away module "library" files in a sub-directory.
2255
	 */
2256
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2257
		static $modules = null;
2258
2259
		if ( ! isset( $modules ) ) {
2260
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2261
			// Use the cache if we're on the front-end and it's available...
2262
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2263
				$modules = $available_modules_option[ JETPACK__VERSION ];
2264
			} else {
2265
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2266
2267
				$modules = array();
2268
2269
				foreach ( $files as $file ) {
2270
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2271
						continue;
2272
					}
2273
2274
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2275
				}
2276
2277
				Jetpack_Options::update_option( 'available_modules', array(
2278
					JETPACK__VERSION => $modules,
2279
				) );
2280
			}
2281
		}
2282
2283
		/**
2284
		 * Filters the array of modules available to be activated.
2285
		 *
2286
		 * @since 2.4.0
2287
		 *
2288
		 * @param array $modules Array of available modules.
2289
		 * @param string $min_version Minimum version number required to use modules.
2290
		 * @param string $max_version Maximum version number required to use modules.
2291
		 */
2292
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2293
2294
		if ( ! $min_version && ! $max_version ) {
2295
			return array_keys( $mods );
2296
		}
2297
2298
		$r = array();
2299
		foreach ( $mods as $slug => $introduced ) {
2300
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2301
				continue;
2302
			}
2303
2304
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2305
				continue;
2306
			}
2307
2308
			$r[] = $slug;
2309
		}
2310
2311
		return $r;
2312
	}
2313
2314
	/**
2315
	 * Default modules loaded on activation.
2316
	 */
2317
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2318
		$return = array();
2319
2320
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2321
			$module_data = Jetpack::get_module( $module );
2322
2323
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2324
				case 'yes' :
2325
					$return[] = $module;
2326
					break;
2327
				case 'public' :
2328
					if ( Jetpack_Options::get_option( 'public' ) ) {
2329
						$return[] = $module;
2330
					}
2331
					break;
2332
				case 'no' :
2333
				default :
2334
					break;
2335
			}
2336
		}
2337
		/**
2338
		 * Filters the array of default modules.
2339
		 *
2340
		 * @since 2.5.0
2341
		 *
2342
		 * @param array $return Array of default modules.
2343
		 * @param string $min_version Minimum version number required to use modules.
2344
		 * @param string $max_version Maximum version number required to use modules.
2345
		 */
2346
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2347
	}
2348
2349
	/**
2350
	 * Checks activated modules during auto-activation to determine
2351
	 * if any of those modules are being deprecated.  If so, close
2352
	 * them out, and add any replacement modules.
2353
	 *
2354
	 * Runs at priority 99 by default.
2355
	 *
2356
	 * This is run late, so that it can still activate a module if
2357
	 * the new module is a replacement for another that the user
2358
	 * currently has active, even if something at the normal priority
2359
	 * would kibosh everything.
2360
	 *
2361
	 * @since 2.6
2362
	 * @uses jetpack_get_default_modules filter
2363
	 * @param array $modules
2364
	 * @return array
2365
	 */
2366
	function handle_deprecated_modules( $modules ) {
2367
		$deprecated_modules = array(
2368
			'debug'            => null,  // Closed out and moved to the debugger library.
2369
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2370
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2371
		);
2372
2373
		// Don't activate SSO if they never completed activating WPCC.
2374
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2375
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2376
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2377
				$deprecated_modules['wpcc'] = null;
2378
			}
2379
		}
2380
2381
		foreach ( $deprecated_modules as $module => $replacement ) {
2382
			if ( Jetpack::is_module_active( $module ) ) {
2383
				self::deactivate_module( $module );
2384
				if ( $replacement ) {
2385
					$modules[] = $replacement;
2386
				}
2387
			}
2388
		}
2389
2390
		return array_unique( $modules );
2391
	}
2392
2393
	/**
2394
	 * Checks activated plugins during auto-activation to determine
2395
	 * if any of those plugins are in the list with a corresponding module
2396
	 * that is not compatible with the plugin. The module will not be allowed
2397
	 * to auto-activate.
2398
	 *
2399
	 * @since 2.6
2400
	 * @uses jetpack_get_default_modules filter
2401
	 * @param array $modules
2402
	 * @return array
2403
	 */
2404
	function filter_default_modules( $modules ) {
2405
2406
		$active_plugins = self::get_active_plugins();
2407
2408
		if ( ! empty( $active_plugins ) ) {
2409
2410
			// For each module we'd like to auto-activate...
2411
			foreach ( $modules as $key => $module ) {
2412
				// If there are potential conflicts for it...
2413
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2414
					// For each potential conflict...
2415
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2416
						// If that conflicting plugin is active...
2417
						if ( in_array( $plugin, $active_plugins ) ) {
2418
							// Remove that item from being auto-activated.
2419
							unset( $modules[ $key ] );
2420
						}
2421
					}
2422
				}
2423
			}
2424
		}
2425
2426
		return $modules;
2427
	}
2428
2429
	/**
2430
	 * Extract a module's slug from its full path.
2431
	 */
2432
	public static function get_module_slug( $file ) {
2433
		return str_replace( '.php', '', basename( $file ) );
2434
	}
2435
2436
	/**
2437
	 * Generate a module's path from its slug.
2438
	 */
2439
	public static function get_module_path( $slug ) {
2440
		/**
2441
		 * Filters the path of a modules.
2442
		 *
2443
		 * @since 7.4.0
2444
		 *
2445
		 * @param array $return The absolute path to a module's root php file
2446
		 * @param string $slug The module slug
2447
		 */
2448
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2449
	}
2450
2451
	/**
2452
	 * Load module data from module file. Headers differ from WordPress
2453
	 * plugin headers to avoid them being identified as standalone
2454
	 * plugins on the WordPress plugins page.
2455
	 */
2456
	public static function get_module( $module ) {
2457
		$headers = array(
2458
			'name'                      => 'Module Name',
2459
			'description'               => 'Module Description',
2460
			'sort'                      => 'Sort Order',
2461
			'recommendation_order'      => 'Recommendation Order',
2462
			'introduced'                => 'First Introduced',
2463
			'changed'                   => 'Major Changes In',
2464
			'deactivate'                => 'Deactivate',
2465
			'free'                      => 'Free',
2466
			'requires_connection'       => 'Requires Connection',
2467
			'auto_activate'             => 'Auto Activate',
2468
			'module_tags'               => 'Module Tags',
2469
			'feature'                   => 'Feature',
2470
			'additional_search_queries' => 'Additional Search Queries',
2471
			'plan_classes'              => 'Plans',
2472
		);
2473
2474
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2475
2476
		$mod = Jetpack::get_file_data( $file, $headers );
2477
		if ( empty( $mod['name'] ) ) {
2478
			return false;
2479
		}
2480
2481
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2482
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2483
		$mod['deactivate']              = empty( $mod['deactivate'] );
2484
		$mod['free']                    = empty( $mod['free'] );
2485
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2486
2487
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2488
			$mod['auto_activate'] = 'No';
2489
		} else {
2490
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2491
		}
2492
2493
		if ( $mod['module_tags'] ) {
2494
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2495
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2496
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2497
		} else {
2498
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2499
		}
2500
2501 View Code Duplication
		if ( $mod['plan_classes'] ) {
2502
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2503
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2504
		} else {
2505
			$mod['plan_classes'] = array( 'free' );
2506
		}
2507
2508 View Code Duplication
		if ( $mod['feature'] ) {
2509
			$mod['feature'] = explode( ',', $mod['feature'] );
2510
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2511
		} else {
2512
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2513
		}
2514
2515
		/**
2516
		 * Filters the feature array on a module.
2517
		 *
2518
		 * This filter allows you to control where each module is filtered: Recommended,
2519
		 * and the default "Other" listing.
2520
		 *
2521
		 * @since 3.5.0
2522
		 *
2523
		 * @param array   $mod['feature'] The areas to feature this module:
2524
		 *     'Recommended' shows on the main Jetpack admin screen.
2525
		 *     'Other' should be the default if no other value is in the array.
2526
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2527
		 * @param array   $mod All the currently assembled module data.
2528
		 */
2529
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2530
2531
		/**
2532
		 * Filter the returned data about a module.
2533
		 *
2534
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2535
		 * so please be careful.
2536
		 *
2537
		 * @since 3.6.0
2538
		 *
2539
		 * @param array   $mod    The details of the requested module.
2540
		 * @param string  $module The slug of the module, e.g. sharedaddy
2541
		 * @param string  $file   The path to the module source file.
2542
		 */
2543
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2544
	}
2545
2546
	/**
2547
	 * Like core's get_file_data implementation, but caches the result.
2548
	 */
2549
	public static function get_file_data( $file, $headers ) {
2550
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2551
		$file_name = basename( $file );
2552
2553
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2554
2555
		$file_data_option = get_transient( $cache_key );
2556
2557
		if ( false === $file_data_option ) {
2558
			$file_data_option = array();
2559
		}
2560
2561
		$key           = md5( $file_name . serialize( $headers ) );
2562
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2563
2564
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2565
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2566
			return $file_data_option[ $key ];
2567
		}
2568
2569
		$data = get_file_data( $file, $headers );
2570
2571
		$file_data_option[ $key ] = $data;
2572
2573
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2574
2575
		return $data;
2576
	}
2577
2578
2579
	/**
2580
	 * Return translated module tag.
2581
	 *
2582
	 * @param string $tag Tag as it appears in each module heading.
2583
	 *
2584
	 * @return mixed
2585
	 */
2586
	public static function translate_module_tag( $tag ) {
2587
		return jetpack_get_module_i18n_tag( $tag );
2588
	}
2589
2590
	/**
2591
	 * Get i18n strings as a JSON-encoded string
2592
	 *
2593
	 * @return string The locale as JSON
2594
	 */
2595
	public static function get_i18n_data_json() {
2596
2597
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2598
		// JSON files with the file they should be included for. This is an md5
2599
		// of '_inc/build/admin.js'.
2600
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2601
2602
		$i18n_json =
2603
				   JETPACK__PLUGIN_DIR
2604
				   . 'languages/json/jetpack-'
2605
				   . get_user_locale()
2606
				   . '-'
2607
				   . $path_md5
2608
				   . '.json';
2609
2610
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2611
			$locale_data = @file_get_contents( $i18n_json );
2612
			if ( $locale_data ) {
2613
				return $locale_data;
2614
			}
2615
		}
2616
2617
		// Return valid empty Jed locale
2618
		return '{ "locale_data": { "messages": { "": {} } } }';
2619
	}
2620
2621
	/**
2622
	 * Add locale data setup to wp-i18n
2623
	 *
2624
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2625
	 *
2626
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2627
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2628
	 *
2629
	 * This method provides a safe way to request the setup multiple times but add the script at
2630
	 * most once.
2631
	 *
2632
	 * @since 6.7.0
2633
	 *
2634
	 * @return void
2635
	 */
2636
	public static function setup_wp_i18n_locale_data() {
2637
		static $script_added = false;
2638
		if ( ! $script_added ) {
2639
			$script_added = true;
2640
			wp_add_inline_script(
2641
				'wp-i18n',
2642
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2643
			);
2644
		}
2645
	}
2646
2647
	/**
2648
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2649
	 *
2650
	 * @since 3.9.2
2651
	 *
2652
	 * @param array $modules
2653
	 *
2654
	 * @return string|void
2655
	 */
2656
	public static function get_translated_modules( $modules ) {
2657
		foreach ( $modules as $index => $module ) {
2658
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2659
			if ( isset( $module['name'] ) ) {
2660
				$modules[ $index ]['name'] = $i18n_module['name'];
2661
			}
2662
			if ( isset( $module['description'] ) ) {
2663
				$modules[ $index ]['description'] = $i18n_module['description'];
2664
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2665
			}
2666
		}
2667
		return $modules;
2668
	}
2669
2670
	/**
2671
	 * Get a list of activated modules as an array of module slugs.
2672
	 */
2673
	public static function get_active_modules() {
2674
		$active = Jetpack_Options::get_option( 'active_modules' );
2675
2676
		if ( ! is_array( $active ) ) {
2677
			$active = array();
2678
		}
2679
2680
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2681
			$active[] = 'vaultpress';
2682
		} else {
2683
			$active = array_diff( $active, array( 'vaultpress' ) );
2684
		}
2685
2686
		//If protect is active on the main site of a multisite, it should be active on all sites.
2687
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2688
			$active[] = 'protect';
2689
		}
2690
2691
		/**
2692
		 * Allow filtering of the active modules.
2693
		 *
2694
		 * Gives theme and plugin developers the power to alter the modules that
2695
		 * are activated on the fly.
2696
		 *
2697
		 * @since 5.8.0
2698
		 *
2699
		 * @param array $active Array of active module slugs.
2700
		 */
2701
		$active = apply_filters( 'jetpack_active_modules', $active );
2702
2703
		return array_unique( $active );
2704
	}
2705
2706
	/**
2707
	 * Check whether or not a Jetpack module is active.
2708
	 *
2709
	 * @param string $module The slug of a Jetpack module.
2710
	 * @return bool
2711
	 *
2712
	 * @static
2713
	 */
2714
	public static function is_module_active( $module ) {
2715
		return in_array( $module, self::get_active_modules() );
2716
	}
2717
2718
	public static function is_module( $module ) {
2719
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2720
	}
2721
2722
	/**
2723
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2724
	 *
2725
	 * @param bool $catch True to start catching, False to stop.
2726
	 *
2727
	 * @static
2728
	 */
2729
	public static function catch_errors( $catch ) {
2730
		static $display_errors, $error_reporting;
2731
2732
		if ( $catch ) {
2733
			$display_errors  = @ini_set( 'display_errors', 1 );
2734
			$error_reporting = @error_reporting( E_ALL );
2735
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2736
		} else {
2737
			@ini_set( 'display_errors', $display_errors );
2738
			@error_reporting( $error_reporting );
2739
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2740
		}
2741
	}
2742
2743
	/**
2744
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2745
	 */
2746
	public static function catch_errors_on_shutdown() {
2747
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2748
	}
2749
2750
	/**
2751
	 * Rewrite any string to make paths easier to read.
2752
	 *
2753
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2754
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2755
	 *
2756
	 * @param $string
2757
	 * @return mixed
2758
	 */
2759
	public static function alias_directories( $string ) {
2760
		// ABSPATH has a trailing slash.
2761
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2762
		// WP_CONTENT_DIR does not have a trailing slash.
2763
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2764
2765
		return $string;
2766
	}
2767
2768
	public static function activate_default_modules(
2769
		$min_version = false,
2770
		$max_version = false,
2771
		$other_modules = array(),
2772
		$redirect = true,
2773
		$send_state_messages = true
2774
	) {
2775
		$jetpack = Jetpack::init();
2776
2777
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2778
		$modules = array_merge( $other_modules, $modules );
2779
2780
		// Look for standalone plugins and disable if active.
2781
2782
		$to_deactivate = array();
2783
		foreach ( $modules as $module ) {
2784
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2785
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2786
			}
2787
		}
2788
2789
		$deactivated = array();
2790
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2791
			list( $probable_file, $probable_title ) = $deactivate_me;
2792
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2793
				$deactivated[] = $module;
2794
			}
2795
		}
2796
2797
		if ( $deactivated && $redirect ) {
2798
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2799
2800
			$url = add_query_arg(
2801
				array(
2802
					'action'   => 'activate_default_modules',
2803
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2804
				),
2805
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2806
			);
2807
			wp_safe_redirect( $url );
2808
			exit;
2809
		}
2810
2811
		/**
2812
		 * Fires before default modules are activated.
2813
		 *
2814
		 * @since 1.9.0
2815
		 *
2816
		 * @param string $min_version Minimum version number required to use modules.
2817
		 * @param string $max_version Maximum version number required to use modules.
2818
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2819
		 */
2820
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2821
2822
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2823
		if ( $send_state_messages ) {
2824
			Jetpack::restate();
2825
			Jetpack::catch_errors( true );
2826
		}
2827
2828
		$active = Jetpack::get_active_modules();
2829
2830
		foreach ( $modules as $module ) {
2831
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2832
				$active[] = $module;
2833
				self::update_active_modules( $active );
2834
				continue;
2835
			}
2836
2837
			if ( $send_state_messages && in_array( $module, $active ) ) {
2838
				$module_info = Jetpack::get_module( $module );
2839 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2840
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2841
					if ( $active_state = Jetpack::state( $state ) ) {
2842
						$active_state = explode( ',', $active_state );
2843
					} else {
2844
						$active_state = array();
2845
					}
2846
					$active_state[] = $module;
2847
					Jetpack::state( $state, implode( ',', $active_state ) );
2848
				}
2849
				continue;
2850
			}
2851
2852
			$file = Jetpack::get_module_path( $module );
2853
			if ( ! file_exists( $file ) ) {
2854
				continue;
2855
			}
2856
2857
			// we'll override this later if the plugin can be included without fatal error
2858
			if ( $redirect ) {
2859
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2860
			}
2861
2862
			if ( $send_state_messages ) {
2863
				Jetpack::state( 'error', 'module_activation_failed' );
2864
				Jetpack::state( 'module', $module );
2865
			}
2866
2867
			ob_start();
2868
			require_once $file;
2869
2870
			$active[] = $module;
2871
2872 View Code Duplication
			if ( $send_state_messages ) {
2873
2874
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2875
				if ( $active_state = Jetpack::state( $state ) ) {
2876
					$active_state = explode( ',', $active_state );
2877
				} else {
2878
					$active_state = array();
2879
				}
2880
				$active_state[] = $module;
2881
				Jetpack::state( $state, implode( ',', $active_state ) );
2882
			}
2883
2884
			Jetpack::update_active_modules( $active );
2885
2886
			ob_end_clean();
2887
		}
2888
2889
		if ( $send_state_messages ) {
2890
			Jetpack::state( 'error', false );
2891
			Jetpack::state( 'module', false );
2892
		}
2893
2894
		Jetpack::catch_errors( false );
2895
		/**
2896
		 * Fires when default modules are activated.
2897
		 *
2898
		 * @since 1.9.0
2899
		 *
2900
		 * @param string $min_version Minimum version number required to use modules.
2901
		 * @param string $max_version Maximum version number required to use modules.
2902
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2903
		 */
2904
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2905
	}
2906
2907
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2908
		/**
2909
		 * Fires before a module is activated.
2910
		 *
2911
		 * @since 2.6.0
2912
		 *
2913
		 * @param string $module Module slug.
2914
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2915
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2916
		 */
2917
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2918
2919
		$jetpack = Jetpack::init();
2920
2921
		if ( ! strlen( $module ) )
2922
			return false;
2923
2924
		if ( ! Jetpack::is_module( $module ) )
2925
			return false;
2926
2927
		// If it's already active, then don't do it again
2928
		$active = Jetpack::get_active_modules();
2929
		foreach ( $active as $act ) {
2930
			if ( $act == $module )
2931
				return true;
2932
		}
2933
2934
		$module_data = Jetpack::get_module( $module );
2935
2936
		if ( ! Jetpack::is_active() ) {
2937
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2938
				return false;
2939
2940
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2941
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2942
				return false;
2943
		}
2944
2945
		// Check and see if the old plugin is active
2946
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2947
			// Deactivate the old plugin
2948
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2949
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2950
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2951
				Jetpack::state( 'deactivated_plugins', $module );
2952
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2953
				exit;
2954
			}
2955
		}
2956
2957
		// Protect won't work with mis-configured IPs
2958
		if ( 'protect' === $module ) {
2959
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2960
			if ( ! jetpack_protect_get_ip() ) {
2961
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2962
				return false;
2963
			}
2964
		}
2965
2966
		if ( ! Jetpack_Plan::supports( $module ) ) {
2967
			return false;
2968
		}
2969
2970
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2971
		Jetpack::state( 'module', $module );
2972
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2973
2974
		Jetpack::catch_errors( true );
2975
		ob_start();
2976
		require Jetpack::get_module_path( $module );
2977
		/** This action is documented in class.jetpack.php */
2978
		do_action( 'jetpack_activate_module', $module );
2979
		$active[] = $module;
2980
		Jetpack::update_active_modules( $active );
2981
2982
		Jetpack::state( 'error', false ); // the override
2983
		ob_end_clean();
2984
		Jetpack::catch_errors( false );
2985
2986
		if ( $redirect ) {
2987
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2988
		}
2989
		if ( $exit ) {
2990
			exit;
2991
		}
2992
		return true;
2993
	}
2994
2995
	function activate_module_actions( $module ) {
2996
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2997
	}
2998
2999
	public static function deactivate_module( $module ) {
3000
		/**
3001
		 * Fires when a module is deactivated.
3002
		 *
3003
		 * @since 1.9.0
3004
		 *
3005
		 * @param string $module Module slug.
3006
		 */
3007
		do_action( 'jetpack_pre_deactivate_module', $module );
3008
3009
		$jetpack = Jetpack::init();
3010
3011
		$active = Jetpack::get_active_modules();
3012
		$new    = array_filter( array_diff( $active, (array) $module ) );
3013
3014
		return self::update_active_modules( $new );
3015
	}
3016
3017
	public static function enable_module_configurable( $module ) {
3018
		$module = Jetpack::get_module_slug( $module );
3019
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3020
	}
3021
3022
	/**
3023
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3024
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3025
	 *
3026
	 * @param string $module Module slug
3027
	 * @return string $url module configuration URL
3028
	 */
3029
	public static function module_configuration_url( $module ) {
3030
		$module = Jetpack::get_module_slug( $module );
3031
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3032
		/**
3033
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3034
		 *
3035
		 * @since 6.9.0
3036
		 *
3037
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3038
		 */
3039
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3040
3041
		return $url;
3042
	}
3043
3044
/* Installation */
3045
	public static function bail_on_activation( $message, $deactivate = true ) {
3046
?>
3047
<!doctype html>
3048
<html>
3049
<head>
3050
<meta charset="<?php bloginfo( 'charset' ); ?>">
3051
<style>
3052
* {
3053
	text-align: center;
3054
	margin: 0;
3055
	padding: 0;
3056
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3057
}
3058
p {
3059
	margin-top: 1em;
3060
	font-size: 18px;
3061
}
3062
</style>
3063
<body>
3064
<p><?php echo esc_html( $message ); ?></p>
3065
</body>
3066
</html>
3067
<?php
3068
		if ( $deactivate ) {
3069
			$plugins = get_option( 'active_plugins' );
3070
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3071
			$update  = false;
3072
			foreach ( $plugins as $i => $plugin ) {
3073
				if ( $plugin === $jetpack ) {
3074
					$plugins[$i] = false;
3075
					$update = true;
3076
				}
3077
			}
3078
3079
			if ( $update ) {
3080
				update_option( 'active_plugins', array_filter( $plugins ) );
3081
			}
3082
		}
3083
		exit;
3084
	}
3085
3086
	/**
3087
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3088
	 * @static
3089
	 */
3090
	public static function plugin_activation( $network_wide ) {
3091
		Jetpack_Options::update_option( 'activated', 1 );
3092
3093
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3094
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3095
		}
3096
3097
		if ( $network_wide )
3098
			Jetpack::state( 'network_nag', true );
3099
3100
		// For firing one-off events (notices) immediately after activation
3101
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3102
3103
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3104
3105
		Jetpack::plugin_initialize();
3106
	}
3107
3108
	public static function get_activation_source( $referer_url ) {
3109
3110
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3111
			return array( 'wp-cli', null );
3112
		}
3113
3114
		$referer = parse_url( $referer_url );
3115
3116
		$source_type = 'unknown';
3117
		$source_query = null;
3118
3119
		if ( ! is_array( $referer ) ) {
3120
			return array( $source_type, $source_query );
3121
		}
3122
3123
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3124
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3125
3126
		if ( isset( $referer['query'] ) ) {
3127
			parse_str( $referer['query'], $query_parts );
3128
		} else {
3129
			$query_parts = array();
3130
		}
3131
3132
		if ( $plugins_path === $referer['path'] ) {
3133
			$source_type = 'list';
3134
		} elseif ( $plugins_install_path === $referer['path'] ) {
3135
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3136
			switch( $tab ) {
3137
				case 'popular':
3138
					$source_type = 'popular';
3139
					break;
3140
				case 'recommended':
3141
					$source_type = 'recommended';
3142
					break;
3143
				case 'favorites':
3144
					$source_type = 'favorites';
3145
					break;
3146
				case 'search':
3147
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3148
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3149
					break;
3150
				default:
3151
					$source_type = 'featured';
3152
			}
3153
		}
3154
3155
		return array( $source_type, $source_query );
3156
	}
3157
3158
	/**
3159
	 * Runs before bumping version numbers up to a new version
3160
	 * @param  string $version    Version:timestamp
3161
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3162
	 * @return null              [description]
3163
	 */
3164
	public static function do_version_bump( $version, $old_version ) {
3165
		if ( ! $old_version ) { // For new sites
3166
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3167
		}
3168
	}
3169
3170
	/**
3171
	 * Sets the internal version number and activation state.
3172
	 * @static
3173
	 */
3174
	public static function plugin_initialize() {
3175
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3176
			Jetpack_Options::update_option( 'activated', 2 );
3177
		}
3178
3179 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3180
			$version = $old_version = JETPACK__VERSION . ':' . time();
3181
			/** This action is documented in class.jetpack.php */
3182
			do_action( 'updating_jetpack_version', $version, false );
3183
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3184
		}
3185
3186
		Jetpack::load_modules();
3187
3188
		Jetpack_Options::delete_option( 'do_activate' );
3189
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3190
	}
3191
3192
	/**
3193
	 * Removes all connection options
3194
	 * @static
3195
	 */
3196
	public static function plugin_deactivation( ) {
3197
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3198
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3199
			Jetpack_Network::init()->deactivate();
3200
		} else {
3201
			Jetpack::disconnect( false );
3202
			//Jetpack_Heartbeat::init()->deactivate();
3203
		}
3204
	}
3205
3206
	/**
3207
	 * Disconnects from the Jetpack servers.
3208
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3209
	 * @static
3210
	 */
3211
	public static function disconnect( $update_activated_state = true ) {
3212
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3213
		$connection = self::connection();
3214
		$connection->clean_nonces( true );
3215
3216
		// If the site is in an IDC because sync is not allowed,
3217
		// let's make sure to not disconnect the production site.
3218
		if ( ! self::validate_sync_error_idc_option() ) {
3219
			$tracking = new Tracking();
3220
			$tracking->record_user_event( 'disconnect_site', array() );
3221
			Jetpack::load_xml_rpc_client();
3222
			$xml = new Jetpack_IXR_Client();
3223
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3224
		}
3225
3226
		Jetpack_Options::delete_option(
3227
			array(
3228
				'blog_token',
3229
				'user_token',
3230
				'user_tokens',
3231
				'master_user',
3232
				'time_diff',
3233
				'fallback_no_verify_ssl_certs',
3234
			)
3235
		);
3236
3237
		Jetpack_IDC::clear_all_idc_options();
3238
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3239
3240
		if ( $update_activated_state ) {
3241
			Jetpack_Options::update_option( 'activated', 4 );
3242
		}
3243
3244
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3245
			// Check then record unique disconnection if site has never been disconnected previously
3246
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3247
				$jetpack_unique_connection['disconnected'] = 1;
3248
			} else {
3249
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3250
					//track unique disconnect
3251
					$jetpack = Jetpack::init();
3252
3253
					$jetpack->stat( 'connections', 'unique-disconnect' );
3254
					$jetpack->do_stats( 'server_side' );
3255
				}
3256
				// increment number of times disconnected
3257
				$jetpack_unique_connection['disconnected'] += 1;
3258
			}
3259
3260
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3261
		}
3262
3263
		// Delete cached connected user data
3264
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3265
		delete_transient( $transient_key );
3266
3267
		// Delete all the sync related data. Since it could be taking up space.
3268
		Sender::get_instance()->uninstall();
3269
3270
		// Disable the Heartbeat cron
3271
		Jetpack_Heartbeat::init()->deactivate();
3272
	}
3273
3274
	/**
3275
	 * Unlinks the current user from the linked WordPress.com user.
3276
	 *
3277
	 * @deprecated since 7.7
3278
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3279
	 *
3280
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
3281
	 * @return Boolean Whether the disconnection of the user was successful.
3282
	 */
3283
	public static function unlink_user( $user_id = null ) {
3284
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3285
		return Connection_Manager::disconnect_user( $user_id );
3286
	}
3287
3288
	/**
3289
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3290
	 */
3291
	public static function try_registration() {
3292
		// The user has agreed to the TOS at some point by now.
3293
		Jetpack_Options::update_option( 'tos_agreed', true );
3294
3295
		// Let's get some testing in beta versions and such.
3296
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3297
			// Before attempting to connect, let's make sure that the domains are viable.
3298
			$domains_to_check = array_unique( array(
3299
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3300
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3301
			) );
3302
			foreach ( $domains_to_check as $domain ) {
3303
				$result = self::connection()->is_usable_domain( $domain );
3304
				if ( is_wp_error( $result ) ) {
3305
					return $result;
3306
				}
3307
			}
3308
		}
3309
3310
		$result = Jetpack::register();
3311
3312
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3313
		if ( ! $result || is_wp_error( $result ) ) {
3314
			return $result;
3315
		} else {
3316
			return true;
3317
		}
3318
	}
3319
3320
	/**
3321
	 * Tracking an internal event log. Try not to put too much chaff in here.
3322
	 *
3323
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3324
	 */
3325
	public static function log( $code, $data = null ) {
3326
		// only grab the latest 200 entries
3327
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3328
3329
		// Append our event to the log
3330
		$log_entry = array(
3331
			'time'    => time(),
3332
			'user_id' => get_current_user_id(),
3333
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3334
			'code'    => $code,
3335
		);
3336
		// Don't bother storing it unless we've got some.
3337
		if ( ! is_null( $data ) ) {
3338
			$log_entry['data'] = $data;
3339
		}
3340
		$log[] = $log_entry;
3341
3342
		// Try add_option first, to make sure it's not autoloaded.
3343
		// @todo: Add an add_option method to Jetpack_Options
3344
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3345
			Jetpack_Options::update_option( 'log', $log );
3346
		}
3347
3348
		/**
3349
		 * Fires when Jetpack logs an internal event.
3350
		 *
3351
		 * @since 3.0.0
3352
		 *
3353
		 * @param array $log_entry {
3354
		 *	Array of details about the log entry.
3355
		 *
3356
		 *	@param string time Time of the event.
3357
		 *	@param int user_id ID of the user who trigerred the event.
3358
		 *	@param int blog_id Jetpack Blog ID.
3359
		 *	@param string code Unique name for the event.
3360
		 *	@param string data Data about the event.
3361
		 * }
3362
		 */
3363
		do_action( 'jetpack_log_entry', $log_entry );
3364
	}
3365
3366
	/**
3367
	 * Get the internal event log.
3368
	 *
3369
	 * @param $event (string) - only return the specific log events
3370
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3371
	 *
3372
	 * @return array of log events || WP_Error for invalid params
3373
	 */
3374
	public static function get_log( $event = false, $num = false ) {
3375
		if ( $event && ! is_string( $event ) ) {
3376
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3377
		}
3378
3379
		if ( $num && ! is_numeric( $num ) ) {
3380
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3381
		}
3382
3383
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3384
3385
		// If nothing set - act as it did before, otherwise let's start customizing the output
3386
		if ( ! $num && ! $event ) {
3387
			return $entire_log;
3388
		} else {
3389
			$entire_log = array_reverse( $entire_log );
3390
		}
3391
3392
		$custom_log_output = array();
3393
3394
		if ( $event ) {
3395
			foreach ( $entire_log as $log_event ) {
3396
				if ( $event == $log_event[ 'code' ] ) {
3397
					$custom_log_output[] = $log_event;
3398
				}
3399
			}
3400
		} else {
3401
			$custom_log_output = $entire_log;
3402
		}
3403
3404
		if ( $num ) {
3405
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3406
		}
3407
3408
		return $custom_log_output;
3409
	}
3410
3411
	/**
3412
	 * Log modification of important settings.
3413
	 */
3414
	public static function log_settings_change( $option, $old_value, $value ) {
3415
		switch( $option ) {
3416
			case 'jetpack_sync_non_public_post_stati':
3417
				self::log( $option, $value );
3418
				break;
3419
		}
3420
	}
3421
3422
	/**
3423
	 * Return stat data for WPCOM sync
3424
	 */
3425
	public static function get_stat_data( $encode = true, $extended = true ) {
3426
		$data = Jetpack_Heartbeat::generate_stats_array();
3427
3428
		if ( $extended ) {
3429
			$additional_data = self::get_additional_stat_data();
3430
			$data = array_merge( $data, $additional_data );
3431
		}
3432
3433
		if ( $encode ) {
3434
			return json_encode( $data );
3435
		}
3436
3437
		return $data;
3438
	}
3439
3440
	/**
3441
	 * Get additional stat data to sync to WPCOM
3442
	 */
3443
	public static function get_additional_stat_data( $prefix = '' ) {
3444
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3445
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3446
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3447
		$return["{$prefix}site-count"]     = 0;
3448
3449
		if ( function_exists( 'get_blog_count' ) ) {
3450
			$return["{$prefix}site-count"] = get_blog_count();
3451
		}
3452
		return $return;
3453
	}
3454
3455
	private static function get_site_user_count() {
3456
		global $wpdb;
3457
3458
		if ( function_exists( 'wp_is_large_network' ) ) {
3459
			if ( wp_is_large_network( 'users' ) ) {
3460
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3461
			}
3462
		}
3463
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3464
			// It wasn't there, so regenerate the data and save the transient
3465
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3466
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3467
		}
3468
		return $user_count;
3469
	}
3470
3471
	/* Admin Pages */
3472
3473
	function admin_init() {
3474
		// If the plugin is not connected, display a connect message.
3475
		if (
3476
			// the plugin was auto-activated and needs its candy
3477
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3478
		||
3479
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3480
			! Jetpack_Options::get_option( 'activated' )
3481
		) {
3482
			Jetpack::plugin_initialize();
3483
		}
3484
3485
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3486
			Jetpack_Connection_Banner::init();
3487
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3488
			// Upgrade: 1.1 -> 1.1.1
3489
			// Check and see if host can verify the Jetpack servers' SSL certificate
3490
			$args = array();
3491
			$connection = self::connection();
3492
			Client::_wp_remote_request(
3493
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3494
				$args,
3495
				true
3496
			);
3497
		}
3498
3499
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3500
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3501
		}
3502
3503
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3504
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3505
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3506
3507
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3508
			// Artificially throw errors in certain whitelisted cases during plugin activation
3509
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3510
		}
3511
3512
		// Add custom column in wp-admin/users.php to show whether user is linked.
3513
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3514
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3515
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3516
	}
3517
3518
	function admin_body_class( $admin_body_class = '' ) {
3519
		$classes = explode( ' ', trim( $admin_body_class ) );
3520
3521
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3522
3523
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3524
		return " $admin_body_class ";
3525
	}
3526
3527
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3528
		return $admin_body_class . ' jetpack-pagestyles ';
3529
	}
3530
3531
	/**
3532
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3533
	 * This function artificially throws errors for such cases (whitelisted).
3534
	 *
3535
	 * @param string $plugin The activated plugin.
3536
	 */
3537
	function throw_error_on_activate_plugin( $plugin ) {
3538
		$active_modules = Jetpack::get_active_modules();
3539
3540
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3541
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3542
			$throw = false;
3543
3544
			// Try and make sure it really was the stats plugin
3545
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3546
				if ( 'stats.php' == basename( $plugin ) ) {
3547
					$throw = true;
3548
				}
3549
			} else {
3550
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3551
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3552
					$throw = true;
3553
				}
3554
			}
3555
3556
			if ( $throw ) {
3557
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3558
			}
3559
		}
3560
	}
3561
3562
	function intercept_plugin_error_scrape_init() {
3563
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3564
	}
3565
3566
	function intercept_plugin_error_scrape( $action, $result ) {
3567
		if ( ! $result ) {
3568
			return;
3569
		}
3570
3571
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3572
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3573
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3574
			}
3575
		}
3576
	}
3577
3578
	function add_remote_request_handlers() {
3579
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3580
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3581
	}
3582
3583
	function remote_request_handlers() {
3584
		$action = current_filter();
3585
3586
		switch ( current_filter() ) {
3587
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3588
			$response = $this->upload_handler();
3589
			break;
3590
3591
		case 'wp_ajax_nopriv_jetpack_update_file' :
3592
			$response = $this->upload_handler( true );
3593
			break;
3594
		default :
3595
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3596
			break;
3597
		}
3598
3599
		if ( ! $response ) {
3600
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3601
		}
3602
3603
		if ( is_wp_error( $response ) ) {
3604
			$status_code       = $response->get_error_data();
3605
			$error             = $response->get_error_code();
3606
			$error_description = $response->get_error_message();
3607
3608
			if ( ! is_int( $status_code ) ) {
3609
				$status_code = 400;
3610
			}
3611
3612
			status_header( $status_code );
3613
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3614
		}
3615
3616
		status_header( 200 );
3617
		if ( true === $response ) {
3618
			exit;
3619
		}
3620
3621
		die( json_encode( (object) $response ) );
3622
	}
3623
3624
	/**
3625
	 * Uploads a file gotten from the global $_FILES.
3626
	 * If `$update_media_item` is true and `post_id` is defined
3627
	 * the attachment file of the media item (gotten through of the post_id)
3628
	 * will be updated instead of add a new one.
3629
	 *
3630
	 * @param  boolean $update_media_item - update media attachment
3631
	 * @return array - An array describing the uploadind files process
3632
	 */
3633
	function upload_handler( $update_media_item = false ) {
3634
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3635
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3636
		}
3637
3638
		$user = wp_authenticate( '', '' );
3639
		if ( ! $user || is_wp_error( $user ) ) {
3640
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3641
		}
3642
3643
		wp_set_current_user( $user->ID );
3644
3645
		if ( ! current_user_can( 'upload_files' ) ) {
3646
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3647
		}
3648
3649
		if ( empty( $_FILES ) ) {
3650
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3651
		}
3652
3653
		foreach ( array_keys( $_FILES ) as $files_key ) {
3654
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3655
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3656
			}
3657
		}
3658
3659
		$media_keys = array_keys( $_FILES['media'] );
3660
3661
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3662
		if ( ! $token || is_wp_error( $token ) ) {
3663
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3664
		}
3665
3666
		$uploaded_files = array();
3667
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3668
		unset( $GLOBALS['post'] );
3669
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3670
			$file = array();
3671
			foreach ( $media_keys as $media_key ) {
3672
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3673
			}
3674
3675
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3676
3677
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3678
			if ( $hmac_provided !== $hmac_file ) {
3679
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3680
				continue;
3681
			}
3682
3683
			$_FILES['.jetpack.upload.'] = $file;
3684
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3685
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3686
				$post_id = 0;
3687
			}
3688
3689
			if ( $update_media_item ) {
3690
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3691
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3692
				}
3693
3694
				$media_array = $_FILES['media'];
3695
3696
				$file_array['name'] = $media_array['name'][0];
3697
				$file_array['type'] = $media_array['type'][0];
3698
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3699
				$file_array['error'] = $media_array['error'][0];
3700
				$file_array['size'] = $media_array['size'][0];
3701
3702
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3703
3704
				if ( is_wp_error( $edited_media_item ) ) {
3705
					return $edited_media_item;
3706
				}
3707
3708
				$response = (object) array(
3709
					'id'   => (string) $post_id,
3710
					'file' => (string) $edited_media_item->post_title,
3711
					'url'  => (string) wp_get_attachment_url( $post_id ),
3712
					'type' => (string) $edited_media_item->post_mime_type,
3713
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3714
				);
3715
3716
				return (array) array( $response );
3717
			}
3718
3719
			$attachment_id = media_handle_upload(
3720
				'.jetpack.upload.',
3721
				$post_id,
3722
				array(),
3723
				array(
3724
					'action' => 'jetpack_upload_file',
3725
				)
3726
			);
3727
3728
			if ( ! $attachment_id ) {
3729
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3730
			} elseif ( is_wp_error( $attachment_id ) ) {
3731
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3732
			} else {
3733
				$attachment = get_post( $attachment_id );
3734
				$uploaded_files[$index] = (object) array(
3735
					'id'   => (string) $attachment_id,
3736
					'file' => $attachment->post_title,
3737
					'url'  => wp_get_attachment_url( $attachment_id ),
3738
					'type' => $attachment->post_mime_type,
3739
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3740
				);
3741
				// Zip files uploads are not supported unless they are done for installation purposed
3742
				// lets delete them in case something goes wrong in this whole process
3743
				if ( 'application/zip' === $attachment->post_mime_type ) {
3744
					// Schedule a cleanup for 2 hours from now in case of failed install.
3745
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3746
				}
3747
			}
3748
		}
3749
		if ( ! is_null( $global_post ) ) {
3750
			$GLOBALS['post'] = $global_post;
3751
		}
3752
3753
		return $uploaded_files;
3754
	}
3755
3756
	/**
3757
	 * Add help to the Jetpack page
3758
	 *
3759
	 * @since Jetpack (1.2.3)
3760
	 * @return false if not the Jetpack page
3761
	 */
3762
	function admin_help() {
3763
		$current_screen = get_current_screen();
3764
3765
		// Overview
3766
		$current_screen->add_help_tab(
3767
			array(
3768
				'id'		=> 'home',
3769
				'title'		=> __( 'Home', 'jetpack' ),
3770
				'content'	=>
3771
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3772
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3773
					'<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>',
3774
			)
3775
		);
3776
3777
		// Screen Content
3778
		if ( current_user_can( 'manage_options' ) ) {
3779
			$current_screen->add_help_tab(
3780
				array(
3781
					'id'		=> 'settings',
3782
					'title'		=> __( 'Settings', 'jetpack' ),
3783
					'content'	=>
3784
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3785
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3786
						'<ol>' .
3787
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3788
							'<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>' .
3789
						'</ol>' .
3790
						'<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>'
3791
				)
3792
			);
3793
		}
3794
3795
		// Help Sidebar
3796
		$current_screen->set_help_sidebar(
3797
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3798
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3799
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3800
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3801
		);
3802
	}
3803
3804
	function admin_menu_css() {
3805
		wp_enqueue_style( 'jetpack-icons' );
3806
	}
3807
3808
	function admin_menu_order() {
3809
		return true;
3810
	}
3811
3812 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3813
		$jp_menu_order = array();
3814
3815
		foreach ( $menu_order as $index => $item ) {
3816
			if ( $item != 'jetpack' ) {
3817
				$jp_menu_order[] = $item;
3818
			}
3819
3820
			if ( $index == 0 ) {
3821
				$jp_menu_order[] = 'jetpack';
3822
			}
3823
		}
3824
3825
		return $jp_menu_order;
3826
	}
3827
3828
	function admin_banner_styles() {
3829
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3830
3831
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3832
			wp_register_style(
3833
				'jetpack-dops-style',
3834
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3835
				array(),
3836
				JETPACK__VERSION
3837
			);
3838
		}
3839
3840
		wp_enqueue_style(
3841
			'jetpack',
3842
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3843
			array( 'jetpack-dops-style' ),
3844
			 JETPACK__VERSION . '-20121016'
3845
		);
3846
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3847
		wp_style_add_data( 'jetpack', 'suffix', $min );
3848
	}
3849
3850
	function plugin_action_links( $actions ) {
3851
3852
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3853
3854
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3855
			return array_merge(
3856
				$jetpack_home,
3857
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3858
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3859
				$actions
3860
				);
3861
			}
3862
3863
		return array_merge( $jetpack_home, $actions );
3864
	}
3865
3866
	/*
3867
	 * Registration flow:
3868
	 * 1 - ::admin_page_load() action=register
3869
	 * 2 - ::try_registration()
3870
	 * 3 - ::register()
3871
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3872
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3873
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3874
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3875
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3876
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3877
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3878
	 *       jetpack_id, jetpack_secret, jetpack_public
3879
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3880
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3881
	 * 5 - user logs in with WP.com account
3882
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3883
	 *		- Jetpack_Client_Server::authorize()
3884
	 *		- Jetpack_Client_Server::get_token()
3885
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3886
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3887
	 *			- which responds with access_token, token_type, scope
3888
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3889
	 *		- Jetpack::activate_default_modules()
3890
	 *     		- Deactivates deprecated plugins
3891
	 *     		- Activates all default modules
3892
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3893
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3894
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3895
	 *     Done!
3896
	 */
3897
3898
	/**
3899
	 * Handles the page load events for the Jetpack admin page
3900
	 */
3901
	function admin_page_load() {
3902
		$error = false;
3903
3904
		// Make sure we have the right body class to hook stylings for subpages off of.
3905
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3906
3907
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3908
			// Should only be used in intermediate redirects to preserve state across redirects
3909
			Jetpack::restate();
3910
		}
3911
3912
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3913
			// @todo: Add validation against a known whitelist
3914
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3915
			// User clicked in the iframe to link their accounts
3916
			if ( ! Jetpack::is_user_connected() ) {
3917
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3918
3919
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3920
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3921
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3922
3923
				if ( isset( $_GET['notes_iframe'] ) )
3924
					$connect_url .= '&notes_iframe';
3925
				wp_redirect( $connect_url );
3926
				exit;
3927
			} else {
3928
				if ( ! isset( $_GET['calypso_env'] ) ) {
3929
					Jetpack::state( 'message', 'already_authorized' );
3930
					wp_safe_redirect( Jetpack::admin_url() );
3931
					exit;
3932
				} else {
3933
					$connect_url = $this->build_connect_url( true, false, $from );
3934
					$connect_url .= '&already_authorized=true';
3935
					wp_redirect( $connect_url );
3936
					exit;
3937
				}
3938
			}
3939
		}
3940
3941
3942
		if ( isset( $_GET['action'] ) ) {
3943
			switch ( $_GET['action'] ) {
3944
			case 'authorize':
3945
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3946
					Jetpack::state( 'message', 'already_authorized' );
3947
					wp_safe_redirect( Jetpack::admin_url() );
3948
					exit;
3949
				}
3950
				Jetpack::log( 'authorize' );
3951
				$client_server = new Jetpack_Client_Server;
3952
				$client_server->client_authorize();
3953
				exit;
3954
			case 'register' :
3955
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3956
					$error = 'cheatin';
3957
					break;
3958
				}
3959
				check_admin_referer( 'jetpack-register' );
3960
				Jetpack::log( 'register' );
3961
				Jetpack::maybe_set_version_option();
3962
				$registered = Jetpack::try_registration();
3963
				if ( is_wp_error( $registered ) ) {
3964
					$error = $registered->get_error_code();
3965
					Jetpack::state( 'error', $error );
3966
					Jetpack::state( 'error', $registered->get_error_message() );
3967
3968
					/**
3969
					 * Jetpack registration Error.
3970
					 *
3971
					 * @since 7.5.0
3972
					 *
3973
					 * @param string|int $error The error code.
3974
					 * @param \WP_Error $registered The error object.
3975
					 */
3976
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3977
					break;
3978
				}
3979
3980
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3981
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3982
3983
				/**
3984
				 * Jetpack registration Success.
3985
				 *
3986
				 * @since 7.5.0
3987
				 *
3988
				 * @param string $from 'from' GET parameter;
3989
				 */
3990
				do_action( 'jetpack_connection_register_success', $from );
3991
3992
				$url = $this->build_connect_url( true, $redirect, $from );
3993
3994
				if ( ! empty( $_GET['onboarding'] ) ) {
3995
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3996
				}
3997
3998
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3999
					$url = add_query_arg( 'auth_approved', 'true', $url );
4000
				}
4001
4002
				wp_redirect( $url );
4003
				exit;
4004
			case 'activate' :
4005
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4006
					$error = 'cheatin';
4007
					break;
4008
				}
4009
4010
				$module = stripslashes( $_GET['module'] );
4011
				check_admin_referer( "jetpack_activate-$module" );
4012
				Jetpack::log( 'activate', $module );
4013
				if ( ! Jetpack::activate_module( $module ) ) {
4014
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4015
				}
4016
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4017
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4018
				exit;
4019
			case 'activate_default_modules' :
4020
				check_admin_referer( 'activate_default_modules' );
4021
				Jetpack::log( 'activate_default_modules' );
4022
				Jetpack::restate();
4023
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4024
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4025
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4026
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4027
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4028
				exit;
4029
			case 'disconnect' :
4030
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4031
					$error = 'cheatin';
4032
					break;
4033
				}
4034
4035
				check_admin_referer( 'jetpack-disconnect' );
4036
				Jetpack::log( 'disconnect' );
4037
				Jetpack::disconnect();
4038
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4039
				exit;
4040
			case 'reconnect' :
4041
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4042
					$error = 'cheatin';
4043
					break;
4044
				}
4045
4046
				check_admin_referer( 'jetpack-reconnect' );
4047
				Jetpack::log( 'reconnect' );
4048
				$this->disconnect();
4049
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4050
				exit;
4051 View Code Duplication
			case 'deactivate' :
4052
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4053
					$error = 'cheatin';
4054
					break;
4055
				}
4056
4057
				$modules = stripslashes( $_GET['module'] );
4058
				check_admin_referer( "jetpack_deactivate-$modules" );
4059
				foreach ( explode( ',', $modules ) as $module ) {
4060
					Jetpack::log( 'deactivate', $module );
4061
					Jetpack::deactivate_module( $module );
4062
					Jetpack::state( 'message', 'module_deactivated' );
4063
				}
4064
				Jetpack::state( 'module', $modules );
4065
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4066
				exit;
4067
			case 'unlink' :
4068
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4069
				check_admin_referer( 'jetpack-unlink' );
4070
				Jetpack::log( 'unlink' );
4071
				Connection_Manager::disconnect_user();
4072
				Jetpack::state( 'message', 'unlinked' );
4073
				if ( 'sub-unlink' == $redirect ) {
4074
					wp_safe_redirect( admin_url() );
4075
				} else {
4076
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4077
				}
4078
				exit;
4079
			case 'onboard' :
4080
				if ( ! current_user_can( 'manage_options' ) ) {
4081
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4082
				} else {
4083
					Jetpack::create_onboarding_token();
4084
					$url = $this->build_connect_url( true );
4085
4086
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4087
						$url = add_query_arg( 'onboarding', $token, $url );
4088
					}
4089
4090
					$calypso_env = $this->get_calypso_env();
4091
					if ( ! empty( $calypso_env ) ) {
4092
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4093
					}
4094
4095
					wp_redirect( $url );
4096
					exit;
4097
				}
4098
				exit;
4099
			default:
4100
				/**
4101
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4102
				 *
4103
				 * @since 2.6.0
4104
				 *
4105
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4106
				 */
4107
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4108
			}
4109
		}
4110
4111
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4112
			self::activate_new_modules( true );
4113
		}
4114
4115
		$message_code = Jetpack::state( 'message' );
4116
		if ( Jetpack::state( 'optin-manage' ) ) {
4117
			$activated_manage = $message_code;
4118
			$message_code = 'jetpack-manage';
4119
		}
4120
4121
		switch ( $message_code ) {
4122
		case 'jetpack-manage':
4123
			$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>';
4124
			if ( $activated_manage ) {
4125
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4126
			}
4127
			break;
4128
4129
		}
4130
4131
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4132
4133
		if ( ! empty( $deactivated_plugins ) ) {
4134
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4135
			$deactivated_titles  = array();
4136
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4137
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4138
					continue;
4139
				}
4140
4141
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4142
			}
4143
4144
			if ( $deactivated_titles ) {
4145
				if ( $this->message ) {
4146
					$this->message .= "<br /><br />\n";
4147
				}
4148
4149
				$this->message .= wp_sprintf(
4150
					_n(
4151
						'Jetpack contains the most recent version of the old %l plugin.',
4152
						'Jetpack contains the most recent versions of the old %l plugins.',
4153
						count( $deactivated_titles ),
4154
						'jetpack'
4155
					),
4156
					$deactivated_titles
4157
				);
4158
4159
				$this->message .= "<br />\n";
4160
4161
				$this->message .= _n(
4162
					'The old version has been deactivated and can be removed from your site.',
4163
					'The old versions have been deactivated and can be removed from your site.',
4164
					count( $deactivated_titles ),
4165
					'jetpack'
4166
				);
4167
			}
4168
		}
4169
4170
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4171
4172
		if ( $this->message || $this->error || $this->privacy_checks ) {
4173
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4174
		}
4175
4176
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4177
	}
4178
4179
	function admin_notices() {
4180
4181
		if ( $this->error ) {
4182
?>
4183
<div id="message" class="jetpack-message jetpack-err">
4184
	<div class="squeezer">
4185
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4186
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4187
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4188
<?php	endif; ?>
4189
	</div>
4190
</div>
4191
<?php
4192
		}
4193
4194
		if ( $this->message ) {
4195
?>
4196
<div id="message" class="jetpack-message">
4197
	<div class="squeezer">
4198
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4199
	</div>
4200
</div>
4201
<?php
4202
		}
4203
4204
		if ( $this->privacy_checks ) :
4205
			$module_names = $module_slugs = array();
4206
4207
			$privacy_checks = explode( ',', $this->privacy_checks );
4208
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4209
			foreach ( $privacy_checks as $module_slug ) {
4210
				$module = Jetpack::get_module( $module_slug );
4211
				if ( ! $module ) {
4212
					continue;
4213
				}
4214
4215
				$module_slugs[] = $module_slug;
4216
				$module_names[] = "<strong>{$module['name']}</strong>";
4217
			}
4218
4219
			$module_slugs = join( ',', $module_slugs );
4220
?>
4221
<div id="message" class="jetpack-message jetpack-err">
4222
	<div class="squeezer">
4223
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4224
		<p><?php
4225
			echo wp_kses(
4226
				wptexturize(
4227
					wp_sprintf(
4228
						_nx(
4229
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4230
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4231
							count( $privacy_checks ),
4232
							'%l = list of Jetpack module/feature names',
4233
							'jetpack'
4234
						),
4235
						$module_names
4236
					)
4237
				),
4238
				array( 'strong' => true )
4239
			);
4240
4241
			echo "\n<br />\n";
4242
4243
			echo wp_kses(
4244
				sprintf(
4245
					_nx(
4246
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4247
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4248
						count( $privacy_checks ),
4249
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4250
						'jetpack'
4251
					),
4252
					wp_nonce_url(
4253
						Jetpack::admin_url(
4254
							array(
4255
								'page'   => 'jetpack',
4256
								'action' => 'deactivate',
4257
								'module' => urlencode( $module_slugs ),
4258
							)
4259
						),
4260
						"jetpack_deactivate-$module_slugs"
4261
					),
4262
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4263
				),
4264
				array( 'a' => array( 'href' => true, 'title' => true ) )
4265
			);
4266
		?></p>
4267
	</div>
4268
</div>
4269
<?php endif;
4270
	}
4271
4272
	/**
4273
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4274
	 */
4275
	function stat( $group, $detail ) {
4276
		if ( ! isset( $this->stats[ $group ] ) )
4277
			$this->stats[ $group ] = array();
4278
		$this->stats[ $group ][] = $detail;
4279
	}
4280
4281
	/**
4282
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4283
	 */
4284
	function do_stats( $method = '' ) {
4285
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4286
			foreach ( $this->stats as $group => $stats ) {
4287
				if ( is_array( $stats ) && count( $stats ) ) {
4288
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4289
					if ( 'server_side' === $method ) {
4290
						self::do_server_side_stat( $args );
4291
					} else {
4292
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4293
					}
4294
				}
4295
				unset( $this->stats[ $group ] );
4296
			}
4297
		}
4298
	}
4299
4300
	/**
4301
	 * Runs stats code for a one-off, server-side.
4302
	 *
4303
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4304
	 *
4305
	 * @return bool If it worked.
4306
	 */
4307
	static function do_server_side_stat( $args ) {
4308
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4309
		if ( is_wp_error( $response ) )
4310
			return false;
4311
4312
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4313
			return false;
4314
4315
		return true;
4316
	}
4317
4318
	/**
4319
	 * Builds the stats url.
4320
	 *
4321
	 * @param $args array|string The arguments to append to the URL.
4322
	 *
4323
	 * @return string The URL to be pinged.
4324
	 */
4325
	static function build_stats_url( $args ) {
4326
		$defaults = array(
4327
			'v'    => 'wpcom2',
4328
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4329
		);
4330
		$args     = wp_parse_args( $args, $defaults );
4331
		/**
4332
		 * Filter the URL used as the Stats tracking pixel.
4333
		 *
4334
		 * @since 2.3.2
4335
		 *
4336
		 * @param string $url Base URL used as the Stats tracking pixel.
4337
		 */
4338
		$base_url = apply_filters(
4339
			'jetpack_stats_base_url',
4340
			'https://pixel.wp.com/g.gif'
4341
		);
4342
		$url      = add_query_arg( $args, $base_url );
4343
		return $url;
4344
	}
4345
4346
	/**
4347
	 * Get the role of the current user.
4348
	 *
4349
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4350
	 *
4351
	 * @access public
4352
	 * @static
4353
	 *
4354
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4355
	 */
4356
	public static function translate_current_user_to_role() {
4357
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4358
4359
		$roles = new Roles();
4360
		return $roles->translate_current_user_to_role();
4361
	}
4362
4363
	/**
4364
	 * Get the role of a particular user.
4365
	 *
4366
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4367
	 *
4368
	 * @access public
4369
	 * @static
4370
	 *
4371
	 * @param \WP_User $user User object.
4372
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4373
	 */
4374
	public static function translate_user_to_role( $user ) {
4375
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4376
4377
		$roles = new Roles();
4378
		return $roles->translate_user_to_role( $user );
4379
	}
4380
4381
	/**
4382
	 * Get the minimum capability for a role.
4383
	 *
4384
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4385
	 *
4386
	 * @access public
4387
	 * @static
4388
	 *
4389
	 * @param string $role Role name.
4390
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4391
	 */
4392
	public static function translate_role_to_cap( $role ) {
4393
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4394
4395
		$roles = new Roles();
4396
		return $roles->translate_role_to_cap( $role );
4397
	}
4398
4399
	static function sign_role( $role, $user_id = null ) {
4400
		if ( empty( $user_id ) ) {
4401
			$user_id = (int) get_current_user_id();
4402
		}
4403
4404
		if ( ! $user_id  ) {
4405
			return false;
4406
		}
4407
4408
		$token = Jetpack_Data::get_access_token();
4409
		if ( ! $token || is_wp_error( $token ) ) {
4410
			return false;
4411
		}
4412
4413
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4414
	}
4415
4416
4417
	/**
4418
	 * Builds a URL to the Jetpack connection auth page
4419
	 *
4420
	 * @since 3.9.5
4421
	 *
4422
	 * @param bool $raw If true, URL will not be escaped.
4423
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4424
	 *                              If string, will be a custom redirect.
4425
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4426
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4427
	 *
4428
	 * @return string Connect URL
4429
	 */
4430
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4431
		$site_id = Jetpack_Options::get_option( 'id' );
4432
		$blog_token = Jetpack_Data::get_access_token();
4433
4434
		if ( $register || ! $blog_token || ! $site_id ) {
4435
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4436
4437
			if ( ! empty( $redirect ) ) {
4438
				$url = add_query_arg(
4439
					'redirect',
4440
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4441
					$url
4442
				);
4443
			}
4444
4445
			if( is_network_admin() ) {
4446
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4447
			}
4448
		} else {
4449
4450
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4451
			// because otherwise this logic can get us in to a loop.
4452
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4453
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4454
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4455
4456
				$response = Client::wpcom_json_api_request_as_blog(
4457
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4458
					'1.1'
4459
				);
4460
4461
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4462
4463
					// Generating a register URL instead to refresh the existing token
4464
					return $this->build_connect_url( $raw, $redirect, $from, true );
4465
				}
4466
			}
4467
4468
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4469
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4470
			}
4471
4472
			$roles       = new Roles();
4473
			$role        = $roles->translate_current_user_to_role();
4474
			$signed_role = self::sign_role( $role );
4475
4476
			$user = wp_get_current_user();
4477
4478
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4479
			$redirect = $redirect
4480
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4481
				: $jetpack_admin_page;
4482
4483
			if( isset( $_REQUEST['is_multisite'] ) ) {
4484
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4485
			}
4486
4487
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4488
4489
			/**
4490
			 * Filter the type of authorization.
4491
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4492
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4493
			 *
4494
			 * @since 4.3.3
4495
			 *
4496
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4497
			 */
4498
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4499
4500
4501
			$tracks = new Tracking();
4502
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4503
4504
			$args = urlencode_deep(
4505
				array(
4506
					'response_type' => 'code',
4507
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4508
					'redirect_uri'  => add_query_arg(
4509
						array(
4510
							'action'   => 'authorize',
4511
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4512
							'redirect' => urlencode( $redirect ),
4513
						),
4514
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4515
					),
4516
					'state'         => $user->ID,
4517
					'scope'         => $signed_role,
4518
					'user_email'    => $user->user_email,
4519
					'user_login'    => $user->user_login,
4520
					'is_active'     => Jetpack::is_active(),
4521
					'jp_version'    => JETPACK__VERSION,
4522
					'auth_type'     => $auth_type,
4523
					'secret'        => $secrets['secret_1'],
4524
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4525
					'blogname'      => get_option( 'blogname' ),
4526
					'site_url'      => site_url(),
4527
					'home_url'      => home_url(),
4528
					'site_icon'     => get_site_icon_url(),
4529
					'site_lang'     => get_locale(),
4530
					'_ui'           => $tracks_identity['_ui'],
4531
					'_ut'           => $tracks_identity['_ut'],
4532
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4533
				)
4534
			);
4535
4536
			self::apply_activation_source_to_args( $args );
4537
4538
			$connection = self::connection();
4539
			$url = add_query_arg( $args, $connection->api_url( 'authorize' ) );
4540
		}
4541
4542
		if ( $from ) {
4543
			$url = add_query_arg( 'from', $from, $url );
4544
		}
4545
4546
		// Ensure that class to get the affiliate code is loaded
4547
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4548
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4549
		}
4550
		// Get affiliate code and add it to the URL
4551
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4552
4553
		$calypso_env = $this->get_calypso_env();
4554
4555
		if ( ! empty( $calypso_env ) ) {
4556
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4557
		}
4558
4559
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4560
	}
4561
4562
	/**
4563
	 * Get our assumed site creation date.
4564
	 * Calculated based on the earlier date of either:
4565
	 * - Earliest admin user registration date.
4566
	 * - Earliest date of post of any post type.
4567
	 *
4568
	 * @since 7.2.0
4569
	 *
4570
	 * @return string Assumed site creation date and time.
4571
	 */
4572 View Code Duplication
	public static function get_assumed_site_creation_date() {
4573
		$earliest_registered_users = get_users( array(
4574
			'role'    => 'administrator',
4575
			'orderby' => 'user_registered',
4576
			'order'   => 'ASC',
4577
			'fields'  => array( 'user_registered' ),
4578
			'number'  => 1,
4579
		) );
4580
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4581
4582
		$earliest_posts = get_posts( array(
4583
			'posts_per_page' => 1,
4584
			'post_type'      => 'any',
4585
			'post_status'    => 'any',
4586
			'orderby'        => 'date',
4587
			'order'          => 'ASC',
4588
		) );
4589
4590
		// If there are no posts at all, we'll count only on user registration date.
4591
		if ( $earliest_posts ) {
4592
			$earliest_post_date = $earliest_posts[0]->post_date;
4593
		} else {
4594
			$earliest_post_date = PHP_INT_MAX;
4595
		}
4596
4597
		return min( $earliest_registration_date, $earliest_post_date );
4598
	}
4599
4600 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4601
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4602
4603
		if ( $activation_source_name ) {
4604
			$args['_as'] = urlencode( $activation_source_name );
4605
		}
4606
4607
		if ( $activation_source_keyword ) {
4608
			$args['_ak'] = urlencode( $activation_source_keyword );
4609
		}
4610
	}
4611
4612
	function build_reconnect_url( $raw = false ) {
4613
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4614
		return $raw ? $url : esc_url( $url );
4615
	}
4616
4617
	public static function admin_url( $args = null ) {
4618
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4619
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4620
		return $url;
4621
	}
4622
4623
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4624
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4625
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4626
	}
4627
4628
	function dismiss_jetpack_notice() {
4629
4630
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4631
			return;
4632
		}
4633
4634
		switch( $_GET['jetpack-notice'] ) {
4635
			case 'dismiss':
4636
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4637
4638
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4639
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4640
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4641
				}
4642
				break;
4643
			case 'jetpack-protect-multisite-opt-out':
4644
4645
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4646
					// Don't show the banner again
4647
4648
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4649
					// redirect back to the page that had the notice
4650
					if ( wp_get_referer() ) {
4651
						wp_safe_redirect( wp_get_referer() );
4652
					} else {
4653
						// Take me to Jetpack
4654
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4655
					}
4656
				}
4657
				break;
4658
		}
4659
	}
4660
4661
	public static function sort_modules( $a, $b ) {
4662
		if ( $a['sort'] == $b['sort'] )
4663
			return 0;
4664
4665
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4666
	}
4667
4668
	function ajax_recheck_ssl() {
4669
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4670
		$result = Jetpack::permit_ssl( true );
4671
		wp_send_json( array(
4672
			'enabled' => $result,
4673
			'message' => get_transient( 'jetpack_https_test_message' )
4674
		) );
4675
	}
4676
4677
/* Client API */
4678
4679
	/**
4680
	 * Returns the requested Jetpack API URL
4681
	 *
4682
	 * @deprecated since 7.7
4683
	 * @return string
4684
	 */
4685
	public static function api_url( $relative_url ) {
4686
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4687
		$connection = self::connection();
4688
		return $connection->api_url( $relative_url );
4689
	}
4690
4691
	/**
4692
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4693
	 */
4694
	public static function fix_url_for_bad_hosts( $url ) {
4695
		if ( 0 !== strpos( $url, 'https://' ) ) {
4696
			return $url;
4697
		}
4698
4699
		switch ( JETPACK_CLIENT__HTTPS ) {
4700
			case 'ALWAYS' :
4701
				return $url;
4702
			case 'NEVER' :
4703
				return set_url_scheme( $url, 'http' );
4704
			// default : case 'AUTO' :
4705
		}
4706
4707
		// we now return the unmodified SSL URL by default, as a security precaution
4708
		return $url;
4709
	}
4710
4711
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4712
		// Default to a blog token.
4713
		$token_type = 'blog';
4714
4715
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4716
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4717
			if ( ! empty( $_GET['onboarding'] ) ) {
4718
				$jpo = $_GET;
4719
			} else {
4720
				$jpo = json_decode( $request_data, true );
4721
			}
4722
4723
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4724
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4725
4726
			if (
4727
				isset( $jpo_user )
4728
				&& isset( $jpo_token )
4729
				&& is_email( $jpo_user )
4730
				&& ctype_alnum( $jpo_token )
4731
				&& isset( $_GET['rest_route'] )
4732
				&& self::validate_onboarding_token_action(
4733
					$jpo_token,
4734
					$_GET['rest_route']
4735
				)
4736
			) {
4737
				$jp_user = get_user_by( 'email', $jpo_user );
4738
				if ( is_a( $jp_user, 'WP_User' ) ) {
4739
					wp_set_current_user( $jp_user->ID );
4740
					$user_can = is_multisite()
4741
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4742
						: current_user_can( 'manage_options' );
4743
					if ( $user_can ) {
4744
						$token_type = 'user';
4745
						$token->external_user_id = $jp_user->ID;
4746
					}
4747
				}
4748
			}
4749
4750
			$token_data['type']    = $token_type;
4751
			$token_data['user_id'] = $token->external_user_id;
4752
		}
4753
4754
		return $token_data;
4755
	}
4756
4757
	/**
4758
	 * Create a random secret for validating onboarding payload
4759
	 *
4760
	 * @return string Secret token
4761
	 */
4762
	public static function create_onboarding_token() {
4763
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4764
			$token = wp_generate_password( 32, false );
4765
			Jetpack_Options::update_option( 'onboarding', $token );
4766
		}
4767
4768
		return $token;
4769
	}
4770
4771
	/**
4772
	 * Remove the onboarding token
4773
	 *
4774
	 * @return bool True on success, false on failure
4775
	 */
4776
	public static function invalidate_onboarding_token() {
4777
		return Jetpack_Options::delete_option( 'onboarding' );
4778
	}
4779
4780
	/**
4781
	 * Validate an onboarding token for a specific action
4782
	 *
4783
	 * @return boolean True if token/action pair is accepted, false if not
4784
	 */
4785
	public static function validate_onboarding_token_action( $token, $action ) {
4786
		// Compare tokens, bail if tokens do not match
4787
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4788
			return false;
4789
		}
4790
4791
		// List of valid actions we can take
4792
		$valid_actions = array(
4793
			'/jetpack/v4/settings',
4794
		);
4795
4796
		// Whitelist the action
4797
		if ( ! in_array( $action, $valid_actions ) ) {
4798
			return false;
4799
		}
4800
4801
		return true;
4802
	}
4803
4804
	/**
4805
	 * Checks to see if the URL is using SSL to connect with Jetpack
4806
	 *
4807
	 * @since 2.3.3
4808
	 * @return boolean
4809
	 */
4810
	public static function permit_ssl( $force_recheck = false ) {
4811
		// Do some fancy tests to see if ssl is being supported
4812
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4813
			$message = '';
4814
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4815
				$ssl = 0;
4816
			} else {
4817
				switch ( JETPACK_CLIENT__HTTPS ) {
4818
					case 'NEVER':
4819
						$ssl = 0;
4820
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4821
						break;
4822
					case 'ALWAYS':
4823
					case 'AUTO':
4824
					default:
4825
						$ssl = 1;
4826
						break;
4827
				}
4828
4829
				// If it's not 'NEVER', test to see
4830
				if ( $ssl ) {
4831
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4832
						$ssl = 0;
4833
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4834
					} else {
4835
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4836
						if ( is_wp_error( $response ) ) {
4837
							$ssl = 0;
4838
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4839
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4840
							$ssl = 0;
4841
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4842
						}
4843
					}
4844
				}
4845
			}
4846
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4847
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4848
		}
4849
4850
		return (bool) $ssl;
4851
	}
4852
4853
	/*
4854
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4855
	 */
4856
	public function alert_auto_ssl_fail() {
4857
		if ( ! current_user_can( 'manage_options' ) )
4858
			return;
4859
4860
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4861
		?>
4862
4863
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4864
			<div class="jp-banner__content">
4865
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4866
				<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>
4867
				<p>
4868
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4869
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4870
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4871
				</p>
4872
				<p>
4873
					<?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' ),
4874
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4875
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4876
				</p>
4877
			</div>
4878
		</div>
4879
		<style>
4880
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4881
		</style>
4882
		<script type="text/javascript">
4883
			jQuery( document ).ready( function( $ ) {
4884
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4885
					var $this = $( this );
4886
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4887
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4888
					e.preventDefault();
4889
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4890
					$.post( ajaxurl, data )
4891
					  .done( function( response ) {
4892
					  	if ( response.enabled ) {
4893
					  		$( '#jetpack-ssl-warning' ).hide();
4894
					  	} else {
4895
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4896
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4897
					  	}
4898
					  }.bind( $this ) );
4899
				} );
4900
			} );
4901
		</script>
4902
4903
		<?php
4904
	}
4905
4906
	/**
4907
	 * Returns the Jetpack XML-RPC API
4908
	 *
4909
	 * @return string
4910
	 */
4911
	public static function xmlrpc_api_url() {
4912
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4913
		return untrailingslashit( $base ) . '/xmlrpc.php';
4914
	}
4915
4916
	public static function connection() {
4917
		return self::init()->connection_manager;
4918
	}
4919
4920
	/**
4921
	 * Creates two secret tokens and the end of life timestamp for them.
4922
	 *
4923
	 * Note these tokens are unique per call, NOT static per site for connecting.
4924
	 *
4925
	 * @since 2.6
4926
	 * @return array
4927
	 */
4928
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4929
		if ( false === $user_id ) {
4930
			$user_id = get_current_user_id();
4931
		}
4932
4933
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4934
	}
4935
4936
	public static function get_secrets( $action, $user_id ) {
4937
		$secrets = self::connection()->get_secrets( $action, $user_id );
4938
4939
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4940
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4941
		}
4942
4943
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4944
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4945
		}
4946
4947
		return $secrets;
4948
	}
4949
4950
	/**
4951
	 * @deprecated 7.5 Use Connection_Manager instead.
4952
	 *
4953
	 * @param $action
4954
	 * @param $user_id
4955
	 */
4956
	public static function delete_secrets( $action, $user_id ) {
4957
		return self::connection()->delete_secrets( $action, $user_id );
4958
	}
4959
4960
	/**
4961
	 * Builds the timeout limit for queries talking with the wpcom servers.
4962
	 *
4963
	 * Based on local php max_execution_time in php.ini
4964
	 *
4965
	 * @since 2.6
4966
	 * @return int
4967
	 * @deprecated
4968
	 **/
4969
	public function get_remote_query_timeout_limit() {
4970
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4971
		return Jetpack::get_max_execution_time();
4972
	}
4973
4974
	/**
4975
	 * Builds the timeout limit for queries talking with the wpcom servers.
4976
	 *
4977
	 * Based on local php max_execution_time in php.ini
4978
	 *
4979
	 * @since 5.4
4980
	 * @return int
4981
	 **/
4982
	public static function get_max_execution_time() {
4983
		$timeout = (int) ini_get( 'max_execution_time' );
4984
4985
		// Ensure exec time set in php.ini
4986
		if ( ! $timeout ) {
4987
			$timeout = 30;
4988
		}
4989
		return $timeout;
4990
	}
4991
4992
	/**
4993
	 * Sets a minimum request timeout, and returns the current timeout
4994
	 *
4995
	 * @since 5.4
4996
	 **/
4997 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
4998
		$timeout = self::get_max_execution_time();
4999
		if ( $timeout < $min_timeout ) {
5000
			$timeout = $min_timeout;
5001
			set_time_limit( $timeout );
5002
		}
5003
		return $timeout;
5004
	}
5005
5006
	/**
5007
	 * Takes the response from the Jetpack register new site endpoint and
5008
	 * verifies it worked properly.
5009
	 *
5010
	 * @since 2.6
5011
	 * @deprecated since 7.7.0
5012
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5013
	 **/
5014
	public function validate_remote_register_response() {
5015
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5016
	}
5017
5018
	/**
5019
	 * @return bool|WP_Error
5020
	 */
5021
	public static function register() {
5022
		$tracking = new Tracking();
5023
		$tracking->record_user_event( 'jpc_register_begin' );
5024
5025
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5026
5027
		$connection = self::connection();
5028
		$registration = $connection->register();
5029
5030
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5031
5032
		if ( ! $registration || is_wp_error( $registration ) ) {
5033
			return $registration;
5034
		}
5035
5036
		return true;
5037
	}
5038
5039
	/**
5040
	 * Filters the registration request body to include tracking properties.
5041
	 *
5042
	 * @param Array $properties
5043
	 * @return Array amended properties.
5044
	 */
5045
	public static function filter_register_request_body( $properties ) {
5046
		$tracking = new Tracking();
5047
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5048
5049
		return array_merge(
5050
			$properties,
5051
			array(
5052
				'_ui' => $tracks_identity['_ui'],
5053
				'_ut' => $tracks_identity['_ut'],
5054
			)
5055
		);
5056
	}
5057
5058
	/**
5059
	 * If the db version is showing something other that what we've got now, bump it to current.
5060
	 *
5061
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5062
	 */
5063
	public static function maybe_set_version_option() {
5064
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5065
		if ( JETPACK__VERSION != $version ) {
5066
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5067
5068
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5069
				/** This action is documented in class.jetpack.php */
5070
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5071
			}
5072
5073
			return true;
5074
		}
5075
		return false;
5076
	}
5077
5078
/* Client Server API */
5079
5080
	/**
5081
	 * Loads the Jetpack XML-RPC client
5082
	 */
5083
	public static function load_xml_rpc_client() {
5084
		require_once ABSPATH . WPINC . '/class-IXR.php';
5085
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5086
	}
5087
5088
	/**
5089
	 * Resets the saved authentication state in between testing requests.
5090
	 */
5091
	public function reset_saved_auth_state() {
5092
		$this->rest_authentication_status = null;
5093
		$this->connection_manager->reset_saved_auth_state();
5094
	}
5095
5096
	/**
5097
	 * Verifies the signature of the current request.
5098
	 *
5099
	 * @deprecated since 7.7.0
5100
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5101
	 *
5102
	 * @return false|array
5103
	 */
5104
	public function verify_xml_rpc_signature() {
5105
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5106
		return self::connection()->verify_xml_rpc_signature();
5107
	}
5108
5109
	/**
5110
	 * Verifies the signature of the current request.
5111
	 *
5112
	 * This function has side effects and should not be used. Instead,
5113
	 * use the memoized version `->verify_xml_rpc_signature()`.
5114
	 *
5115
	 * @deprecated since 7.7.0
5116
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5117
	 * @internal
5118
	 */
5119
	private function internal_verify_xml_rpc_signature() {
5120
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5121
	}
5122
5123
	/**
5124
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5125
	 *
5126
	 * @deprecated since 7.7.0
5127
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5128
	 *
5129
	 * @param \WP_User|mixed $user     User object if authenticated.
5130
	 * @param string         $username Username.
5131
	 * @param string         $password Password string.
5132
	 * @return \WP_User|mixed Authenticated user or error.
5133
	 */
5134
	public function authenticate_jetpack( $user, $username, $password ) {
5135
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5136
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5137
	}
5138
5139
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5140
	// Uses the existing XMLRPC request signing implementation.
5141
	function wp_rest_authenticate( $user ) {
5142
		if ( ! empty( $user ) ) {
5143
			// Another authentication method is in effect.
5144
			return $user;
5145
		}
5146
5147
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5148
			// Nothing to do for this authentication method.
5149
			return null;
5150
		}
5151
5152
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5153
			// Nothing to do for this authentication method.
5154
			return null;
5155
		}
5156
5157
		// Ensure that we always have the request body available.  At this
5158
		// point, the WP REST API code to determine the request body has not
5159
		// run yet.  That code may try to read from 'php://input' later, but
5160
		// this can only be done once per request in PHP versions prior to 5.6.
5161
		// So we will go ahead and perform this read now if needed, and save
5162
		// the request body where both the Jetpack signature verification code
5163
		// and the WP REST API code can see it.
5164
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5165
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5166
		}
5167
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5168
5169
		// Only support specific request parameters that have been tested and
5170
		// are known to work with signature verification.  A different method
5171
		// can be passed to the WP REST API via the '?_method=' parameter if
5172
		// needed.
5173
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5174
			$this->rest_authentication_status = new WP_Error(
5175
				'rest_invalid_request',
5176
				__( 'This request method is not supported.', 'jetpack' ),
5177
				array( 'status' => 400 )
5178
			);
5179
			return null;
5180
		}
5181
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5182
			$this->rest_authentication_status = new WP_Error(
5183
				'rest_invalid_request',
5184
				__( 'This request method does not support body parameters.', 'jetpack' ),
5185
				array( 'status' => 400 )
5186
			);
5187
			return null;
5188
		}
5189
5190
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5191
5192
		if (
5193
			$verified &&
5194
			isset( $verified['type'] ) &&
5195
			'user' === $verified['type'] &&
5196
			! empty( $verified['user_id'] )
5197
		) {
5198
			// Authentication successful.
5199
			$this->rest_authentication_status = true;
5200
			return $verified['user_id'];
5201
		}
5202
5203
		// Something else went wrong.  Probably a signature error.
5204
		$this->rest_authentication_status = new WP_Error(
5205
			'rest_invalid_signature',
5206
			__( 'The request is not signed correctly.', 'jetpack' ),
5207
			array( 'status' => 400 )
5208
		);
5209
		return null;
5210
	}
5211
5212
	/**
5213
	 * Report authentication status to the WP REST API.
5214
	 *
5215
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5216
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5217
	 */
5218
	public function wp_rest_authentication_errors( $value ) {
5219
		if ( $value !== null ) {
5220
			return $value;
5221
		}
5222
		return $this->rest_authentication_status;
5223
	}
5224
5225
	/**
5226
	 * Add our nonce to this request.
5227
	 *
5228
	 * @deprecated since 7.7.0
5229
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5230
	 *
5231
	 * @param int    $timestamp Timestamp of the request.
5232
	 * @param string $nonce     Nonce string.
5233
	 */
5234
	public function add_nonce( $timestamp, $nonce ) {
5235
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5236
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5237
	}
5238
5239
	/**
5240
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5241
	 * Capture it here so we can verify the signature later.
5242
	 *
5243
	 * @deprecated since 7.7.0
5244
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5245
	 *
5246
	 * @param array $methods XMLRPC methods.
5247
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5248
	 */
5249
	public function xmlrpc_methods( $methods ) {
5250
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5251
		return $this->connection_manager->xmlrpc_methods( $methods );
5252
	}
5253
5254
	/**
5255
	 * Register additional public XMLRPC methods.
5256
	 *
5257
	 * @deprecated since 7.7.0
5258
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5259
	 *
5260
	 * @param array $methods Public XMLRPC methods.
5261
	 * @return array Public XMLRPC methods, with the getOptions one.
5262
	 */
5263
	public function public_xmlrpc_methods( $methods ) {
5264
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5265
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5266
	}
5267
5268
	/**
5269
	 * Handles a getOptions XMLRPC method call.
5270
	 *
5271
	 * @deprecated since 7.7.0
5272
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5273
	 *
5274
	 * @param array $args method call arguments.
5275
	 * @return array an amended XMLRPC server options array.
5276
	 */
5277
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5278
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5279
		return $this->connection_manager->jetpack_getOptions( $args );
5280
	}
5281
5282
	/**
5283
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5284
	 *
5285
	 * @deprecated since 7.7.0
5286
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5287
	 *
5288
	 * @param array $options Standard Core options.
5289
	 * @return array Amended options.
5290
	 */
5291
	public function xmlrpc_options( $options ) {
5292
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5293
		return $this->connection_manager->xmlrpc_options( $options );
5294
	}
5295
5296
	/**
5297
	 * Cleans nonces that were saved when calling ::add_nonce.
5298
	 *
5299
	 * @deprecated since 7.7.0
5300
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5301
	 *
5302
	 * @param bool $all whether to clean even non-expired nonces.
5303
	 */
5304
	public static function clean_nonces( $all = false ) {
5305
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5306
		return self::connection()->clean_nonces( $all );
5307
	}
5308
5309
	/**
5310
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5311
	 * SET: state( $key, $value );
5312
	 * GET: $value = state( $key );
5313
	 *
5314
	 * @param string $key
5315
	 * @param string $value
5316
	 * @param bool $restate private
5317
	 */
5318
	public static function state( $key = null, $value = null, $restate = false ) {
5319
		static $state = array();
5320
		static $path, $domain;
5321
		if ( ! isset( $path ) ) {
5322
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5323
			$admin_url = Jetpack::admin_url();
5324
			$bits      = wp_parse_url( $admin_url );
5325
5326
			if ( is_array( $bits ) ) {
5327
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5328
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5329
			} else {
5330
				$path = $domain = null;
5331
			}
5332
		}
5333
5334
		// Extract state from cookies and delete cookies
5335
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5336
			$yum = $_COOKIE[ 'jetpackState' ];
5337
			unset( $_COOKIE[ 'jetpackState' ] );
5338
			foreach ( $yum as $k => $v ) {
5339
				if ( strlen( $v ) )
5340
					$state[ $k ] = $v;
5341
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5342
			}
5343
		}
5344
5345
		if ( $restate ) {
5346
			foreach ( $state as $k => $v ) {
5347
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5348
			}
5349
			return;
5350
		}
5351
5352
		// Get a state variable
5353
		if ( isset( $key ) && ! isset( $value ) ) {
5354
			if ( array_key_exists( $key, $state ) )
5355
				return $state[ $key ];
5356
			return null;
5357
		}
5358
5359
		// Set a state variable
5360
		if ( isset ( $key ) && isset( $value ) ) {
5361
			if( is_array( $value ) && isset( $value[0] ) ) {
5362
				$value = $value[0];
5363
			}
5364
			$state[ $key ] = $value;
5365
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5366
		}
5367
	}
5368
5369
	public static function restate() {
5370
		Jetpack::state( null, null, true );
5371
	}
5372
5373
	public static function check_privacy( $file ) {
5374
		static $is_site_publicly_accessible = null;
5375
5376
		if ( is_null( $is_site_publicly_accessible ) ) {
5377
			$is_site_publicly_accessible = false;
5378
5379
			Jetpack::load_xml_rpc_client();
5380
			$rpc = new Jetpack_IXR_Client();
5381
5382
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5383
			if ( $success ) {
5384
				$response = $rpc->getResponse();
5385
				if ( $response ) {
5386
					$is_site_publicly_accessible = true;
5387
				}
5388
			}
5389
5390
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5391
		}
5392
5393
		if ( $is_site_publicly_accessible ) {
5394
			return;
5395
		}
5396
5397
		$module_slug = self::get_module_slug( $file );
5398
5399
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5400
		if ( ! $privacy_checks ) {
5401
			$privacy_checks = $module_slug;
5402
		} else {
5403
			$privacy_checks .= ",$module_slug";
5404
		}
5405
5406
		Jetpack::state( 'privacy_checks', $privacy_checks );
5407
	}
5408
5409
	/**
5410
	 * Helper method for multicall XMLRPC.
5411
	 */
5412
	public static function xmlrpc_async_call() {
5413
		global $blog_id;
5414
		static $clients = array();
5415
5416
		$client_blog_id = is_multisite() ? $blog_id : 0;
5417
5418
		if ( ! isset( $clients[$client_blog_id] ) ) {
5419
			Jetpack::load_xml_rpc_client();
5420
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5421
			if ( function_exists( 'ignore_user_abort' ) ) {
5422
				ignore_user_abort( true );
5423
			}
5424
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5425
		}
5426
5427
		$args = func_get_args();
5428
5429
		if ( ! empty( $args[0] ) ) {
5430
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5431
		} elseif ( is_multisite() ) {
5432
			foreach ( $clients as $client_blog_id => $client ) {
5433
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5434
					continue;
5435
				}
5436
5437
				$switch_success = switch_to_blog( $client_blog_id, true );
5438
				if ( ! $switch_success ) {
5439
					continue;
5440
				}
5441
5442
				flush();
5443
				$client->query();
5444
5445
				restore_current_blog();
5446
			}
5447
		} else {
5448
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5449
				flush();
5450
				$clients[0]->query();
5451
			}
5452
		}
5453
	}
5454
5455
	public static function staticize_subdomain( $url ) {
5456
5457
		// Extract hostname from URL
5458
		$host = parse_url( $url, PHP_URL_HOST );
5459
5460
		// Explode hostname on '.'
5461
		$exploded_host = explode( '.', $host );
5462
5463
		// Retrieve the name and TLD
5464
		if ( count( $exploded_host ) > 1 ) {
5465
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5466
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5467
			// Rebuild domain excluding subdomains
5468
			$domain = $name . '.' . $tld;
5469
		} else {
5470
			$domain = $host;
5471
		}
5472
		// Array of Automattic domains
5473
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5474
5475
		// Return $url if not an Automattic domain
5476
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5477
			return $url;
5478
		}
5479
5480
		if ( is_ssl() ) {
5481
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5482
		}
5483
5484
		srand( crc32( basename( $url ) ) );
5485
		$static_counter = rand( 0, 2 );
5486
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5487
5488
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5489
	}
5490
5491
/* JSON API Authorization */
5492
5493
	/**
5494
	 * Handles the login action for Authorizing the JSON API
5495
	 */
5496
	function login_form_json_api_authorization() {
5497
		$this->verify_json_api_authorization_request();
5498
5499
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5500
5501
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5502
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5503
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5504
	}
5505
5506
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5507
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5508
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5509
			return $url;
5510
		}
5511
5512
		$parsed_url = parse_url( $url );
5513
		$url = strtok( $url, '?' );
5514
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5515
		if ( ! empty( $parsed_url['query'] ) )
5516
			$url .= "&{$parsed_url['query']}";
5517
5518
		return $url;
5519
	}
5520
5521
	// Make sure the POSTed request is handled by the same action
5522
	function preserve_action_in_login_form_for_json_api_authorization() {
5523
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5524
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5525
	}
5526
5527
	// If someone logs in to approve API access, store the Access Code in usermeta
5528
	function store_json_api_authorization_token( $user_login, $user ) {
5529
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5530
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5531
		$token = wp_generate_password( 32, false );
5532
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5533
	}
5534
5535
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5536
	function allow_wpcom_public_api_domain( $domains ) {
5537
		$domains[] = 'public-api.wordpress.com';
5538
		return $domains;
5539
	}
5540
5541
	static function is_redirect_encoded( $redirect_url ) {
5542
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5543
	}
5544
5545
	// Add all wordpress.com environments to the safe redirect whitelist
5546
	function allow_wpcom_environments( $domains ) {
5547
		$domains[] = 'wordpress.com';
5548
		$domains[] = 'wpcalypso.wordpress.com';
5549
		$domains[] = 'horizon.wordpress.com';
5550
		$domains[] = 'calypso.localhost';
5551
		return $domains;
5552
	}
5553
5554
	// Add the Access Code details to the public-api.wordpress.com redirect
5555
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5556
		return add_query_arg(
5557
			urlencode_deep(
5558
				array(
5559
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5560
					'jetpack-user-id' => (int) $user->ID,
5561
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5562
				)
5563
			),
5564
			$redirect_to
5565
		);
5566
	}
5567
5568
5569
	/**
5570
	 * Verifies the request by checking the signature
5571
	 *
5572
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5573
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5574
	 *
5575
	 * @param null|array $environment
5576
	 */
5577
	function verify_json_api_authorization_request( $environment = null ) {
5578
		$environment = is_null( $environment )
5579
			? $_REQUEST
5580
			: $environment;
5581
5582
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5583
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5584
		if ( ! $token || empty( $token->secret ) ) {
5585
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5586
		}
5587
5588
		$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' );
5589
5590
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5591
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5592
			/**
5593
			 * Jetpack authorisation request Error.
5594
			 *
5595
			 * @since 7.5.0
5596
			 *
5597
			 */
5598
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5599
			$die_error = sprintf(
5600
				/* translators: %s is a URL */
5601
				__( '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' ),
5602
				'https://jetpack.com/support/double-encoding/'
5603
			);
5604
		}
5605
5606
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5607
5608
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5609
			$signature = $jetpack_signature->sign_request(
5610
				$environment['token'],
5611
				$environment['timestamp'],
5612
				$environment['nonce'],
5613
				'',
5614
				'GET',
5615
				$environment['jetpack_json_api_original_query'],
5616
				null,
5617
				true
5618
			);
5619
		} else {
5620
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5621
		}
5622
5623
		if ( ! $signature ) {
5624
			wp_die( $die_error );
5625
		} else if ( is_wp_error( $signature ) ) {
5626
			wp_die( $die_error );
5627
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5628
			if ( is_ssl() ) {
5629
				// 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
5630
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5631
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5632
					wp_die( $die_error );
5633
				}
5634
			} else {
5635
				wp_die( $die_error );
5636
			}
5637
		}
5638
5639
		$timestamp = (int) $environment['timestamp'];
5640
		$nonce     = stripslashes( (string) $environment['nonce'] );
5641
5642
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
5643
			// De-nonce the nonce, at least for 5 minutes.
5644
			// 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)
5645
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5646
			if ( $old_nonce_time < time() - 300 ) {
5647
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5648
			}
5649
		}
5650
5651
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5652
		$data_filters = array(
5653
			'state'        => 'opaque',
5654
			'client_id'    => 'int',
5655
			'client_title' => 'string',
5656
			'client_image' => 'url',
5657
		);
5658
5659
		foreach ( $data_filters as $key => $sanitation ) {
5660
			if ( ! isset( $data->$key ) ) {
5661
				wp_die( $die_error );
5662
			}
5663
5664
			switch ( $sanitation ) {
5665
			case 'int' :
5666
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5667
				break;
5668
			case 'opaque' :
5669
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5670
				break;
5671
			case 'string' :
5672
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5673
				break;
5674
			case 'url' :
5675
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5676
				break;
5677
			}
5678
		}
5679
5680
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5681
			wp_die( $die_error );
5682
		}
5683
	}
5684
5685
	function login_message_json_api_authorization( $message ) {
5686
		return '<p class="message">' . sprintf(
5687
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5688
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5689
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5690
	}
5691
5692
	/**
5693
	 * Get $content_width, but with a <s>twist</s> filter.
5694
	 */
5695
	public static function get_content_width() {
5696
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5697
			? $GLOBALS['content_width']
5698
			: false;
5699
		/**
5700
		 * Filter the Content Width value.
5701
		 *
5702
		 * @since 2.2.3
5703
		 *
5704
		 * @param string $content_width Content Width value.
5705
		 */
5706
		return apply_filters( 'jetpack_content_width', $content_width );
5707
	}
5708
5709
	/**
5710
	 * Pings the WordPress.com Mirror Site for the specified options.
5711
	 *
5712
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5713
	 *
5714
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5715
	 */
5716
	public function get_cloud_site_options( $option_names ) {
5717
		$option_names = array_filter( (array) $option_names, 'is_string' );
5718
5719
		Jetpack::load_xml_rpc_client();
5720
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5721
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5722
		if ( $xml->isError() ) {
5723
			return array(
5724
				'error_code' => $xml->getErrorCode(),
5725
				'error_msg'  => $xml->getErrorMessage(),
5726
			);
5727
		}
5728
		$cloud_site_options = $xml->getResponse();
5729
5730
		return $cloud_site_options;
5731
	}
5732
5733
	/**
5734
	 * Checks if the site is currently in an identity crisis.
5735
	 *
5736
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5737
	 */
5738
	public static function check_identity_crisis() {
5739
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5740
			return false;
5741
		}
5742
5743
		return Jetpack_Options::get_option( 'sync_error_idc' );
5744
	}
5745
5746
	/**
5747
	 * Checks whether the home and siteurl specifically are whitelisted
5748
	 * Written so that we don't have re-check $key and $value params every time
5749
	 * we want to check if this site is whitelisted, for example in footer.php
5750
	 *
5751
	 * @since  3.8.0
5752
	 * @return bool True = already whitelisted False = not whitelisted
5753
	 */
5754
	public static function is_staging_site() {
5755
		$is_staging = false;
5756
5757
		$known_staging = array(
5758
			'urls' => array(
5759
				'#\.staging\.wpengine\.com$#i', // WP Engine
5760
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5761
				'#\.stage\.site$#i'             // DreamPress
5762
			),
5763
			'constants' => array(
5764
				'IS_WPE_SNAPSHOT',      // WP Engine
5765
				'KINSTA_DEV_ENV',       // Kinsta.com
5766
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5767
				'JETPACK_STAGING_MODE', // Generic
5768
			)
5769
		);
5770
		/**
5771
		 * Filters the flags of known staging sites.
5772
		 *
5773
		 * @since 3.9.0
5774
		 *
5775
		 * @param array $known_staging {
5776
		 *     An array of arrays that each are used to check if the current site is staging.
5777
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5778
		 *     @type array $constants PHP constants of known staging/developement environments.
5779
		 *  }
5780
		 */
5781
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5782
5783
		if ( isset( $known_staging['urls'] ) ) {
5784
			foreach ( $known_staging['urls'] as $url ){
5785
				if ( preg_match( $url, site_url() ) ) {
5786
					$is_staging = true;
5787
					break;
5788
				}
5789
			}
5790
		}
5791
5792
		if ( isset( $known_staging['constants'] ) ) {
5793
			foreach ( $known_staging['constants'] as $constant ) {
5794
				if ( defined( $constant ) && constant( $constant ) ) {
5795
					$is_staging = true;
5796
				}
5797
			}
5798
		}
5799
5800
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5801
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5802
			$is_staging = true;
5803
		}
5804
5805
		/**
5806
		 * Filters is_staging_site check.
5807
		 *
5808
		 * @since 3.9.0
5809
		 *
5810
		 * @param bool $is_staging If the current site is a staging site.
5811
		 */
5812
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5813
	}
5814
5815
	/**
5816
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5817
	 *
5818
	 * @since 4.4.0
5819
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5820
	 *
5821
	 * @return bool
5822
	 */
5823
	public static function validate_sync_error_idc_option() {
5824
		$is_valid = false;
5825
5826
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5827
		if ( false === $idc_allowed ) {
5828
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5829
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5830
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5831
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5832
				$transient_duration = HOUR_IN_SECONDS;
5833
			} else {
5834
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5835
				$idc_allowed = '1';
5836
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5837
			}
5838
5839
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5840
		}
5841
5842
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5843
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5844
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5845
			$local_options = self::get_sync_error_idc_option();
5846
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5847
				$is_valid = true;
5848
			}
5849
		}
5850
5851
		/**
5852
		 * Filters whether the sync_error_idc option is valid.
5853
		 *
5854
		 * @since 4.4.0
5855
		 *
5856
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5857
		 */
5858
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5859
5860
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5861
			// Since the option exists, and did not validate, delete it
5862
			Jetpack_Options::delete_option( 'sync_error_idc' );
5863
		}
5864
5865
		return $is_valid;
5866
	}
5867
5868
	/**
5869
	 * Normalizes a url by doing three things:
5870
	 *  - Strips protocol
5871
	 *  - Strips www
5872
	 *  - Adds a trailing slash
5873
	 *
5874
	 * @since 4.4.0
5875
	 * @param string $url
5876
	 * @return WP_Error|string
5877
	 */
5878
	public static function normalize_url_protocol_agnostic( $url ) {
5879
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5880
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5881
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5882
		}
5883
5884
		// Strip www and protocols
5885
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5886
		return $url;
5887
	}
5888
5889
	/**
5890
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5891
	 *
5892
	 * @since 4.4.0
5893
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5894
	 *
5895
	 * @param array $response
5896
	 * @return array Array of the local urls, wpcom urls, and error code
5897
	 */
5898
	public static function get_sync_error_idc_option( $response = array() ) {
5899
		// Since the local options will hit the database directly, store the values
5900
		// in a transient to allow for autoloading and caching on subsequent views.
5901
		$local_options = get_transient( 'jetpack_idc_local' );
5902
		if ( false === $local_options ) {
5903
			$local_options = array(
5904
				'home'    => Functions::home_url(),
5905
				'siteurl' => Functions::site_url(),
5906
			);
5907
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5908
		}
5909
5910
		$options = array_merge( $local_options, $response );
5911
5912
		$returned_values = array();
5913
		foreach( $options as $key => $option ) {
5914
			if ( 'error_code' === $key ) {
5915
				$returned_values[ $key ] = $option;
5916
				continue;
5917
			}
5918
5919
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5920
				continue;
5921
			}
5922
5923
			$returned_values[ $key ] = $normalized_url;
5924
		}
5925
5926
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5927
5928
		return $returned_values;
5929
	}
5930
5931
	/**
5932
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5933
	 * If set to true, the site will be put into staging mode.
5934
	 *
5935
	 * @since 4.3.2
5936
	 * @return bool
5937
	 */
5938
	public static function sync_idc_optin() {
5939
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5940
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5941
		} else {
5942
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5943
		}
5944
5945
		/**
5946
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5947
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5948
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5949
		 *
5950
		 * @since 4.3.2
5951
		 *
5952
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5953
		 */
5954
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5955
	}
5956
5957
	/**
5958
	 * Maybe Use a .min.css stylesheet, maybe not.
5959
	 *
5960
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5961
	 */
5962
	public static function maybe_min_asset( $url, $path, $plugin ) {
5963
		// Short out on things trying to find actual paths.
5964
		if ( ! $path || empty( $plugin ) ) {
5965
			return $url;
5966
		}
5967
5968
		$path = ltrim( $path, '/' );
5969
5970
		// Strip out the abspath.
5971
		$base = dirname( plugin_basename( $plugin ) );
5972
5973
		// Short out on non-Jetpack assets.
5974
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5975
			return $url;
5976
		}
5977
5978
		// File name parsing.
5979
		$file              = "{$base}/{$path}";
5980
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5981
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5982
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5983
		$extension         = array_shift( $file_name_parts_r );
5984
5985
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5986
			// Already pointing at the minified version.
5987
			if ( 'min' === $file_name_parts_r[0] ) {
5988
				return $url;
5989
			}
5990
5991
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5992
			if ( file_exists( $min_full_path ) ) {
5993
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5994
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5995
				if ( 'css' === $extension ) {
5996
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5997
					self::$min_assets[ $key ] = $path;
5998
				}
5999
			}
6000
		}
6001
6002
		return $url;
6003
	}
6004
6005
	/**
6006
	 * If the asset is minified, let's flag .min as the suffix.
6007
	 *
6008
	 * Attached to `style_loader_src` filter.
6009
	 *
6010
	 * @param string $tag The tag that would link to the external asset.
6011
	 * @param string $handle The registered handle of the script in question.
6012
	 * @param string $href The url of the asset in question.
6013
	 */
6014
	public static function set_suffix_on_min( $src, $handle ) {
6015
		if ( false === strpos( $src, '.min.css' ) ) {
6016
			return $src;
6017
		}
6018
6019
		if ( ! empty( self::$min_assets ) ) {
6020
			foreach ( self::$min_assets as $file => $path ) {
6021
				if ( false !== strpos( $src, $file ) ) {
6022
					wp_style_add_data( $handle, 'suffix', '.min' );
6023
					return $src;
6024
				}
6025
			}
6026
		}
6027
6028
		return $src;
6029
	}
6030
6031
	/**
6032
	 * Maybe inlines a stylesheet.
6033
	 *
6034
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6035
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6036
	 *
6037
	 * Attached to `style_loader_tag` filter.
6038
	 *
6039
	 * @param string $tag The tag that would link to the external asset.
6040
	 * @param string $handle The registered handle of the script in question.
6041
	 *
6042
	 * @return string
6043
	 */
6044
	public static function maybe_inline_style( $tag, $handle ) {
6045
		global $wp_styles;
6046
		$item = $wp_styles->registered[ $handle ];
6047
6048
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6049
			return $tag;
6050
		}
6051
6052
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6053
			$href = $matches[1];
6054
			// Strip off query string
6055
			if ( $pos = strpos( $href, '?' ) ) {
6056
				$href = substr( $href, 0, $pos );
6057
			}
6058
			// Strip off fragment
6059
			if ( $pos = strpos( $href, '#' ) ) {
6060
				$href = substr( $href, 0, $pos );
6061
			}
6062
		} else {
6063
			return $tag;
6064
		}
6065
6066
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6067
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6068
			return $tag;
6069
		}
6070
6071
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6072
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6073
			// And this isn't the pass that actually deals with the RTL version...
6074
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6075
				// Short out, as the RTL version will deal with it in a moment.
6076
				return $tag;
6077
			}
6078
		}
6079
6080
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6081
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6082
		if ( $css ) {
6083
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6084
			if ( empty( $item->extra['after'] ) ) {
6085
				wp_add_inline_style( $handle, $css );
6086
			} else {
6087
				array_unshift( $item->extra['after'], $css );
6088
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6089
			}
6090
		}
6091
6092
		return $tag;
6093
	}
6094
6095
	/**
6096
	 * Loads a view file from the views
6097
	 *
6098
	 * Data passed in with the $data parameter will be available in the
6099
	 * template file as $data['value']
6100
	 *
6101
	 * @param string $template - Template file to load
6102
	 * @param array $data - Any data to pass along to the template
6103
	 * @return boolean - If template file was found
6104
	 **/
6105
	public function load_view( $template, $data = array() ) {
6106
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6107
6108
		if( file_exists( $views_dir . $template ) ) {
6109
			require_once( $views_dir . $template );
6110
			return true;
6111
		}
6112
6113
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6114
		return false;
6115
	}
6116
6117
	/**
6118
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6119
	 */
6120
	public function deprecated_hooks() {
6121
		global $wp_filter;
6122
6123
		/*
6124
		 * Format:
6125
		 * deprecated_filter_name => replacement_name
6126
		 *
6127
		 * If there is no replacement, use null for replacement_name
6128
		 */
6129
		$deprecated_list = array(
6130
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6131
			'wpl_sharing_2014_1'                                     => null,
6132
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6133
			'jetpack_identity_crisis_options_to_check'               => null,
6134
			'update_option_jetpack_single_user_site'                 => null,
6135
			'audio_player_default_colors'                            => null,
6136
			'add_option_jetpack_featured_images_enabled'             => null,
6137
			'add_option_jetpack_update_details'                      => null,
6138
			'add_option_jetpack_updates'                             => null,
6139
			'add_option_jetpack_network_name'                        => null,
6140
			'add_option_jetpack_network_allow_new_registrations'     => null,
6141
			'add_option_jetpack_network_add_new_users'               => null,
6142
			'add_option_jetpack_network_site_upload_space'           => null,
6143
			'add_option_jetpack_network_upload_file_types'           => null,
6144
			'add_option_jetpack_network_enable_administration_menus' => null,
6145
			'add_option_jetpack_is_multi_site'                       => null,
6146
			'add_option_jetpack_is_main_network'                     => null,
6147
			'add_option_jetpack_main_network_site'                   => null,
6148
			'jetpack_sync_all_registered_options'                    => null,
6149
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6150
			'jetpack_is_post_mailable'                               => null,
6151
			'jetpack_seo_site_host'                                  => null,
6152
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6153
			'jetpack_holiday_snow_option_name'                       => null,
6154
			'jetpack_holiday_chance_of_snow'                         => null,
6155
			'jetpack_holiday_snow_js_url'                            => null,
6156
			'jetpack_is_holiday_snow_season'                         => null,
6157
			'jetpack_holiday_snow_option_updated'                    => null,
6158
			'jetpack_holiday_snowing'                                => null,
6159
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6160
			'jetpack_cache_plans'                                    => null,
6161
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6162
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6163
			'jetpack_enable_site_verification'                       => null,
6164
			'can_display_jetpack_manage_notice'                      => null,
6165
			// Removed in Jetpack 7.3.0
6166
			'atd_load_scripts'                                       => null,
6167
			'atd_http_post_timeout'                                  => null,
6168
			'atd_http_post_error'                                    => null,
6169
			'atd_service_domain'                                     => null,
6170
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6171
		);
6172
6173
		// This is a silly loop depth. Better way?
6174
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6175
			if ( has_action( $hook ) ) {
6176
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6177
					foreach( $values AS $hooked ) {
6178
						if ( is_callable( $hooked['function'] ) ) {
6179
							$function_name = 'an anonymous function';
6180
						} else {
6181
							$function_name = $hooked['function'];
6182
						}
6183
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6184
					}
6185
				}
6186
			}
6187
		}
6188
	}
6189
6190
	/**
6191
	 * Converts any url in a stylesheet, to the correct absolute url.
6192
	 *
6193
	 * Considerations:
6194
	 *  - Normal, relative URLs     `feh.png`
6195
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6196
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6197
	 *  - Absolute URLs             `http://domain.com/feh.png`
6198
	 *  - Domain root relative URLs `/feh.png`
6199
	 *
6200
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6201
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6202
	 *
6203
	 * @return mixed|string
6204
	 */
6205
	public static function absolutize_css_urls( $css, $css_file_url ) {
6206
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6207
		$css_dir = dirname( $css_file_url );
6208
		$p       = parse_url( $css_dir );
6209
		$domain  = sprintf(
6210
					'%1$s//%2$s%3$s%4$s',
6211
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6212
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6213
					$p['host'],
6214
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6215
				);
6216
6217
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6218
			$find = $replace = array();
6219
			foreach ( $matches as $match ) {
6220
				$url = trim( $match['path'], "'\" \t" );
6221
6222
				// If this is a data url, we don't want to mess with it.
6223
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6224
					continue;
6225
				}
6226
6227
				// If this is an absolute or protocol-agnostic url,
6228
				// we don't want to mess with it.
6229
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6230
					continue;
6231
				}
6232
6233
				switch ( substr( $url, 0, 1 ) ) {
6234
					case '/':
6235
						$absolute = $domain . $url;
6236
						break;
6237
					default:
6238
						$absolute = $css_dir . '/' . $url;
6239
				}
6240
6241
				$find[]    = $match[0];
6242
				$replace[] = sprintf( 'url("%s")', $absolute );
6243
			}
6244
			$css = str_replace( $find, $replace, $css );
6245
		}
6246
6247
		return $css;
6248
	}
6249
6250
	/**
6251
	 * This methods removes all of the registered css files on the front end
6252
	 * from Jetpack in favor of using a single file. In effect "imploding"
6253
	 * all the files into one file.
6254
	 *
6255
	 * Pros:
6256
	 * - Uses only ONE css asset connection instead of 15
6257
	 * - Saves a minimum of 56k
6258
	 * - Reduces server load
6259
	 * - Reduces time to first painted byte
6260
	 *
6261
	 * Cons:
6262
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6263
	 *		should not cause any issues with themes.
6264
	 * - Plugins/themes dequeuing styles no longer do anything. See
6265
	 *		jetpack_implode_frontend_css filter for a workaround
6266
	 *
6267
	 * For some situations developers may wish to disable css imploding and
6268
	 * instead operate in legacy mode where each file loads seperately and
6269
	 * can be edited individually or dequeued. This can be accomplished with
6270
	 * the following line:
6271
	 *
6272
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6273
	 *
6274
	 * @since 3.2
6275
	 **/
6276
	public function implode_frontend_css( $travis_test = false ) {
6277
		$do_implode = true;
6278
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6279
			$do_implode = false;
6280
		}
6281
6282
		// Do not implode CSS when the page loads via the AMP plugin.
6283
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6284
			$do_implode = false;
6285
		}
6286
6287
		/**
6288
		 * Allow CSS to be concatenated into a single jetpack.css file.
6289
		 *
6290
		 * @since 3.2.0
6291
		 *
6292
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6293
		 */
6294
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6295
6296
		// Do not use the imploded file when default behavior was altered through the filter
6297
		if ( ! $do_implode ) {
6298
			return;
6299
		}
6300
6301
		// We do not want to use the imploded file in dev mode, or if not connected
6302
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6303
			if ( ! $travis_test ) {
6304
				return;
6305
			}
6306
		}
6307
6308
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6309
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6310
			return;
6311
		}
6312
6313
		/*
6314
		 * Now we assume Jetpack is connected and able to serve the single
6315
		 * file.
6316
		 *
6317
		 * In the future there will be a check here to serve the file locally
6318
		 * or potentially from the Jetpack CDN
6319
		 *
6320
		 * For now:
6321
		 * - Enqueue a single imploded css file
6322
		 * - Zero out the style_loader_tag for the bundled ones
6323
		 * - Be happy, drink scotch
6324
		 */
6325
6326
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6327
6328
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6329
6330
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6331
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6332
	}
6333
6334
	function concat_remove_style_loader_tag( $tag, $handle ) {
6335
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6336
			$tag = '';
6337
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6338
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6339
			}
6340
		}
6341
6342
		return $tag;
6343
	}
6344
6345
	/**
6346
	 * Add an async attribute to scripts that can be loaded asynchronously.
6347
	 * https://www.w3schools.com/tags/att_script_async.asp
6348
	 *
6349
	 * @since 7.7.0
6350
	 *
6351
	 * @param string $tag    The <script> tag for the enqueued script.
6352
	 * @param string $handle The script's registered handle.
6353
	 * @param string $src    The script's source URL.
6354
	 */
6355
	public function script_add_async( $tag, $handle, $src ) {
6356
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6357
			return preg_replace( '/^<script /i', '<script async ', $tag );
6358
		}
6359
6360
		return $tag;
6361
	}
6362
6363
	/*
6364
	 * Check the heartbeat data
6365
	 *
6366
	 * Organizes the heartbeat data by severity.  For example, if the site
6367
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6368
	 *
6369
	 * Data will be added to "caution" array, if it either:
6370
	 *  - Out of date Jetpack version
6371
	 *  - Out of date WP version
6372
	 *  - Out of date PHP version
6373
	 *
6374
	 * $return array $filtered_data
6375
	 */
6376
	public static function jetpack_check_heartbeat_data() {
6377
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6378
6379
		$good    = array();
6380
		$caution = array();
6381
		$bad     = array();
6382
6383
		foreach ( $raw_data as $stat => $value ) {
6384
6385
			// Check jetpack version
6386
			if ( 'version' == $stat ) {
6387
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6388
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6389
					continue;
6390
				}
6391
			}
6392
6393
			// Check WP version
6394
			if ( 'wp-version' == $stat ) {
6395
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6396
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6397
					continue;
6398
				}
6399
			}
6400
6401
			// Check PHP version
6402
			if ( 'php-version' == $stat ) {
6403
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6404
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6405
					continue;
6406
				}
6407
			}
6408
6409
			// Check ID crisis
6410
			if ( 'identitycrisis' == $stat ) {
6411
				if ( 'yes' == $value ) {
6412
					$bad[ $stat ] = $value;
6413
					continue;
6414
				}
6415
			}
6416
6417
			// The rest are good :)
6418
			$good[ $stat ] = $value;
6419
		}
6420
6421
		$filtered_data = array(
6422
			'good'    => $good,
6423
			'caution' => $caution,
6424
			'bad'     => $bad
6425
		);
6426
6427
		return $filtered_data;
6428
	}
6429
6430
6431
	/*
6432
	 * This method is used to organize all options that can be reset
6433
	 * without disconnecting Jetpack.
6434
	 *
6435
	 * It is used in class.jetpack-cli.php to reset options
6436
	 *
6437
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6438
	 *
6439
	 * @return array of options to delete.
6440
	 */
6441
	public static function get_jetpack_options_for_reset() {
6442
		return Jetpack_Options::get_options_for_reset();
6443
	}
6444
6445
	/*
6446
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6447
	 * so we can bring them directly to their site in calypso.
6448
	 *
6449
	 * @param string | url
6450
	 * @return string | url without the guff
6451
	 */
6452
	public static function build_raw_urls( $url ) {
6453
		$strip_http = '/.*?:\/\//i';
6454
		$url = preg_replace( $strip_http, '', $url  );
6455
		$url = str_replace( '/', '::', $url );
6456
		return $url;
6457
	}
6458
6459
	/**
6460
	 * Stores and prints out domains to prefetch for page speed optimization.
6461
	 *
6462
	 * @param mixed $new_urls
6463
	 */
6464
	public static function dns_prefetch( $new_urls = null ) {
6465
		static $prefetch_urls = array();
6466
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6467
			echo "\r\n";
6468
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6469
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6470
			}
6471
		} elseif ( ! empty( $new_urls ) ) {
6472
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6473
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6474
			}
6475
			foreach ( (array) $new_urls as $this_new_url ) {
6476
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6477
			}
6478
			$prefetch_urls = array_unique( $prefetch_urls );
6479
		}
6480
	}
6481
6482
	public function wp_dashboard_setup() {
6483
		if ( self::is_active() ) {
6484
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6485
		}
6486
6487
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6488
			$jetpack_logo = new Jetpack_Logo();
6489
			$widget_title = sprintf(
6490
				wp_kses(
6491
					/* translators: Placeholder is a Jetpack logo. */
6492
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6493
					array( 'span' => array() )
6494
				),
6495
				$jetpack_logo->get_jp_emblem( true )
6496
			);
6497
6498
			wp_add_dashboard_widget(
6499
				'jetpack_summary_widget',
6500
				$widget_title,
6501
				array( __CLASS__, 'dashboard_widget' )
6502
			);
6503
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6504
6505
			// If we're inactive and not in development mode, sort our box to the top.
6506
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6507
				global $wp_meta_boxes;
6508
6509
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6510
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6511
6512
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6513
			}
6514
		}
6515
	}
6516
6517
	/**
6518
	 * @param mixed $result Value for the user's option
6519
	 * @return mixed
6520
	 */
6521
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6522
		if ( ! is_array( $sorted ) ) {
6523
			return $sorted;
6524
		}
6525
6526
		foreach ( $sorted as $box_context => $ids ) {
6527
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6528
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6529
				continue;
6530
			}
6531
6532
			$ids_array = explode( ',', $ids );
6533
			$key = array_search( 'dashboard_stats', $ids_array );
6534
6535
			if ( false !== $key ) {
6536
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6537
				$ids_array[ $key ] = 'jetpack_summary_widget';
6538
				$sorted[ $box_context ] = implode( ',', $ids_array );
6539
				// We've found it, stop searching, and just return.
6540
				break;
6541
			}
6542
		}
6543
6544
		return $sorted;
6545
	}
6546
6547
	public static function dashboard_widget() {
6548
		/**
6549
		 * Fires when the dashboard is loaded.
6550
		 *
6551
		 * @since 3.4.0
6552
		 */
6553
		do_action( 'jetpack_dashboard_widget' );
6554
	}
6555
6556
	public static function dashboard_widget_footer() {
6557
		?>
6558
		<footer>
6559
6560
		<div class="protect">
6561
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6562
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6563
				<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>
6564
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6565
				<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' ); ?>">
6566
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6567
				</a>
6568
			<?php else : ?>
6569
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6570
			<?php endif; ?>
6571
		</div>
6572
6573
		<div class="akismet">
6574
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6575
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6576
				<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>
6577
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6578
				<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">
6579
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6580
				</a>
6581
			<?php else : ?>
6582
				<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>
6583
			<?php endif; ?>
6584
		</div>
6585
6586
		</footer>
6587
		<?php
6588
	}
6589
6590
	/*
6591
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6592
	 */
6593
	function jetpack_icon_user_connected( $columns ) {
6594
		$columns['user_jetpack'] = '';
6595
		return $columns;
6596
	}
6597
6598
	/*
6599
	 * Show Jetpack icon if the user is linked.
6600
	 */
6601
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6602
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6603
			$jetpack_logo = new Jetpack_Logo();
6604
			$emblem_html = sprintf(
6605
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6606
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6607
				$jetpack_logo->get_jp_emblem()
6608
			);
6609
			return $emblem_html;
6610
		}
6611
6612
		return $val;
6613
	}
6614
6615
	/*
6616
	 * Style the Jetpack user column
6617
	 */
6618
	function jetpack_user_col_style() {
6619
		global $current_screen;
6620
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6621
			<style>
6622
				.fixed .column-user_jetpack {
6623
					width: 21px;
6624
				}
6625
				.jp-emblem-user-admin svg {
6626
					width: 20px;
6627
					height: 20px;
6628
				}
6629
				.jp-emblem-user-admin path {
6630
					fill: #00BE28;
6631
				}
6632
			</style>
6633
		<?php }
6634
	}
6635
6636
	/**
6637
	 * Checks if Akismet is active and working.
6638
	 *
6639
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6640
	 * that implied usage of methods present since more recent version.
6641
	 * See https://github.com/Automattic/jetpack/pull/9585
6642
	 *
6643
	 * @since  5.1.0
6644
	 *
6645
	 * @return bool True = Akismet available. False = Aksimet not available.
6646
	 */
6647
	public static function is_akismet_active() {
6648
		static $status = null;
6649
6650
		if ( ! is_null( $status ) ) {
6651
			return $status;
6652
		}
6653
6654
		// Check if a modern version of Akismet is active.
6655
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6656
			$status = false;
6657
			return $status;
6658
		}
6659
6660
		// Make sure there is a key known to Akismet at all before verifying key.
6661
		$akismet_key = Akismet::get_api_key();
6662
		if ( ! $akismet_key ) {
6663
			$status = false;
6664
			return $status;
6665
		}
6666
6667
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6668
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6669
6670
		// 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.
6671
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6672
		// We cache the result of the Akismet key verification for ten minutes.
6673
		if ( ! $akismet_key_state || $recheck ) {
6674
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6675
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6676
		}
6677
6678
		$status = 'valid' === $akismet_key_state;
6679
6680
		return $status;
6681
	}
6682
6683
	/**
6684
	 * @deprecated
6685
	 *
6686
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6687
	 */
6688
	public static function is_function_in_backtrace() {
6689
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6690
	}
6691
6692
	/**
6693
	 * Given a minified path, and a non-minified path, will return
6694
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6695
	 *
6696
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6697
	 * root Jetpack directory.
6698
	 *
6699
	 * @since 5.6.0
6700
	 *
6701
	 * @param string $min_path
6702
	 * @param string $non_min_path
6703
	 * @return string The URL to the file
6704
	 */
6705
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6706
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6707
	}
6708
6709
	/**
6710
	 * Checks for whether Jetpack Backup & Scan is enabled.
6711
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6712
	 * @return bool|int|mixed
6713
	 */
6714
	public static function is_rewind_enabled() {
6715
		if ( ! Jetpack::is_active() ) {
6716
			return false;
6717
		}
6718
6719
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6720
		if ( false === $rewind_enabled ) {
6721
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6722
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6723
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6724
				&& ! empty( $rewind_data['state'] )
6725
				&& 'active' === $rewind_data['state'] )
6726
				? 1
6727
				: 0;
6728
6729
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6730
		}
6731
		return $rewind_enabled;
6732
	}
6733
6734
	/**
6735
	 * Return Calypso environment value; used for developing Jetpack and pairing
6736
	 * it with different Calypso enrionments, such as localhost.
6737
	 *
6738
	 * @since 7.4.0
6739
	 *
6740
	 * @return string Calypso environment
6741
	 */
6742
	public static function get_calypso_env() {
6743
		if ( isset( $_GET['calypso_env'] ) ) {
6744
			return sanitize_key( $_GET['calypso_env'] );
6745
		}
6746
6747
		if ( getenv( 'CALYPSO_ENV' ) ) {
6748
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6749
		}
6750
6751
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6752
			return sanitize_key( CALYPSO_ENV );
6753
		}
6754
6755
		return '';
6756
	}
6757
6758
	/**
6759
	 * Checks whether or not TOS has been agreed upon.
6760
	 * Will return true if a user has clicked to register, or is already connected.
6761
	 */
6762
	public static function jetpack_tos_agreed() {
6763
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6764
	}
6765
6766
	/**
6767
	 * Handles activating default modules as well general cleanup for the new connection.
6768
	 *
6769
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6770
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6771
	 * @param boolean $send_state_messages          Whether to send state messages.
6772
	 * @return void
6773
	 */
6774
	public static function handle_post_authorization_actions(
6775
		$activate_sso = false,
6776
		$redirect_on_activation_error = false,
6777
		$send_state_messages = true
6778
	) {
6779
		$other_modules = $activate_sso
6780
			? array( 'sso' )
6781
			: array();
6782
6783
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6784
			Jetpack::delete_active_modules();
6785
6786
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
6787
		} else {
6788
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6789
		}
6790
6791
		// Since this is a fresh connection, be sure to clear out IDC options
6792
		Jetpack_IDC::clear_all_idc_options();
6793
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6794
6795
		// Start nonce cleaner
6796
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6797
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6798
6799
		if ( $send_state_messages ) {
6800
			Jetpack::state( 'message', 'authorized' );
6801
		}
6802
	}
6803
6804
	/**
6805
	 * Returns a boolean for whether backups UI should be displayed or not.
6806
	 *
6807
	 * @return bool Should backups UI be displayed?
6808
	 */
6809
	public static function show_backups_ui() {
6810
		/**
6811
		 * Whether UI for backups should be displayed.
6812
		 *
6813
		 * @since 6.5.0
6814
		 *
6815
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6816
		 */
6817
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6818
	}
6819
6820
	/*
6821
	 * Deprecated manage functions
6822
	 */
6823
	function prepare_manage_jetpack_notice() {
6824
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6825
	}
6826
	function manage_activate_screen() {
6827
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6828
	}
6829
	function admin_jetpack_manage_notice() {
6830
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6831
	}
6832
	function opt_out_jetpack_manage_url() {
6833
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6834
	}
6835
	function opt_in_jetpack_manage_url() {
6836
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6837
	}
6838
	function opt_in_jetpack_manage_notice() {
6839
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6840
	}
6841
	function can_display_jetpack_manage_notice() {
6842
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6843
	}
6844
6845
	/**
6846
	 * Clean leftoveruser meta.
6847
	 *
6848
	 * Delete Jetpack-related user meta when it is no longer needed.
6849
	 *
6850
	 * @since 7.3.0
6851
	 *
6852
	 * @param int $user_id User ID being updated.
6853
	 */
6854
	public static function user_meta_cleanup( $user_id ) {
6855
		$meta_keys = array(
6856
			// AtD removed from Jetpack 7.3
6857
			'AtD_options',
6858
			'AtD_check_when',
6859
			'AtD_guess_lang',
6860
			'AtD_ignored_phrases',
6861
		);
6862
6863
		foreach ( $meta_keys as $meta_key ) {
6864
			if ( get_user_meta( $user_id, $meta_key ) ) {
6865
				delete_user_meta( $user_id, $meta_key );
6866
			}
6867
		}
6868
	}
6869
6870
	function is_active_and_not_development_mode( $maybe ) {
6871
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6872
			return false;
6873
		}
6874
		return true;
6875
	}
6876
}
6877