Completed
Push — update/package-tracks-move-mor... ( d9eaf6...efacb9 )
by
unknown
101:45 queued 92:03
created

class.jetpack.php (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
6
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
7
use Automattic\Jetpack\Constants;
8
use Automattic\Jetpack\Tracking;
9
10
/*
11
Options:
12
jetpack_options (array)
13
	An array of options.
14
	@see Jetpack_Options::get_option_names()
15
16
jetpack_register (string)
17
	Temporary verification secrets.
18
19
jetpack_activated (int)
20
	1: the plugin was activated normally
21
	2: the plugin was activated on this site because of a network-wide activation
22
	3: the plugin was auto-installed
23
	4: the plugin was manually disconnected (but is still installed)
24
25
jetpack_active_modules (array)
26
	Array of active module slugs.
27
28
jetpack_do_activate (bool)
29
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
30
*/
31
32
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
33
34
class Jetpack {
35
	public $xmlrpc_server = null;
36
37
	private $xmlrpc_verification = null;
38
	private $rest_authentication_status = null;
39
40
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
41
42
	private $tracking;
43
44
	/**
45
	 * @var array The handles of styles that are concatenated into jetpack.css.
46
	 *
47
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
48
	 */
49
	public $concatenated_style_handles = array(
50
		'jetpack-carousel',
51
		'grunion.css',
52
		'the-neverending-homepage',
53
		'jetpack_likes',
54
		'jetpack_related-posts',
55
		'sharedaddy',
56
		'jetpack-slideshow',
57
		'presentations',
58
		'quiz',
59
		'jetpack-subscriptions',
60
		'jetpack-responsive-videos-style',
61
		'jetpack-social-menu',
62
		'tiled-gallery',
63
		'jetpack_display_posts_widget',
64
		'gravatar-profile-widget',
65
		'goodreads-widget',
66
		'jetpack_social_media_icons_widget',
67
		'jetpack-top-posts-widget',
68
		'jetpack_image_widget',
69
		'jetpack-my-community-widget',
70
		'jetpack-authors-widget',
71
		'wordads',
72
		'eu-cookie-law-style',
73
		'flickr-widget-style',
74
		'jetpack-search-widget',
75
		'jetpack-simple-payments-widget-style',
76
		'jetpack-widget-social-icons-styles',
77
	);
78
79
	/**
80
	 * Contains all assets that have had their URL rewritten to minified versions.
81
	 *
82
	 * @var array
83
	 */
84
	static $min_assets = array();
85
86
	public $plugins_to_deactivate = array(
87
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
88
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
89
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
90
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
91
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
92
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
93
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
94
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
95
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
96
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
97
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
98
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
99
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
100
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
101
	);
102
103
	static $capability_translations = array(
104
		'administrator' => 'manage_options',
105
		'editor'        => 'edit_others_posts',
106
		'author'        => 'publish_posts',
107
		'contributor'   => 'edit_posts',
108
		'subscriber'    => 'read',
109
	);
110
111
	/**
112
	 * Map of modules that have conflicts with plugins and should not be auto-activated
113
	 * if the plugins are active.  Used by filter_default_modules
114
	 *
115
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
116
	 * change `module-slug` and add this to your plugin:
117
	 *
118
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
119
	 * function my_jetpack_get_default_modules( $modules ) {
120
	 *     return array_diff( $modules, array( 'module-slug' ) );
121
	 * }
122
	 *
123
	 * @var array
124
	 */
125
	private $conflicting_plugins = array(
126
		'comments'          => array(
127
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
128
			'Disqus'                               => 'disqus-comment-system/disqus.php',
129
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
130
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
131
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
132
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
133
		),
134
		'comment-likes' => array(
135
			'Epoch'                                => 'epoch/plugincore.php',
136
		),
137
		'contact-form'      => array(
138
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
139
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
140
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
141
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
142
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
143
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
144
		),
145
		'minileven'         => array(
146
			'WPtouch'                              => 'wptouch/wptouch.php',
147
		),
148
		'latex'             => array(
149
			'LaTeX for WordPress'                  => 'latex/latex.php',
150
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
151
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
152
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
153
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
154
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
155
		),
156
		'protect'           => array(
157
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
158
			'Captcha'                              => 'captcha/captcha.php',
159
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
160
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
161
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
162
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
163
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
164
			'Security-protection'                  => 'security-protection/security-protection.php',
165
			'Login Security'                       => 'login-security/login-security.php',
166
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
167
			'Wordfence Security'                   => 'wordfence/wordfence.php',
168
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
169
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
170
		),
171
		'random-redirect'   => array(
172
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
173
		),
174
		'related-posts'     => array(
175
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
176
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
177
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
178
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
179
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
180
			'outbrain'                             => 'outbrain/outbrain.php',
181
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
182
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
183
		),
184
		'sharedaddy'        => array(
185
			'AddThis'                              => 'addthis/addthis_social_widget.php',
186
			'Add To Any'                           => 'add-to-any/add-to-any.php',
187
			'ShareThis'                            => 'share-this/sharethis.php',
188
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
189
		),
190
		'seo-tools' => array(
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'The SEO Framework'                    => 'autodescription/autodescription.php',
196
		),
197
		'verification-tools' => array(
198
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
199
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
200
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
201
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
202
			'The SEO Framework'                    => 'autodescription/autodescription.php',
203
		),
204
		'widget-visibility' => array(
205
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
206
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
207
		),
208
		'sitemaps' => array(
209
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
210
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
211
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
212
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
213
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
214
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'                    => 'autodescription/autodescription.php',
219
			'Sitemap'                              => 'sitemap/sitemap.php',
220
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
221
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
222
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
223
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
224
		),
225
		'lazy-images' => array(
226
			'Lazy Load'              => 'lazy-load/lazy-load.php',
227
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
228
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
229
		),
230
	);
231
232
	/**
233
	 * Plugins for which we turn off our Facebook OG Tags implementation.
234
	 *
235
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
236
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
237
	 *
238
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
239
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
240
	 */
241
	private $open_graph_conflicting_plugins = array(
242
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
243
		                                                         // 2 Click Social Media Buttons
244
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
245
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
246
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
247
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
248
		                                                         // Open Graph Meta Tags by Heateor
249
		'facebook/facebook.php',                                 // Facebook (official plugin)
250
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
251
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
252
		                                                         // Facebook Featured Image & OG Meta Tags
253
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
254
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
255
		                                                         // Facebook Open Graph Meta Tags for WordPress
256
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
257
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
258
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
259
		                                                         // Fedmich's Facebook Open Graph Meta
260
		'network-publisher/networkpub.php',                      // Network Publisher
261
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
262
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
263
		                                                         // NextScripts SNAP
264
		'og-tags/og-tags.php',                                   // OG Tags
265
		'opengraph/opengraph.php',                               // Open Graph
266
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
267
		                                                         // Open Graph Protocol Framework
268
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
269
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
270
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
271
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
272
		'sharepress/sharepress.php',                             // SharePress
273
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
274
		'social-discussions/social-discussions.php',             // Social Discussions
275
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
276
		'socialize/socialize.php',                               // Socialize
277
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
278
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
279
		                                                         // Tweet, Like, Google +1 and Share
280
		'wordbooker/wordbooker.php',                             // Wordbooker
281
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
282
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
283
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
284
		                                                         // WP Facebook Like Send & Open Graph Meta
285
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
286
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
287
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
288
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
289
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
290
	);
291
292
	/**
293
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
294
	 */
295
	private $twitter_cards_conflicting_plugins = array(
296
	//	'twitter/twitter.php',                       // The official one handles this on its own.
297
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
298
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
299
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
300
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
301
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
302
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
303
		'twitter-cards/twitter-cards.php',           // Twitter Cards
304
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
305
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
306
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
307
	);
308
309
	/**
310
	 * Message to display in admin_notice
311
	 * @var string
312
	 */
313
	public $message = '';
314
315
	/**
316
	 * Error to display in admin_notice
317
	 * @var string
318
	 */
319
	public $error = '';
320
321
	/**
322
	 * Modules that need more privacy description.
323
	 * @var string
324
	 */
325
	public $privacy_checks = '';
326
327
	/**
328
	 * Stats to record once the page loads
329
	 *
330
	 * @var array
331
	 */
332
	public $stats = array();
333
334
	/**
335
	 * Jetpack_Sync object
336
	 */
337
	public $sync;
338
339
	/**
340
	 * Verified data for JSON authorization request
341
	 */
342
	public $json_api_authorization_request = array();
343
344
	/**
345
	 * @var \Automattic\Jetpack\Connection\Manager
346
	 */
347
	protected $connection_manager;
348
349
	/**
350
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
351
	 */
352
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
353
354
	/**
355
	 * Holds the singleton instance of this class
356
	 * @since 2.3.3
357
	 * @var Jetpack
358
	 */
359
	static $instance = false;
360
361
	/**
362
	 * Singleton
363
	 * @static
364
	 */
365
	public static function init() {
366
		if ( ! self::$instance ) {
367
			self::$instance = new Jetpack;
368
369
			self::$instance->plugin_upgrade();
370
		}
371
372
		return self::$instance;
373
	}
374
375
	/**
376
	 * Must never be called statically
377
	 */
378
	function plugin_upgrade() {
379
		if ( Jetpack::is_active() ) {
380
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
381
			if ( JETPACK__VERSION != $version ) {
382
				// Prevent multiple upgrades at once - only a single process should trigger
383
				// an upgrade to avoid stampedes
384
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
385
					return;
386
				}
387
388
				// Set a short lock to prevent multiple instances of the upgrade
389
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
390
391
				// check which active modules actually exist and remove others from active_modules list
392
				$unfiltered_modules = Jetpack::get_active_modules();
393
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
394
				if ( array_diff( $unfiltered_modules, $modules ) ) {
395
					Jetpack::update_active_modules( $modules );
396
				}
397
398
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
399
400
				// Upgrade to 4.3.0
401
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
402
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
403
				}
404
405
				// Make sure Markdown for posts gets turned back on
406
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
407
					update_option( 'wpcom_publish_posts_with_markdown', true );
408
				}
409
410
				if ( did_action( 'wp_loaded' ) ) {
411
					self::upgrade_on_load();
412
				} else {
413
					add_action(
414
						'wp_loaded',
415
						array( __CLASS__, 'upgrade_on_load' )
416
					);
417
				}
418
			}
419
		}
420
	}
421
422
	/**
423
	 * Runs upgrade routines that need to have modules loaded.
424
	 */
425
	static function upgrade_on_load() {
426
427
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
428
		// This can happen in case Jetpack has been just upgraded and is
429
		// being initialized late during the page load. In this case we wait
430
		// until the next proper admin page load with Jetpack active.
431
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
432
			delete_transient( self::$plugin_upgrade_lock_key );
433
434
			return;
435
		}
436
437
		Jetpack::maybe_set_version_option();
438
439
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
440
			Jetpack_Widget_Conditions::migrate_post_type_rules();
441
		}
442
443
		if (
444
			class_exists( 'Jetpack_Sitemap_Manager' )
445
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
446
		) {
447
			do_action( 'jetpack_sitemaps_purge_data' );
448
		}
449
450
		delete_transient( self::$plugin_upgrade_lock_key );
451
	}
452
453
	/**
454
	 * Saves all the currently active modules to options.
455
	 * Also fires Action hooks for each newly activated and deactivated module.
456
	 *
457
	 * @param $modules Array Array of active modules to be saved in options.
458
	 *
459
	 * @return $success bool true for success, false for failure.
460
	 */
461
	static function update_active_modules( $modules ) {
462
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
463
		$active_modules       = Jetpack::get_active_modules();
464
		$new_active_modules   = array_diff( $modules, $current_modules );
465
		$new_inactive_modules = array_diff( $active_modules, $modules );
466
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
467
		$reindexed_modules    = array_values( $new_current_modules );
468
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
469
470
		foreach ( $new_active_modules as $module ) {
471
			/**
472
			 * Fires when a specific module is activated.
473
			 *
474
			 * @since 1.9.0
475
			 *
476
			 * @param string $module Module slug.
477
			 * @param boolean $success whether the module was activated. @since 4.2
478
			 */
479
			do_action( 'jetpack_activate_module', $module, $success );
480
			/**
481
			 * Fires when a module is activated.
482
			 * The dynamic part of the filter, $module, is the module slug.
483
			 *
484
			 * @since 1.9.0
485
			 *
486
			 * @param string $module Module slug.
487
			 */
488
			do_action( "jetpack_activate_module_$module", $module );
489
		}
490
491
		foreach ( $new_inactive_modules as $module ) {
492
			/**
493
			 * Fired after a module has been deactivated.
494
			 *
495
			 * @since 4.2.0
496
			 *
497
			 * @param string $module Module slug.
498
			 * @param boolean $success whether the module was deactivated.
499
			 */
500
			do_action( 'jetpack_deactivate_module', $module, $success );
501
			/**
502
			 * Fires when a module is deactivated.
503
			 * The dynamic part of the filter, $module, is the module slug.
504
			 *
505
			 * @since 1.9.0
506
			 *
507
			 * @param string $module Module slug.
508
			 */
509
			do_action( "jetpack_deactivate_module_$module", $module );
510
		}
511
512
		return $success;
513
	}
514
515
	static function delete_active_modules() {
516
		self::update_active_modules( array() );
517
	}
518
519
	/**
520
	 * Constructor.  Initializes WordPress hooks
521
	 */
522
	private function __construct() {
523
		/*
524
		 * Check for and alert any deprecated hooks
525
		 */
526
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
527
528
		/*
529
		 * Enable enhanced handling of previewing sites in Calypso
530
		 */
531
		if ( Jetpack::is_active() ) {
532
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
533
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
534
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
535
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
536
537
			$this->tracking = new Tracking( 'jetpack' );
538
			add_action( 'init', array( $this, 'track_jetpack_usage' ) );
539
		}
540
541
		/*
542
		 * Load things that should only be in Network Admin.
543
		 *
544
		 * For now blow away everything else until a more full
545
		 * understanding of what is needed at the network level is
546
		 * available
547
		 */
548
		if ( is_multisite() ) {
549
			Jetpack_Network::init();
550
		}
551
552
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
553
			return function() {
554
				return wp_generate_password( 32, false );
555
			};
556
		} );
557
558
		$this->connection_manager = new Connection_Manager( );
559
560
		/**
561
		 * Prepare Gutenberg Editor functionality
562
		 */
563
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
564
		Jetpack_Gutenberg::init();
565
		Jetpack_Gutenberg::load_independent_blocks();
566
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
567
568
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
569
570
		// Unlink user before deleting the user from .com
571
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
572
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
573
574
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
575
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
576
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
577
				define( 'XMLRPC_REQUEST', true );
578
			}
579
580
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
581
582
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
583
		}
584
585
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
586
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
587
588
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
589
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
590
591
			$this->require_jetpack_authentication();
592
593
			if ( Jetpack::is_active() ) {
594
				// Hack to preserve $HTTP_RAW_POST_DATA
595
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
596
597
				$signed = $this->verify_xml_rpc_signature();
598
				if ( $signed && ! is_wp_error( $signed ) ) {
599
					// The actual API methods.
600
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
601
				} else {
602
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
603
					// active Jetpack connection, so that additional users can link their account.
604
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
605
				}
606
			} else {
607
				new XMLRPC_Connector( $this->connection_manager );
608
609
				// The bootstrap API methods.
610
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
611
				$signed = $this->verify_xml_rpc_signature();
612
				if ( $signed && ! is_wp_error( $signed ) ) {
613
					// the jetpack Provision method is available for blog-token-signed requests
614
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
615
				}
616
			}
617
618
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
619
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
620
		} elseif (
621
			is_admin() &&
622
			isset( $_POST['action'] ) && (
623
				'jetpack_upload_file' == $_POST['action'] ||
624
				'jetpack_update_file' == $_POST['action']
625
			)
626
		) {
627
			$this->require_jetpack_authentication();
628
			$this->add_remote_request_handlers();
629
		} else {
630
			if ( Jetpack::is_active() ) {
631
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
632
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
633
			} else {
634
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
635
			}
636
		}
637
638
		if ( Jetpack::is_active() ) {
639
			Jetpack_Heartbeat::init();
640
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
641
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
642
				Jetpack_Search_Performance_Logger::init();
643
			}
644
		}
645
646
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
647
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
648
649
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
650
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
651
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
652
		}
653
654
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
655
656
		add_action( 'admin_init', array( $this, 'admin_init' ) );
657
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
658
659
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
660
661
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
662
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
663
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
664
665
		// returns HTTPS support status
666
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
667
668
		// JITM AJAX callback function
669
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
670
671
		// Universal ajax callback for all tracking events triggered via js
672
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
673
674
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
675
676
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
677
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
678
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
680
681
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
682
683
		/**
684
		 * These actions run checks to load additional files.
685
		 * They check for external files or plugins, so they need to run as late as possible.
686
		 */
687
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
688
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
689
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
690
691
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
692
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
693
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
694
695
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
696
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
697
698
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
700
701
		// A filter to control all just in time messages
702
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
703
704
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
705
706
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
707
		// We should make sure to only do this for front end links.
708
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
709
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
710
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
711
712
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
713
			//so they point moderation links on emails to Calypso
714
			jetpack_require_lib( 'functions.wp-notify' );
715
		}
716
717
		// Update the Jetpack plan from API on heartbeats
718
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
719
720
		/**
721
		 * This is the hack to concatenate all css files into one.
722
		 * For description and reasoning see the implode_frontend_css method
723
		 *
724
		 * Super late priority so we catch all the registered styles
725
		 */
726
		if( !is_admin() ) {
727
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
728
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
729
		}
730
731
732
		/**
733
		 * These are sync actions that we need to keep track of for jitms
734
		 */
735
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
736
737
		// Actually push the stats on shutdown.
738
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
739
			add_action( 'shutdown', array( $this, 'push_stats' ) );
740
		}
741
	}
742
743
	function initialize_rest_api_registration_connector() {
744
		new REST_Connector( $this->connection_manager );
745
	}
746
747
	/**
748
	 * This is ported over from the manage module, which has been deprecated and baked in here.
749
	 *
750
	 * @param $domains
751
	 */
752
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
753
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
754
	}
755
756
	/**
757
	 * Return $domains, with 'wordpress.com' appended.
758
	 * This is ported over from the manage module, which has been deprecated and baked in here.
759
	 *
760
	 * @param $domains
761
	 * @return array
762
	 */
763
	function allow_wpcom_domain( $domains ) {
764
		if ( empty( $domains ) ) {
765
			$domains = array();
766
		}
767
		$domains[] = 'wordpress.com';
768
		return array_unique( $domains );
769
	}
770
771
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
772
		$post = get_post( $post_id );
773
774
		if ( empty( $post ) ) {
775
			return $default_url;
776
		}
777
778
		$post_type = $post->post_type;
779
780
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
781
		// https://en.support.wordpress.com/custom-post-types/
782
		$allowed_post_types = array(
783
			'post' => 'post',
784
			'page' => 'page',
785
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
786
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
787
		);
788
789
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
790
			return $default_url;
791
		}
792
793
		$path_prefix = $allowed_post_types[ $post_type ];
794
795
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
796
797
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
798
	}
799
800
	function point_edit_comment_links_to_calypso( $url ) {
801
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
802
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
803
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
804
			Jetpack::build_raw_urls( get_home_url() ),
805
			$query_args['amp;c']
806
		) );
807
	}
808
809
	function jetpack_track_last_sync_callback( $params ) {
810
		/**
811
		 * Filter to turn off jitm caching
812
		 *
813
		 * @since 5.4.0
814
		 *
815
		 * @param bool false Whether to cache just in time messages
816
		 */
817
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
818
			return $params;
819
		}
820
821
		if ( is_array( $params ) && isset( $params[0] ) ) {
822
			$option = $params[0];
823
			if ( 'active_plugins' === $option ) {
824
				// use the cache if we can, but not terribly important if it gets evicted
825
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
826
			}
827
		}
828
829
		return $params;
830
	}
831
832
	function jetpack_connection_banner_callback() {
833
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
834
835
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
836
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
837
			wp_send_json_success();
838
		}
839
840
		wp_die();
841
	}
842
843
	/**
844
	 * Removes all XML-RPC methods that are not `jetpack.*`.
845
	 * Only used in our alternate XML-RPC endpoint, where we want to
846
	 * ensure that Core and other plugins' methods are not exposed.
847
	 *
848
	 * @param array $methods
849
	 * @return array filtered $methods
850
	 */
851
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
852
		$jetpack_methods = array();
853
854
		foreach ( $methods as $method => $callback ) {
855
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
856
				$jetpack_methods[ $method ] = $callback;
857
			}
858
		}
859
860
		return $jetpack_methods;
861
	}
862
863
	/**
864
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
865
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
866
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
867
	 * which is accessible via a different URI. Most of the below is copied directly
868
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
869
	 */
870
	function alternate_xmlrpc() {
871
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
872
		global $HTTP_RAW_POST_DATA;
873
874
		// Some browser-embedded clients send cookies. We don't want them.
875
		$_COOKIE = array();
876
877
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
878
		// but we can do it ourself.
879
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
880
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
881
		}
882
883
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
884
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
885
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
886
		}
887
888
		// phpcs:enable
889
890
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
891
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
892
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
893
894
		/**
895
		 * Filters the class used for handling XML-RPC requests.
896
		 *
897
		 * @since 3.1.0
898
		 *
899
		 * @param string $class The name of the XML-RPC server class.
900
		 */
901
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
902
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
903
904
		// Fire off the request
905
		nocache_headers();
906
		$wp_xmlrpc_server->serve_request();
907
908
		exit;
909
	}
910
911
	function jetpack_admin_ajax_tracks_callback() {
912
		// Check for nonce
913
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
914
			wp_die( 'Permissions check failed.' );
915
		}
916
917
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
918
			wp_die( 'No valid event name or type.' );
919
		}
920
921
		$tracks_data = array();
922
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
923
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
924
				$tracks_data = $_REQUEST['tracksEventProp'];
925
			} else {
926
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
927
			}
928
		}
929
930
		$this->tracking->record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
931
		wp_send_json_success();
932
		wp_die();
933
	}
934
935
	/**
936
	 * The callback for the JITM ajax requests.
937
	 */
938
	function jetpack_jitm_ajax_callback() {
939
		// Check for nonce
940
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
941
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
942
		}
943
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
944
			$module_slug = $_REQUEST['jitmModule'];
945
			Jetpack::log( 'activate', $module_slug );
946
			Jetpack::activate_module( $module_slug, false, false );
947
			Jetpack::state( 'message', 'no_message' );
948
949
			//A Jetpack module is being activated through a JITM, track it
950
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
951
			$this->do_stats( 'server_side' );
952
953
			wp_send_json_success();
954
		}
955
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
956
			// get the hide_jitm options array
957
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
958
			$module_slug = $_REQUEST['jitmModule'];
959
960
			if( ! $jetpack_hide_jitm ) {
961
				$jetpack_hide_jitm = array(
962
					$module_slug => 'hide'
963
				);
964
			} else {
965
				$jetpack_hide_jitm[$module_slug] = 'hide';
966
			}
967
968
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
969
970
			//jitm is being dismissed forever, track it
971
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
972
			$this->do_stats( 'server_side' );
973
974
			wp_send_json_success();
975
		}
976 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
977
			$module_slug = $_REQUEST['jitmModule'];
978
979
			// User went to WordPress.com, track this
980
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
981
			$this->do_stats( 'server_side' );
982
983
			wp_send_json_success();
984
		}
985 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
986
			$track = $_REQUEST['jitmModule'];
987
988
			// User is viewing JITM, track it.
989
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
990
			$this->do_stats( 'server_side' );
991
992
			wp_send_json_success();
993
		}
994
	}
995
996
	/**
997
	 * If there are any stats that need to be pushed, but haven't been, push them now.
998
	 */
999
	function push_stats() {
1000
		if ( ! empty( $this->stats ) ) {
1001
			$this->do_stats( 'server_side' );
1002
		}
1003
	}
1004
1005
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1006
		switch( $cap ) {
1007
			case 'jetpack_connect' :
1008
			case 'jetpack_reconnect' :
1009
				if ( Jetpack::is_development_mode() ) {
1010
					$caps = array( 'do_not_allow' );
1011
					break;
1012
				}
1013
				/**
1014
				 * Pass through. If it's not development mode, these should match disconnect.
1015
				 * Let users disconnect if it's development mode, just in case things glitch.
1016
				 */
1017
			case 'jetpack_disconnect' :
1018
				/**
1019
				 * In multisite, can individual site admins manage their own connection?
1020
				 *
1021
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1022
				 */
1023
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1024
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1025
						/**
1026
						 * We need to update the option name -- it's terribly unclear which
1027
						 * direction the override goes.
1028
						 *
1029
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1030
						 */
1031
						$caps = array( 'do_not_allow' );
1032
						break;
1033
					}
1034
				}
1035
1036
				$caps = array( 'manage_options' );
1037
				break;
1038
			case 'jetpack_manage_modules' :
1039
			case 'jetpack_activate_modules' :
1040
			case 'jetpack_deactivate_modules' :
1041
				$caps = array( 'manage_options' );
1042
				break;
1043
			case 'jetpack_configure_modules' :
1044
				$caps = array( 'manage_options' );
1045
				break;
1046
			case 'jetpack_manage_autoupdates' :
1047
				$caps = array(
1048
					'manage_options',
1049
					'update_plugins',
1050
				);
1051
				break;
1052
			case 'jetpack_network_admin_page':
1053
			case 'jetpack_network_settings_page':
1054
				$caps = array( 'manage_network_plugins' );
1055
				break;
1056
			case 'jetpack_network_sites_page':
1057
				$caps = array( 'manage_sites' );
1058
				break;
1059
			case 'jetpack_admin_page' :
1060
				if ( Jetpack::is_development_mode() ) {
1061
					$caps = array( 'manage_options' );
1062
					break;
1063
				} else {
1064
					$caps = array( 'read' );
1065
				}
1066
				break;
1067
			case 'jetpack_connect_user' :
1068
				if ( Jetpack::is_development_mode() ) {
1069
					$caps = array( 'do_not_allow' );
1070
					break;
1071
				}
1072
				$caps = array( 'read' );
1073
				break;
1074
		}
1075
		return $caps;
1076
	}
1077
1078
	function require_jetpack_authentication() {
1079
		// Don't let anyone authenticate
1080
		$_COOKIE = array();
1081
		remove_all_filters( 'authenticate' );
1082
		remove_all_actions( 'wp_login_failed' );
1083
1084
		if ( Jetpack::is_active() ) {
1085
			// Allow Jetpack authentication
1086
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1087
		}
1088
	}
1089
1090
	/**
1091
	 * Load language files
1092
	 * @action plugins_loaded
1093
	 */
1094
	public static function plugin_textdomain() {
1095
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1096
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1097
	}
1098
1099
	/**
1100
	 * Register assets for use in various modules and the Jetpack admin page.
1101
	 *
1102
	 * @uses wp_script_is, wp_register_script, plugins_url
1103
	 * @action wp_loaded
1104
	 * @return null
1105
	 */
1106
	public function register_assets() {
1107
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1108
			wp_register_script(
1109
				'spin',
1110
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1111
				false,
1112
				'1.3'
1113
			);
1114
		}
1115
1116
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1117
			wp_register_script(
1118
				'jquery.spin',
1119
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1120
				array( 'jquery', 'spin' ),
1121
				'1.3'
1122
			);
1123
		}
1124
1125 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1126
			wp_register_script(
1127
				'jetpack-gallery-settings',
1128
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1129
				array( 'media-views' ),
1130
				'20121225'
1131
			);
1132
		}
1133
1134
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1135
			wp_register_script(
1136
				'jetpack-twitter-timeline',
1137
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1138
				array( 'jquery' ),
1139
				'4.0.0',
1140
				true
1141
			);
1142
		}
1143
1144
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1145
			wp_register_script(
1146
				'jetpack-facebook-embed',
1147
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1148
				array( 'jquery' ),
1149
				null,
1150
				true
1151
			);
1152
1153
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1154
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1155
			if ( ! is_numeric( $fb_app_id ) ) {
1156
				$fb_app_id = '';
1157
			}
1158
			wp_localize_script(
1159
				'jetpack-facebook-embed',
1160
				'jpfbembed',
1161
				array(
1162
					'appid' => $fb_app_id,
1163
					'locale' => $this->get_locale(),
1164
				)
1165
			);
1166
		}
1167
1168
		/**
1169
		 * As jetpack_register_genericons is by default fired off a hook,
1170
		 * the hook may have already fired by this point.
1171
		 * So, let's just trigger it manually.
1172
		 */
1173
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1174
		jetpack_register_genericons();
1175
1176
		/**
1177
		 * Register the social logos
1178
		 */
1179
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1180
		jetpack_register_social_logos();
1181
1182 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1183
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1184
	}
1185
1186
	/**
1187
	 * Guess locale from language code.
1188
	 *
1189
	 * @param string $lang Language code.
1190
	 * @return string|bool
1191
	 */
1192 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1193
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1194
			return 'en_US';
1195
		}
1196
1197
		if ( ! class_exists( 'GP_Locales' ) ) {
1198
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1199
				return false;
1200
			}
1201
1202
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1203
		}
1204
1205
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1206
			// WP.com: get_locale() returns 'it'
1207
			$locale = GP_Locales::by_slug( $lang );
1208
		} else {
1209
			// Jetpack: get_locale() returns 'it_IT';
1210
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1211
		}
1212
1213
		if ( ! $locale ) {
1214
			return false;
1215
		}
1216
1217
		if ( empty( $locale->facebook_locale ) ) {
1218
			if ( empty( $locale->wp_locale ) ) {
1219
				return false;
1220
			} else {
1221
				// Facebook SDK is smart enough to fall back to en_US if a
1222
				// locale isn't supported. Since supported Facebook locales
1223
				// can fall out of sync, we'll attempt to use the known
1224
				// wp_locale value and rely on said fallback.
1225
				return $locale->wp_locale;
1226
			}
1227
		}
1228
1229
		return $locale->facebook_locale;
1230
	}
1231
1232
	/**
1233
	 * Get the locale.
1234
	 *
1235
	 * @return string|bool
1236
	 */
1237
	function get_locale() {
1238
		$locale = $this->guess_locale_from_lang( get_locale() );
1239
1240
		if ( ! $locale ) {
1241
			$locale = 'en_US';
1242
		}
1243
1244
		return $locale;
1245
	}
1246
1247
	/**
1248
	 * Device Pixels support
1249
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1250
	 */
1251
	function devicepx() {
1252
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1253
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1254
		}
1255
	}
1256
1257
	/**
1258
	 * Return the network_site_url so that .com knows what network this site is a part of.
1259
	 * @param  bool $option
1260
	 * @return string
1261
	 */
1262
	public function jetpack_main_network_site_option( $option ) {
1263
		return network_site_url();
1264
	}
1265
	/**
1266
	 * Network Name.
1267
	 */
1268
	static function network_name( $option = null ) {
1269
		global $current_site;
1270
		return $current_site->site_name;
1271
	}
1272
	/**
1273
	 * Does the network allow new user and site registrations.
1274
	 * @return string
1275
	 */
1276
	static function network_allow_new_registrations( $option = null ) {
1277
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1278
	}
1279
	/**
1280
	 * Does the network allow admins to add new users.
1281
	 * @return boolian
1282
	 */
1283
	static function network_add_new_users( $option = null ) {
1284
		return (bool) get_site_option( 'add_new_users' );
1285
	}
1286
	/**
1287
	 * File upload psace left per site in MB.
1288
	 *  -1 means NO LIMIT.
1289
	 * @return number
1290
	 */
1291
	static function network_site_upload_space( $option = null ) {
1292
		// value in MB
1293
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1294
	}
1295
1296
	/**
1297
	 * Network allowed file types.
1298
	 * @return string
1299
	 */
1300
	static function network_upload_file_types( $option = null ) {
1301
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1302
	}
1303
1304
	/**
1305
	 * Maximum file upload size set by the network.
1306
	 * @return number
1307
	 */
1308
	static function network_max_upload_file_size( $option = null ) {
1309
		// value in KB
1310
		return get_site_option( 'fileupload_maxk', 300 );
1311
	}
1312
1313
	/**
1314
	 * Lets us know if a site allows admins to manage the network.
1315
	 * @return array
1316
	 */
1317
	static function network_enable_administration_menus( $option = null ) {
1318
		return get_site_option( 'menu_items' );
1319
	}
1320
1321
	/**
1322
	 * If a user has been promoted to or demoted from admin, we need to clear the
1323
	 * jetpack_other_linked_admins transient.
1324
	 *
1325
	 * @since 4.3.2
1326
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1327
	 *
1328
	 * @param int    $user_id   The user ID whose role changed.
1329
	 * @param string $role      The new role.
1330
	 * @param array  $old_roles An array of the user's previous roles.
1331
	 */
1332
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1333
		if ( 'administrator' == $role
1334
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1335
			|| is_null( $old_roles )
1336
		) {
1337
			delete_transient( 'jetpack_other_linked_admins' );
1338
		}
1339
	}
1340
1341
	/**
1342
	 * Checks to see if there are any other users available to become primary
1343
	 * Users must both:
1344
	 * - Be linked to wpcom
1345
	 * - Be an admin
1346
	 *
1347
	 * @return mixed False if no other users are linked, Int if there are.
1348
	 */
1349
	static function get_other_linked_admins() {
1350
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1351
1352
		if ( false === $other_linked_users ) {
1353
			$admins = get_users( array( 'role' => 'administrator' ) );
1354
			if ( count( $admins ) > 1 ) {
1355
				$available = array();
1356
				foreach ( $admins as $admin ) {
1357
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1358
						$available[] = $admin->ID;
1359
					}
1360
				}
1361
1362
				$count_connected_admins = count( $available );
1363
				if ( count( $available ) > 1 ) {
1364
					$other_linked_users = $count_connected_admins;
1365
				} else {
1366
					$other_linked_users = 0;
1367
				}
1368
			} else {
1369
				$other_linked_users = 0;
1370
			}
1371
1372
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1373
		}
1374
1375
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1376
	}
1377
1378
	/**
1379
	 * Return whether we are dealing with a multi network setup or not.
1380
	 * The reason we are type casting this is because we want to avoid the situation where
1381
	 * the result is false since when is_main_network_option return false it cases
1382
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1383
	 * database which could be set to anything as opposed to what this function returns.
1384
	 * @param  bool  $option
1385
	 *
1386
	 * @return boolean
1387
	 */
1388
	public function is_main_network_option( $option ) {
1389
		// return '1' or ''
1390
		return (string) (bool) Jetpack::is_multi_network();
1391
	}
1392
1393
	/**
1394
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1395
	 *
1396
	 * @param  string  $option
1397
	 * @return boolean
1398
	 */
1399
	public function is_multisite( $option ) {
1400
		return (string) (bool) is_multisite();
1401
	}
1402
1403
	/**
1404
	 * Implemented since there is no core is multi network function
1405
	 * Right now there is no way to tell if we which network is the dominant network on the system
1406
	 *
1407
	 * @since  3.3
1408
	 * @return boolean
1409
	 */
1410
	public static function is_multi_network() {
1411
		global  $wpdb;
1412
1413
		// if we don't have a multi site setup no need to do any more
1414
		if ( ! is_multisite() ) {
1415
			return false;
1416
		}
1417
1418
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1419
		if ( $num_sites > 1 ) {
1420
			return true;
1421
		} else {
1422
			return false;
1423
		}
1424
	}
1425
1426
	/**
1427
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1428
	 * @return null
1429
	 */
1430
	function update_jetpack_main_network_site_option() {
1431
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1432
	}
1433
	/**
1434
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1435
	 *
1436
	 */
1437
	function update_jetpack_network_settings() {
1438
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1439
		// Only sync this info for the main network site.
1440
	}
1441
1442
	/**
1443
	 * Get back if the current site is single user site.
1444
	 *
1445
	 * @return bool
1446
	 */
1447
	public static function is_single_user_site() {
1448
		global $wpdb;
1449
1450 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1451
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1452
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1453
		}
1454
		return 1 === (int) $some_users;
1455
	}
1456
1457
	/**
1458
	 * Returns true if the site has file write access false otherwise.
1459
	 * @return string ( '1' | '0' )
1460
	 **/
1461
	public static function file_system_write_access() {
1462
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1463
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1464
		}
1465
1466
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1467
1468
		$filesystem_method = get_filesystem_method();
1469
		if ( $filesystem_method === 'direct' ) {
1470
			return 1;
1471
		}
1472
1473
		ob_start();
1474
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1475
		ob_end_clean();
1476
		if ( $filesystem_credentials_are_stored ) {
1477
			return 1;
1478
		}
1479
		return 0;
1480
	}
1481
1482
	/**
1483
	 * Finds out if a site is using a version control system.
1484
	 * @return string ( '1' | '0' )
1485
	 **/
1486
	public static function is_version_controlled() {
1487
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1488
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1489
	}
1490
1491
	/**
1492
	 * Determines whether the current theme supports featured images or not.
1493
	 * @return string ( '1' | '0' )
1494
	 */
1495
	public static function featured_images_enabled() {
1496
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1497
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1498
	}
1499
1500
	/**
1501
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1502
	 *
1503
	 * @deprecated 4.7 use get_avatar_url instead.
1504
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1505
	 * @param int $size Size of the avatar image
1506
	 * @param string $default URL to a default image to use if no avatar is available
1507
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1508
	 *
1509
	 * @return array
1510
	 */
1511
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1512
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1513
		return get_avatar_url( $id_or_email, array(
1514
			'size' => $size,
1515
			'default' => $default,
1516
			'force_default' => $force_display,
1517
		) );
1518
	}
1519
1520
	/**
1521
	 * jetpack_updates is saved in the following schema:
1522
	 *
1523
	 * array (
1524
	 *      'plugins'                       => (int) Number of plugin updates available.
1525
	 *      'themes'                        => (int) Number of theme updates available.
1526
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1527
	 *      'translations'                  => (int) Number of translation updates available.
1528
	 *      'total'                         => (int) Total of all available updates.
1529
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1530
	 * )
1531
	 * @return array
1532
	 */
1533
	public static function get_updates() {
1534
		$update_data = wp_get_update_data();
1535
1536
		// Stores the individual update counts as well as the total count.
1537
		if ( isset( $update_data['counts'] ) ) {
1538
			$updates = $update_data['counts'];
1539
		}
1540
1541
		// If we need to update WordPress core, let's find the latest version number.
1542 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1543
			$cur = get_preferred_from_update_core();
1544
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1545
				$updates['wp_update_version'] = $cur->current;
1546
			}
1547
		}
1548
		return isset( $updates ) ? $updates : array();
1549
	}
1550
1551
	public static function get_update_details() {
1552
		$update_details = array(
1553
			'update_core' => get_site_transient( 'update_core' ),
1554
			'update_plugins' => get_site_transient( 'update_plugins' ),
1555
			'update_themes' => get_site_transient( 'update_themes' ),
1556
		);
1557
		return $update_details;
1558
	}
1559
1560
	public static function refresh_update_data() {
1561
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1562
1563
	}
1564
1565
	public static function refresh_theme_data() {
1566
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1567
	}
1568
1569
	/**
1570
	 * Is Jetpack active?
1571
	 */
1572
	public static function is_active() {
1573
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1574
	}
1575
1576
	/**
1577
	 * Make an API call to WordPress.com for plan status
1578
	 *
1579
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1580
	 *
1581
	 * @return bool True if plan is updated, false if no update
1582
	 */
1583
	public static function refresh_active_plan_from_wpcom() {
1584
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1585
		return Jetpack_Plan::refresh_from_wpcom();
1586
	}
1587
1588
	/**
1589
	 * Get the plan that this Jetpack site is currently using
1590
	 *
1591
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1592
	 * @return array Active Jetpack plan details.
1593
	 */
1594
	public static function get_active_plan() {
1595
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1596
		return Jetpack_Plan::get();
1597
	}
1598
1599
	/**
1600
	 * Determine whether the active plan supports a particular feature
1601
	 *
1602
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1603
	 * @return bool True if plan supports feature, false if not.
1604
	 */
1605
	public static function active_plan_supports( $feature ) {
1606
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1607
		return Jetpack_Plan::supports( $feature );
1608
	}
1609
1610
	/**
1611
	 * Is Jetpack in development (offline) mode?
1612
	 */
1613
	public static function is_development_mode() {
1614
		$development_mode = false;
1615
1616
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1617
			$development_mode = JETPACK_DEV_DEBUG;
1618
		} elseif ( $site_url = site_url() ) {
1619
			$development_mode = false === strpos( $site_url, '.' );
1620
		}
1621
1622
		/**
1623
		 * Filters Jetpack's development mode.
1624
		 *
1625
		 * @see https://jetpack.com/support/development-mode/
1626
		 *
1627
		 * @since 2.2.1
1628
		 *
1629
		 * @param bool $development_mode Is Jetpack's development mode active.
1630
		 */
1631
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1632
		return $development_mode;
1633
	}
1634
1635
	/**
1636
	 * Whether the site is currently onboarding or not.
1637
	 * A site is considered as being onboarded if it currently has an onboarding token.
1638
	 *
1639
	 * @since 5.8
1640
	 *
1641
	 * @access public
1642
	 * @static
1643
	 *
1644
	 * @return bool True if the site is currently onboarding, false otherwise
1645
	 */
1646
	public static function is_onboarding() {
1647
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1648
	}
1649
1650
	/**
1651
	 * Determines reason for Jetpack development mode.
1652
	 */
1653
	public static function development_mode_trigger_text() {
1654
		if ( ! Jetpack::is_development_mode() ) {
1655
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1656
		}
1657
1658
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1659
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1660
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1661
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1662
		} else {
1663
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1664
		}
1665
1666
		return $notice;
1667
1668
	}
1669
	/**
1670
	* Get Jetpack development mode notice text and notice class.
1671
	*
1672
	* Mirrors the checks made in Jetpack::is_development_mode
1673
	*
1674
	*/
1675
	public static function show_development_mode_notice() {
1676 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1677
			$notice = sprintf(
1678
			/* translators: %s is a URL */
1679
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1680
				'https://jetpack.com/support/development-mode/'
1681
			);
1682
1683
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1684
1685
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1686
		}
1687
1688
		// Throw up a notice if using a development version and as for feedback.
1689
		if ( Jetpack::is_development_version() ) {
1690
			/* translators: %s is a URL */
1691
			$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/' );
1692
1693
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1694
		}
1695
		// Throw up a notice if using staging mode
1696
		if ( Jetpack::is_staging_site() ) {
1697
			/* translators: %s is a URL */
1698
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1699
1700
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1701
		}
1702
	}
1703
1704
	/**
1705
	 * Whether Jetpack's version maps to a public release, or a development version.
1706
	 */
1707
	public static function is_development_version() {
1708
		/**
1709
		 * Allows filtering whether this is a development version of Jetpack.
1710
		 *
1711
		 * This filter is especially useful for tests.
1712
		 *
1713
		 * @since 4.3.0
1714
		 *
1715
		 * @param bool $development_version Is this a develoment version of Jetpack?
1716
		 */
1717
		return (bool) apply_filters(
1718
			'jetpack_development_version',
1719
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1720
		);
1721
	}
1722
1723
	/**
1724
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1725
	 */
1726
	public static function is_user_connected( $user_id = false ) {
1727
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1728
		if ( ! $user_id ) {
1729
			return false;
1730
		}
1731
1732
		return (bool) Jetpack_Data::get_access_token( $user_id );
1733
	}
1734
1735
	/**
1736
	 * Get the wpcom user data of the current|specified connected user.
1737
	 */
1738
	public static function get_connected_user_data( $user_id = null ) {
1739
		if ( ! $user_id ) {
1740
			$user_id = get_current_user_id();
1741
		}
1742
1743
		$transient_key = "jetpack_connected_user_data_$user_id";
1744
1745
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1746
			return $cached_user_data;
1747
		}
1748
1749
		Jetpack::load_xml_rpc_client();
1750
		$xml = new Jetpack_IXR_Client( array(
1751
			'user_id' => $user_id,
1752
		) );
1753
		$xml->query( 'wpcom.getUser' );
1754
		if ( ! $xml->isError() ) {
1755
			$user_data = $xml->getResponse();
1756
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1757
			return $user_data;
1758
		}
1759
1760
		return false;
1761
	}
1762
1763
	/**
1764
	 * Get the wpcom email of the current|specified connected user.
1765
	 */
1766 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1767
		if ( ! $user_id ) {
1768
			$user_id = get_current_user_id();
1769
		}
1770
		Jetpack::load_xml_rpc_client();
1771
		$xml = new Jetpack_IXR_Client( array(
1772
			'user_id' => $user_id,
1773
		) );
1774
		$xml->query( 'wpcom.getUserEmail' );
1775
		if ( ! $xml->isError() ) {
1776
			return $xml->getResponse();
1777
		}
1778
		return false;
1779
	}
1780
1781
	/**
1782
	 * Get the wpcom email of the master user.
1783
	 */
1784
	public static function get_master_user_email() {
1785
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1786
		if ( $master_user_id ) {
1787
			return self::get_connected_user_email( $master_user_id );
1788
		}
1789
		return '';
1790
	}
1791
1792
	function current_user_is_connection_owner() {
1793
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1794
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1795
	}
1796
1797
	/**
1798
	 * Gets current user IP address.
1799
	 *
1800
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1801
	 *
1802
	 * @return string                  Current user IP address.
1803
	 */
1804
	public static function current_user_ip( $check_all_headers = false ) {
1805
		if ( $check_all_headers ) {
1806
			foreach ( array(
1807
				'HTTP_CF_CONNECTING_IP',
1808
				'HTTP_CLIENT_IP',
1809
				'HTTP_X_FORWARDED_FOR',
1810
				'HTTP_X_FORWARDED',
1811
				'HTTP_X_CLUSTER_CLIENT_IP',
1812
				'HTTP_FORWARDED_FOR',
1813
				'HTTP_FORWARDED',
1814
				'HTTP_VIA',
1815
			) as $key ) {
1816
				if ( ! empty( $_SERVER[ $key ] ) ) {
1817
					return $_SERVER[ $key ];
1818
				}
1819
			}
1820
		}
1821
1822
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1823
	}
1824
1825
	/**
1826
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1827
	 */
1828
	function extra_oembed_providers() {
1829
		// Cloudup: https://dev.cloudup.com/#oembed
1830
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1831
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1832
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1833
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1834
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1835
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1836
	}
1837
1838
	/**
1839
	 * Synchronize connected user role changes
1840
	 */
1841
	function user_role_change( $user_id ) {
1842
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1843
		Jetpack_Sync_Users::user_role_change( $user_id );
1844
	}
1845
1846
	/**
1847
	 * Loads the currently active modules.
1848
	 */
1849
	public static function load_modules() {
1850
		if (
1851
			! self::is_active()
1852
			&& ! self::is_development_mode()
1853
			&& ! self::is_onboarding()
1854
			&& (
1855
				! is_multisite()
1856
				|| ! get_site_option( 'jetpack_protect_active' )
1857
			)
1858
		) {
1859
			return;
1860
		}
1861
1862
		$version = Jetpack_Options::get_option( 'version' );
1863 View Code Duplication
		if ( ! $version ) {
1864
			$version = $old_version = JETPACK__VERSION . ':' . time();
1865
			/** This action is documented in class.jetpack.php */
1866
			do_action( 'updating_jetpack_version', $version, false );
1867
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1868
		}
1869
		list( $version ) = explode( ':', $version );
1870
1871
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1872
1873
		$modules_data = array();
1874
1875
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1876
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1877
			$updated_modules = array();
1878
			foreach ( $modules as $module ) {
1879
				$modules_data[ $module ] = Jetpack::get_module( $module );
1880
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1881
					continue;
1882
				}
1883
1884
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1885
					continue;
1886
				}
1887
1888
				$updated_modules[] = $module;
1889
			}
1890
1891
			$modules = array_diff( $modules, $updated_modules );
1892
		}
1893
1894
		$is_development_mode = Jetpack::is_development_mode();
1895
1896
		foreach ( $modules as $index => $module ) {
1897
			// If we're in dev mode, disable modules requiring a connection
1898
			if ( $is_development_mode ) {
1899
				// Prime the pump if we need to
1900
				if ( empty( $modules_data[ $module ] ) ) {
1901
					$modules_data[ $module ] = Jetpack::get_module( $module );
1902
				}
1903
				// If the module requires a connection, but we're in local mode, don't include it.
1904
				if ( $modules_data[ $module ]['requires_connection'] ) {
1905
					continue;
1906
				}
1907
			}
1908
1909
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1910
				continue;
1911
			}
1912
1913
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1914
				unset( $modules[ $index ] );
1915
				self::update_active_modules( array_values( $modules ) );
1916
				continue;
1917
			}
1918
1919
			/**
1920
			 * Fires when a specific module is loaded.
1921
			 * The dynamic part of the hook, $module, is the module slug.
1922
			 *
1923
			 * @since 1.1.0
1924
			 */
1925
			do_action( 'jetpack_module_loaded_' . $module );
1926
		}
1927
1928
		/**
1929
		 * Fires when all the modules are loaded.
1930
		 *
1931
		 * @since 1.1.0
1932
		 */
1933
		do_action( 'jetpack_modules_loaded' );
1934
1935
		// 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.
1936
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1937
	}
1938
1939
	/**
1940
	 * Check if Jetpack's REST API compat file should be included
1941
	 * @action plugins_loaded
1942
	 * @return null
1943
	 */
1944
	public function check_rest_api_compat() {
1945
		/**
1946
		 * Filters the list of REST API compat files to be included.
1947
		 *
1948
		 * @since 2.2.5
1949
		 *
1950
		 * @param array $args Array of REST API compat files to include.
1951
		 */
1952
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1953
1954
		if ( function_exists( 'bbpress' ) )
1955
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1956
1957
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1958
			require_once $_jetpack_rest_api_compat_include;
1959
	}
1960
1961
	/**
1962
	 * Gets all plugins currently active in values, regardless of whether they're
1963
	 * traditionally activated or network activated.
1964
	 *
1965
	 * @todo Store the result in core's object cache maybe?
1966
	 */
1967
	public static function get_active_plugins() {
1968
		$active_plugins = (array) get_option( 'active_plugins', array() );
1969
1970
		if ( is_multisite() ) {
1971
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1972
			// whereas active_plugins stores them in the values.
1973
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1974
			if ( $network_plugins ) {
1975
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1976
			}
1977
		}
1978
1979
		sort( $active_plugins );
1980
1981
		return array_unique( $active_plugins );
1982
	}
1983
1984
	/**
1985
	 * Gets and parses additional plugin data to send with the heartbeat data
1986
	 *
1987
	 * @since 3.8.1
1988
	 *
1989
	 * @return array Array of plugin data
1990
	 */
1991
	public static function get_parsed_plugin_data() {
1992
		if ( ! function_exists( 'get_plugins' ) ) {
1993
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1994
		}
1995
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1996
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1997
		$active_plugins = Jetpack::get_active_plugins();
1998
1999
		$plugins = array();
2000
		foreach ( $all_plugins as $path => $plugin_data ) {
2001
			$plugins[ $path ] = array(
2002
					'is_active' => in_array( $path, $active_plugins ),
2003
					'file'      => $path,
2004
					'name'      => $plugin_data['Name'],
2005
					'version'   => $plugin_data['Version'],
2006
					'author'    => $plugin_data['Author'],
2007
			);
2008
		}
2009
2010
		return $plugins;
2011
	}
2012
2013
	/**
2014
	 * Gets and parses theme data to send with the heartbeat data
2015
	 *
2016
	 * @since 3.8.1
2017
	 *
2018
	 * @return array Array of theme data
2019
	 */
2020
	public static function get_parsed_theme_data() {
2021
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2022
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2023
2024
		$themes = array();
2025
		foreach ( $all_themes as $slug => $theme_data ) {
2026
			$theme_headers = array();
2027
			foreach ( $header_keys as $header_key ) {
2028
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2029
			}
2030
2031
			$themes[ $slug ] = array(
2032
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2033
					'slug' => $slug,
2034
					'theme_root' => $theme_data->get_theme_root_uri(),
2035
					'parent' => $theme_data->parent(),
2036
					'headers' => $theme_headers
2037
			);
2038
		}
2039
2040
		return $themes;
2041
	}
2042
2043
	/**
2044
	 * Checks whether a specific plugin is active.
2045
	 *
2046
	 * We don't want to store these in a static variable, in case
2047
	 * there are switch_to_blog() calls involved.
2048
	 */
2049
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2050
		return in_array( $plugin, self::get_active_plugins() );
2051
	}
2052
2053
	/**
2054
	 * Check if Jetpack's Open Graph tags should be used.
2055
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2056
	 *
2057
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2058
	 * @action plugins_loaded
2059
	 * @return null
2060
	 */
2061
	public function check_open_graph() {
2062
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2063
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2064
		}
2065
2066
		$active_plugins = self::get_active_plugins();
2067
2068
		if ( ! empty( $active_plugins ) ) {
2069
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2070
				if ( in_array( $plugin, $active_plugins ) ) {
2071
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2072
					break;
2073
				}
2074
			}
2075
		}
2076
2077
		/**
2078
		 * Allow the addition of Open Graph Meta Tags to all pages.
2079
		 *
2080
		 * @since 2.0.3
2081
		 *
2082
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2083
		 */
2084
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2085
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2086
		}
2087
	}
2088
2089
	/**
2090
	 * Check if Jetpack's Twitter tags should be used.
2091
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2092
	 *
2093
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2094
	 * @action plugins_loaded
2095
	 * @return null
2096
	 */
2097
	public function check_twitter_tags() {
2098
2099
		$active_plugins = self::get_active_plugins();
2100
2101
		if ( ! empty( $active_plugins ) ) {
2102
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2103
				if ( in_array( $plugin, $active_plugins ) ) {
2104
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2105
					break;
2106
				}
2107
			}
2108
		}
2109
2110
		/**
2111
		 * Allow Twitter Card Meta tags to be disabled.
2112
		 *
2113
		 * @since 2.6.0
2114
		 *
2115
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2116
		 */
2117
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2118
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2119
		}
2120
	}
2121
2122
	/**
2123
	 * Allows plugins to submit security reports.
2124
 	 *
2125
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2126
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2127
	 * @param array   $args         See definitions above
2128
	 */
2129
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2130
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2131
	}
2132
2133
/* Jetpack Options API */
2134
2135
	public static function get_option_names( $type = 'compact' ) {
2136
		return Jetpack_Options::get_option_names( $type );
2137
	}
2138
2139
	/**
2140
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2141
 	 *
2142
	 * @param string $name    Option name
2143
	 * @param mixed  $default (optional)
2144
	 */
2145
	public static function get_option( $name, $default = false ) {
2146
		return Jetpack_Options::get_option( $name, $default );
2147
	}
2148
2149
	/**
2150
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2151
 	 *
2152
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2153
	 * @param string $name  Option name
2154
	 * @param mixed  $value Option value
2155
	 */
2156
	public static function update_option( $name, $value ) {
2157
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2158
		return Jetpack_Options::update_option( $name, $value );
2159
	}
2160
2161
	/**
2162
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2163
 	 *
2164
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2165
	 * @param array $array array( option name => option value, ... )
2166
	 */
2167
	public static function update_options( $array ) {
2168
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2169
		return Jetpack_Options::update_options( $array );
2170
	}
2171
2172
	/**
2173
	 * Deletes the given option.  May be passed multiple option names as an array.
2174
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2175
	 *
2176
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2177
	 * @param string|array $names
2178
	 */
2179
	public static function delete_option( $names ) {
2180
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2181
		return Jetpack_Options::delete_option( $names );
2182
	}
2183
2184
	/**
2185
	 * Enters a user token into the user_tokens option
2186
	 *
2187
	 * @param int $user_id
2188
	 * @param string $token
2189
	 * return bool
2190
	 */
2191
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2192
		// not designed for concurrent updates
2193
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2194
		if ( ! is_array( $user_tokens ) )
2195
			$user_tokens = array();
2196
		$user_tokens[$user_id] = $token;
2197
		if ( $is_master_user ) {
2198
			$master_user = $user_id;
2199
			$options     = compact( 'user_tokens', 'master_user' );
2200
		} else {
2201
			$options = compact( 'user_tokens' );
2202
		}
2203
		return Jetpack_Options::update_options( $options );
2204
	}
2205
2206
	/**
2207
	 * Returns an array of all PHP files in the specified absolute path.
2208
	 * Equivalent to glob( "$absolute_path/*.php" ).
2209
	 *
2210
	 * @param string $absolute_path The absolute path of the directory to search.
2211
	 * @return array Array of absolute paths to the PHP files.
2212
	 */
2213
	public static function glob_php( $absolute_path ) {
2214
		if ( function_exists( 'glob' ) ) {
2215
			return glob( "$absolute_path/*.php" );
2216
		}
2217
2218
		$absolute_path = untrailingslashit( $absolute_path );
2219
		$files = array();
2220
		if ( ! $dir = @opendir( $absolute_path ) ) {
2221
			return $files;
2222
		}
2223
2224
		while ( false !== $file = readdir( $dir ) ) {
2225
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2226
				continue;
2227
			}
2228
2229
			$file = "$absolute_path/$file";
2230
2231
			if ( ! is_file( $file ) ) {
2232
				continue;
2233
			}
2234
2235
			$files[] = $file;
2236
		}
2237
2238
		closedir( $dir );
2239
2240
		return $files;
2241
	}
2242
2243
	public static function activate_new_modules( $redirect = false ) {
2244
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2245
			return;
2246
		}
2247
2248
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2249 View Code Duplication
		if ( ! $jetpack_old_version ) {
2250
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2251
			/** This action is documented in class.jetpack.php */
2252
			do_action( 'updating_jetpack_version', $version, false );
2253
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2254
		}
2255
2256
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2257
2258
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2259
			return;
2260
		}
2261
2262
		$active_modules     = Jetpack::get_active_modules();
2263
		$reactivate_modules = array();
2264
		foreach ( $active_modules as $active_module ) {
2265
			$module = Jetpack::get_module( $active_module );
2266
			if ( ! isset( $module['changed'] ) ) {
2267
				continue;
2268
			}
2269
2270
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2271
				continue;
2272
			}
2273
2274
			$reactivate_modules[] = $active_module;
2275
			Jetpack::deactivate_module( $active_module );
2276
		}
2277
2278
		$new_version = JETPACK__VERSION . ':' . time();
2279
		/** This action is documented in class.jetpack.php */
2280
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2281
		Jetpack_Options::update_options(
2282
			array(
2283
				'version'     => $new_version,
2284
				'old_version' => $jetpack_old_version,
2285
			)
2286
		);
2287
2288
		Jetpack::state( 'message', 'modules_activated' );
2289
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2290
2291
		if ( $redirect ) {
2292
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2293
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2294
				$page = $_GET['page'];
2295
			}
2296
2297
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2298
			exit;
2299
		}
2300
	}
2301
2302
	/**
2303
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2304
	 * Make sure to tuck away module "library" files in a sub-directory.
2305
	 */
2306
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2307
		static $modules = null;
2308
2309
		if ( ! isset( $modules ) ) {
2310
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2311
			// Use the cache if we're on the front-end and it's available...
2312
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2313
				$modules = $available_modules_option[ JETPACK__VERSION ];
2314
			} else {
2315
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2316
2317
				$modules = array();
2318
2319
				foreach ( $files as $file ) {
2320
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2321
						continue;
2322
					}
2323
2324
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2325
				}
2326
2327
				Jetpack_Options::update_option( 'available_modules', array(
2328
					JETPACK__VERSION => $modules,
2329
				) );
2330
			}
2331
		}
2332
2333
		/**
2334
		 * Filters the array of modules available to be activated.
2335
		 *
2336
		 * @since 2.4.0
2337
		 *
2338
		 * @param array $modules Array of available modules.
2339
		 * @param string $min_version Minimum version number required to use modules.
2340
		 * @param string $max_version Maximum version number required to use modules.
2341
		 */
2342
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2343
2344
		if ( ! $min_version && ! $max_version ) {
2345
			return array_keys( $mods );
2346
		}
2347
2348
		$r = array();
2349
		foreach ( $mods as $slug => $introduced ) {
2350
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2351
				continue;
2352
			}
2353
2354
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2355
				continue;
2356
			}
2357
2358
			$r[] = $slug;
2359
		}
2360
2361
		return $r;
2362
	}
2363
2364
	/**
2365
	 * Default modules loaded on activation.
2366
	 */
2367
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2368
		$return = array();
2369
2370
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2371
			$module_data = Jetpack::get_module( $module );
2372
2373
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2374
				case 'yes' :
2375
					$return[] = $module;
2376
					break;
2377
				case 'public' :
2378
					if ( Jetpack_Options::get_option( 'public' ) ) {
2379
						$return[] = $module;
2380
					}
2381
					break;
2382
				case 'no' :
2383
				default :
2384
					break;
2385
			}
2386
		}
2387
		/**
2388
		 * Filters the array of default modules.
2389
		 *
2390
		 * @since 2.5.0
2391
		 *
2392
		 * @param array $return Array of default modules.
2393
		 * @param string $min_version Minimum version number required to use modules.
2394
		 * @param string $max_version Maximum version number required to use modules.
2395
		 */
2396
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2397
	}
2398
2399
	/**
2400
	 * Checks activated modules during auto-activation to determine
2401
	 * if any of those modules are being deprecated.  If so, close
2402
	 * them out, and add any replacement modules.
2403
	 *
2404
	 * Runs at priority 99 by default.
2405
	 *
2406
	 * This is run late, so that it can still activate a module if
2407
	 * the new module is a replacement for another that the user
2408
	 * currently has active, even if something at the normal priority
2409
	 * would kibosh everything.
2410
	 *
2411
	 * @since 2.6
2412
	 * @uses jetpack_get_default_modules filter
2413
	 * @param array $modules
2414
	 * @return array
2415
	 */
2416
	function handle_deprecated_modules( $modules ) {
2417
		$deprecated_modules = array(
2418
			'debug'            => null,  // Closed out and moved to the debugger library.
2419
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2420
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2421
		);
2422
2423
		// Don't activate SSO if they never completed activating WPCC.
2424
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2425
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2426
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2427
				$deprecated_modules['wpcc'] = null;
2428
			}
2429
		}
2430
2431
		foreach ( $deprecated_modules as $module => $replacement ) {
2432
			if ( Jetpack::is_module_active( $module ) ) {
2433
				self::deactivate_module( $module );
2434
				if ( $replacement ) {
2435
					$modules[] = $replacement;
2436
				}
2437
			}
2438
		}
2439
2440
		return array_unique( $modules );
2441
	}
2442
2443
	/**
2444
	 * Checks activated plugins during auto-activation to determine
2445
	 * if any of those plugins are in the list with a corresponding module
2446
	 * that is not compatible with the plugin. The module will not be allowed
2447
	 * to auto-activate.
2448
	 *
2449
	 * @since 2.6
2450
	 * @uses jetpack_get_default_modules filter
2451
	 * @param array $modules
2452
	 * @return array
2453
	 */
2454
	function filter_default_modules( $modules ) {
2455
2456
		$active_plugins = self::get_active_plugins();
2457
2458
		if ( ! empty( $active_plugins ) ) {
2459
2460
			// For each module we'd like to auto-activate...
2461
			foreach ( $modules as $key => $module ) {
2462
				// If there are potential conflicts for it...
2463
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2464
					// For each potential conflict...
2465
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2466
						// If that conflicting plugin is active...
2467
						if ( in_array( $plugin, $active_plugins ) ) {
2468
							// Remove that item from being auto-activated.
2469
							unset( $modules[ $key ] );
2470
						}
2471
					}
2472
				}
2473
			}
2474
		}
2475
2476
		return $modules;
2477
	}
2478
2479
	/**
2480
	 * Extract a module's slug from its full path.
2481
	 */
2482
	public static function get_module_slug( $file ) {
2483
		return str_replace( '.php', '', basename( $file ) );
2484
	}
2485
2486
	/**
2487
	 * Generate a module's path from its slug.
2488
	 */
2489
	public static function get_module_path( $slug ) {
2490
		/**
2491
		 * Filters the path of a modules.
2492
		 *
2493
		 * @since 7.4.0
2494
		 *
2495
		 * @param array $return The absolute path to a module's root php file
2496
		 * @param string $slug The module slug
2497
		 */
2498
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2499
	}
2500
2501
	/**
2502
	 * Load module data from module file. Headers differ from WordPress
2503
	 * plugin headers to avoid them being identified as standalone
2504
	 * plugins on the WordPress plugins page.
2505
	 */
2506
	public static function get_module( $module ) {
2507
		$headers = array(
2508
			'name'                      => 'Module Name',
2509
			'description'               => 'Module Description',
2510
			'jumpstart_desc'            => 'Jumpstart Description',
2511
			'sort'                      => 'Sort Order',
2512
			'recommendation_order'      => 'Recommendation Order',
2513
			'introduced'                => 'First Introduced',
2514
			'changed'                   => 'Major Changes In',
2515
			'deactivate'                => 'Deactivate',
2516
			'free'                      => 'Free',
2517
			'requires_connection'       => 'Requires Connection',
2518
			'auto_activate'             => 'Auto Activate',
2519
			'module_tags'               => 'Module Tags',
2520
			'feature'                   => 'Feature',
2521
			'additional_search_queries' => 'Additional Search Queries',
2522
			'plan_classes'              => 'Plans',
2523
		);
2524
2525
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2526
2527
		$mod = Jetpack::get_file_data( $file, $headers );
2528
		if ( empty( $mod['name'] ) ) {
2529
			return false;
2530
		}
2531
2532
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2533
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2534
		$mod['deactivate']              = empty( $mod['deactivate'] );
2535
		$mod['free']                    = empty( $mod['free'] );
2536
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2537
2538
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2539
			$mod['auto_activate'] = 'No';
2540
		} else {
2541
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2542
		}
2543
2544
		if ( $mod['module_tags'] ) {
2545
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2546
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2547
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2548
		} else {
2549
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2550
		}
2551
2552 View Code Duplication
		if ( $mod['plan_classes'] ) {
2553
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2554
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2555
		} else {
2556
			$mod['plan_classes'] = array( 'free' );
2557
		}
2558
2559 View Code Duplication
		if ( $mod['feature'] ) {
2560
			$mod['feature'] = explode( ',', $mod['feature'] );
2561
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2562
		} else {
2563
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2564
		}
2565
2566
		/**
2567
		 * Filters the feature array on a module.
2568
		 *
2569
		 * This filter allows you to control where each module is filtered: Recommended,
2570
		 * Jumpstart, and the default "Other" listing.
2571
		 *
2572
		 * @since 3.5.0
2573
		 *
2574
		 * @param array   $mod['feature'] The areas to feature this module:
2575
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2576
		 *     'Recommended' shows on the main Jetpack admin screen.
2577
		 *     'Other' should be the default if no other value is in the array.
2578
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2579
		 * @param array   $mod All the currently assembled module data.
2580
		 */
2581
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2582
2583
		/**
2584
		 * Filter the returned data about a module.
2585
		 *
2586
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2587
		 * so please be careful.
2588
		 *
2589
		 * @since 3.6.0
2590
		 *
2591
		 * @param array   $mod    The details of the requested module.
2592
		 * @param string  $module The slug of the module, e.g. sharedaddy
2593
		 * @param string  $file   The path to the module source file.
2594
		 */
2595
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2596
	}
2597
2598
	/**
2599
	 * Like core's get_file_data implementation, but caches the result.
2600
	 */
2601
	public static function get_file_data( $file, $headers ) {
2602
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2603
		$file_name = basename( $file );
2604
2605
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2606
2607
		$file_data_option = get_transient( $cache_key );
2608
2609
		if ( false === $file_data_option ) {
2610
			$file_data_option = array();
2611
		}
2612
2613
		$key           = md5( $file_name . serialize( $headers ) );
2614
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2615
2616
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2617
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2618
			return $file_data_option[ $key ];
2619
		}
2620
2621
		$data = get_file_data( $file, $headers );
2622
2623
		$file_data_option[ $key ] = $data;
2624
2625
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2626
2627
		return $data;
2628
	}
2629
2630
2631
	/**
2632
	 * Return translated module tag.
2633
	 *
2634
	 * @param string $tag Tag as it appears in each module heading.
2635
	 *
2636
	 * @return mixed
2637
	 */
2638
	public static function translate_module_tag( $tag ) {
2639
		return jetpack_get_module_i18n_tag( $tag );
2640
	}
2641
2642
	/**
2643
	 * Get i18n strings as a JSON-encoded string
2644
	 *
2645
	 * @return string The locale as JSON
2646
	 */
2647
	public static function get_i18n_data_json() {
2648
2649
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2650
		// JSON files with the file they should be included for. This is an md5
2651
		// of '_inc/build/admin.js'.
2652
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2653
2654
		$i18n_json =
2655
				   JETPACK__PLUGIN_DIR
2656
				   . 'languages/json/jetpack-'
2657
				   . get_user_locale()
2658
				   . '-'
2659
				   . $path_md5
2660
				   . '.json';
2661
2662
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2663
			$locale_data = @file_get_contents( $i18n_json );
2664
			if ( $locale_data ) {
2665
				return $locale_data;
2666
			}
2667
		}
2668
2669
		// Return valid empty Jed locale
2670
		return '{ "locale_data": { "messages": { "": {} } } }';
2671
	}
2672
2673
	/**
2674
	 * Add locale data setup to wp-i18n
2675
	 *
2676
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2677
	 *
2678
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2679
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2680
	 *
2681
	 * This method provides a safe way to request the setup multiple times but add the script at
2682
	 * most once.
2683
	 *
2684
	 * @since 6.7.0
2685
	 *
2686
	 * @return void
2687
	 */
2688
	public static function setup_wp_i18n_locale_data() {
2689
		static $script_added = false;
2690
		if ( ! $script_added ) {
2691
			$script_added = true;
2692
			wp_add_inline_script(
2693
				'wp-i18n',
2694
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2695
			);
2696
		}
2697
	}
2698
2699
	/**
2700
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2701
	 *
2702
	 * @since 3.9.2
2703
	 *
2704
	 * @param array $modules
2705
	 *
2706
	 * @return string|void
2707
	 */
2708
	public static function get_translated_modules( $modules ) {
2709
		foreach ( $modules as $index => $module ) {
2710
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2711
			if ( isset( $module['name'] ) ) {
2712
				$modules[ $index ]['name'] = $i18n_module['name'];
2713
			}
2714
			if ( isset( $module['description'] ) ) {
2715
				$modules[ $index ]['description'] = $i18n_module['description'];
2716
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2717
			}
2718
		}
2719
		return $modules;
2720
	}
2721
2722
	/**
2723
	 * Get a list of activated modules as an array of module slugs.
2724
	 */
2725
	public static function get_active_modules() {
2726
		$active = Jetpack_Options::get_option( 'active_modules' );
2727
2728
		if ( ! is_array( $active ) ) {
2729
			$active = array();
2730
		}
2731
2732
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2733
			$active[] = 'vaultpress';
2734
		} else {
2735
			$active = array_diff( $active, array( 'vaultpress' ) );
2736
		}
2737
2738
		//If protect is active on the main site of a multisite, it should be active on all sites.
2739
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2740
			$active[] = 'protect';
2741
		}
2742
2743
		/**
2744
		 * Allow filtering of the active modules.
2745
		 *
2746
		 * Gives theme and plugin developers the power to alter the modules that
2747
		 * are activated on the fly.
2748
		 *
2749
		 * @since 5.8.0
2750
		 *
2751
		 * @param array $active Array of active module slugs.
2752
		 */
2753
		$active = apply_filters( 'jetpack_active_modules', $active );
2754
2755
		return array_unique( $active );
2756
	}
2757
2758
	/**
2759
	 * Check whether or not a Jetpack module is active.
2760
	 *
2761
	 * @param string $module The slug of a Jetpack module.
2762
	 * @return bool
2763
	 *
2764
	 * @static
2765
	 */
2766
	public static function is_module_active( $module ) {
2767
		return in_array( $module, self::get_active_modules() );
2768
	}
2769
2770
	public static function is_module( $module ) {
2771
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2772
	}
2773
2774
	/**
2775
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2776
	 *
2777
	 * @param bool $catch True to start catching, False to stop.
2778
	 *
2779
	 * @static
2780
	 */
2781
	public static function catch_errors( $catch ) {
2782
		static $display_errors, $error_reporting;
2783
2784
		if ( $catch ) {
2785
			$display_errors  = @ini_set( 'display_errors', 1 );
2786
			$error_reporting = @error_reporting( E_ALL );
2787
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2788
		} else {
2789
			@ini_set( 'display_errors', $display_errors );
2790
			@error_reporting( $error_reporting );
2791
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2792
		}
2793
	}
2794
2795
	/**
2796
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2797
	 */
2798
	public static function catch_errors_on_shutdown() {
2799
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2800
	}
2801
2802
	/**
2803
	 * Rewrite any string to make paths easier to read.
2804
	 *
2805
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2806
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2807
	 *
2808
	 * @param $string
2809
	 * @return mixed
2810
	 */
2811
	public static function alias_directories( $string ) {
2812
		// ABSPATH has a trailing slash.
2813
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2814
		// WP_CONTENT_DIR does not have a trailing slash.
2815
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2816
2817
		return $string;
2818
	}
2819
2820
	public static function activate_default_modules(
2821
		$min_version = false,
2822
		$max_version = false,
2823
		$other_modules = array(),
2824
		$redirect = true,
2825
		$send_state_messages = true
2826
	) {
2827
		$jetpack = Jetpack::init();
2828
2829
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2830
		$modules = array_merge( $other_modules, $modules );
2831
2832
		// Look for standalone plugins and disable if active.
2833
2834
		$to_deactivate = array();
2835
		foreach ( $modules as $module ) {
2836
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2837
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2838
			}
2839
		}
2840
2841
		$deactivated = array();
2842
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2843
			list( $probable_file, $probable_title ) = $deactivate_me;
2844
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2845
				$deactivated[] = $module;
2846
			}
2847
		}
2848
2849
		if ( $deactivated && $redirect ) {
2850
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2851
2852
			$url = add_query_arg(
2853
				array(
2854
					'action'   => 'activate_default_modules',
2855
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2856
				),
2857
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2858
			);
2859
			wp_safe_redirect( $url );
2860
			exit;
2861
		}
2862
2863
		/**
2864
		 * Fires before default modules are activated.
2865
		 *
2866
		 * @since 1.9.0
2867
		 *
2868
		 * @param string $min_version Minimum version number required to use modules.
2869
		 * @param string $max_version Maximum version number required to use modules.
2870
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2871
		 */
2872
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2873
2874
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2875
		if ( $send_state_messages ) {
2876
			Jetpack::restate();
2877
			Jetpack::catch_errors( true );
2878
		}
2879
2880
		$active = Jetpack::get_active_modules();
2881
2882
		foreach ( $modules as $module ) {
2883
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2884
				$active[] = $module;
2885
				self::update_active_modules( $active );
2886
				continue;
2887
			}
2888
2889
			if ( $send_state_messages && in_array( $module, $active ) ) {
2890
				$module_info = Jetpack::get_module( $module );
2891 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2892
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2893
					if ( $active_state = Jetpack::state( $state ) ) {
2894
						$active_state = explode( ',', $active_state );
2895
					} else {
2896
						$active_state = array();
2897
					}
2898
					$active_state[] = $module;
2899
					Jetpack::state( $state, implode( ',', $active_state ) );
2900
				}
2901
				continue;
2902
			}
2903
2904
			$file = Jetpack::get_module_path( $module );
2905
			if ( ! file_exists( $file ) ) {
2906
				continue;
2907
			}
2908
2909
			// we'll override this later if the plugin can be included without fatal error
2910
			if ( $redirect ) {
2911
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2912
			}
2913
2914
			if ( $send_state_messages ) {
2915
				Jetpack::state( 'error', 'module_activation_failed' );
2916
				Jetpack::state( 'module', $module );
2917
			}
2918
2919
			ob_start();
2920
			require_once $file;
2921
2922
			$active[] = $module;
2923
2924 View Code Duplication
			if ( $send_state_messages ) {
2925
2926
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2927
				if ( $active_state = Jetpack::state( $state ) ) {
2928
					$active_state = explode( ',', $active_state );
2929
				} else {
2930
					$active_state = array();
2931
				}
2932
				$active_state[] = $module;
2933
				Jetpack::state( $state, implode( ',', $active_state ) );
2934
			}
2935
2936
			Jetpack::update_active_modules( $active );
2937
2938
			ob_end_clean();
2939
		}
2940
2941
		if ( $send_state_messages ) {
2942
			Jetpack::state( 'error', false );
2943
			Jetpack::state( 'module', false );
2944
		}
2945
2946
		Jetpack::catch_errors( false );
2947
		/**
2948
		 * Fires when default modules are activated.
2949
		 *
2950
		 * @since 1.9.0
2951
		 *
2952
		 * @param string $min_version Minimum version number required to use modules.
2953
		 * @param string $max_version Maximum version number required to use modules.
2954
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2955
		 */
2956
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2957
	}
2958
2959
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2960
		/**
2961
		 * Fires before a module is activated.
2962
		 *
2963
		 * @since 2.6.0
2964
		 *
2965
		 * @param string $module Module slug.
2966
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2967
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2968
		 */
2969
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2970
2971
		$jetpack = Jetpack::init();
2972
2973
		if ( ! strlen( $module ) )
2974
			return false;
2975
2976
		if ( ! Jetpack::is_module( $module ) )
2977
			return false;
2978
2979
		// If it's already active, then don't do it again
2980
		$active = Jetpack::get_active_modules();
2981
		foreach ( $active as $act ) {
2982
			if ( $act == $module )
2983
				return true;
2984
		}
2985
2986
		$module_data = Jetpack::get_module( $module );
2987
2988
		if ( ! Jetpack::is_active() ) {
2989
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2990
				return false;
2991
2992
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2993
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2994
				return false;
2995
		}
2996
2997
		// Check and see if the old plugin is active
2998
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2999
			// Deactivate the old plugin
3000
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3001
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3002
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3003
				Jetpack::state( 'deactivated_plugins', $module );
3004
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3005
				exit;
3006
			}
3007
		}
3008
3009
		// Protect won't work with mis-configured IPs
3010
		if ( 'protect' === $module ) {
3011
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3012
			if ( ! jetpack_protect_get_ip() ) {
3013
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3014
				return false;
3015
			}
3016
		}
3017
3018
		if ( ! Jetpack_Plan::supports( $module ) ) {
3019
			return false;
3020
		}
3021
3022
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3023
		Jetpack::state( 'module', $module );
3024
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3025
3026
		Jetpack::catch_errors( true );
3027
		ob_start();
3028
		require Jetpack::get_module_path( $module );
3029
		/** This action is documented in class.jetpack.php */
3030
		do_action( 'jetpack_activate_module', $module );
3031
		$active[] = $module;
3032
		Jetpack::update_active_modules( $active );
3033
3034
		Jetpack::state( 'error', false ); // the override
3035
		ob_end_clean();
3036
		Jetpack::catch_errors( false );
3037
3038
		if ( $redirect ) {
3039
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3040
		}
3041
		if ( $exit ) {
3042
			exit;
3043
		}
3044
		return true;
3045
	}
3046
3047
	function activate_module_actions( $module ) {
3048
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3049
	}
3050
3051
	public static function deactivate_module( $module ) {
3052
		/**
3053
		 * Fires when a module is deactivated.
3054
		 *
3055
		 * @since 1.9.0
3056
		 *
3057
		 * @param string $module Module slug.
3058
		 */
3059
		do_action( 'jetpack_pre_deactivate_module', $module );
3060
3061
		$jetpack = Jetpack::init();
3062
3063
		$active = Jetpack::get_active_modules();
3064
		$new    = array_filter( array_diff( $active, (array) $module ) );
3065
3066
		return self::update_active_modules( $new );
3067
	}
3068
3069
	public static function enable_module_configurable( $module ) {
3070
		$module = Jetpack::get_module_slug( $module );
3071
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3072
	}
3073
3074
	/**
3075
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3076
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3077
	 *
3078
	 * @param string $module Module slug
3079
	 * @return string $url module configuration URL
3080
	 */
3081
	public static function module_configuration_url( $module ) {
3082
		$module = Jetpack::get_module_slug( $module );
3083
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3084
		/**
3085
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3086
		 *
3087
		 * @since 6.9.0
3088
		 *
3089
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3090
		 */
3091
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3092
3093
		return $url;
3094
	}
3095
3096
/* Installation */
3097
	public static function bail_on_activation( $message, $deactivate = true ) {
3098
?>
3099
<!doctype html>
3100
<html>
3101
<head>
3102
<meta charset="<?php bloginfo( 'charset' ); ?>">
3103
<style>
3104
* {
3105
	text-align: center;
3106
	margin: 0;
3107
	padding: 0;
3108
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3109
}
3110
p {
3111
	margin-top: 1em;
3112
	font-size: 18px;
3113
}
3114
</style>
3115
<body>
3116
<p><?php echo esc_html( $message ); ?></p>
3117
</body>
3118
</html>
3119
<?php
3120
		if ( $deactivate ) {
3121
			$plugins = get_option( 'active_plugins' );
3122
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3123
			$update  = false;
3124
			foreach ( $plugins as $i => $plugin ) {
3125
				if ( $plugin === $jetpack ) {
3126
					$plugins[$i] = false;
3127
					$update = true;
3128
				}
3129
			}
3130
3131
			if ( $update ) {
3132
				update_option( 'active_plugins', array_filter( $plugins ) );
3133
			}
3134
		}
3135
		exit;
3136
	}
3137
3138
	/**
3139
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3140
	 * @static
3141
	 */
3142
	public static function plugin_activation( $network_wide ) {
3143
		Jetpack_Options::update_option( 'activated', 1 );
3144
3145
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3146
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3147
		}
3148
3149
		if ( $network_wide )
3150
			Jetpack::state( 'network_nag', true );
3151
3152
		// For firing one-off events (notices) immediately after activation
3153
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3154
3155
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3156
3157
		Jetpack::plugin_initialize();
3158
	}
3159
3160
	public static function get_activation_source( $referer_url ) {
3161
3162
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3163
			return array( 'wp-cli', null );
3164
		}
3165
3166
		$referer = parse_url( $referer_url );
3167
3168
		$source_type = 'unknown';
3169
		$source_query = null;
3170
3171
		if ( ! is_array( $referer ) ) {
3172
			return array( $source_type, $source_query );
3173
		}
3174
3175
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3176
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3177
3178
		if ( isset( $referer['query'] ) ) {
3179
			parse_str( $referer['query'], $query_parts );
3180
		} else {
3181
			$query_parts = array();
3182
		}
3183
3184
		if ( $plugins_path === $referer['path'] ) {
3185
			$source_type = 'list';
3186
		} elseif ( $plugins_install_path === $referer['path'] ) {
3187
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3188
			switch( $tab ) {
3189
				case 'popular':
3190
					$source_type = 'popular';
3191
					break;
3192
				case 'recommended':
3193
					$source_type = 'recommended';
3194
					break;
3195
				case 'favorites':
3196
					$source_type = 'favorites';
3197
					break;
3198
				case 'search':
3199
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3200
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3201
					break;
3202
				default:
3203
					$source_type = 'featured';
3204
			}
3205
		}
3206
3207
		return array( $source_type, $source_query );
3208
	}
3209
3210
	/**
3211
	 * Runs before bumping version numbers up to a new version
3212
	 * @param  string $version    Version:timestamp
3213
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3214
	 * @return null              [description]
3215
	 */
3216
	public static function do_version_bump( $version, $old_version ) {
3217
		if ( ! $old_version ) { // For new sites
3218
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3219
		}
3220
	}
3221
3222
	/**
3223
	 * Sets the internal version number and activation state.
3224
	 * @static
3225
	 */
3226
	public static function plugin_initialize() {
3227
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3228
			Jetpack_Options::update_option( 'activated', 2 );
3229
		}
3230
3231 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3232
			$version = $old_version = JETPACK__VERSION . ':' . time();
3233
			/** This action is documented in class.jetpack.php */
3234
			do_action( 'updating_jetpack_version', $version, false );
3235
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3236
		}
3237
3238
		Jetpack::load_modules();
3239
3240
		Jetpack_Options::delete_option( 'do_activate' );
3241
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3242
	}
3243
3244
	/**
3245
	 * Removes all connection options
3246
	 * @static
3247
	 */
3248
	public static function plugin_deactivation( ) {
3249
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3250
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3251
			Jetpack_Network::init()->deactivate();
3252
		} else {
3253
			Jetpack::disconnect( false );
3254
			//Jetpack_Heartbeat::init()->deactivate();
3255
		}
3256
	}
3257
3258
	/**
3259
	 * Disconnects from the Jetpack servers.
3260
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3261
	 * @static
3262
	 */
3263
	public static function disconnect( $update_activated_state = true ) {
3264
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3265
		Jetpack::clean_nonces( true );
3266
3267
		// If the site is in an IDC because sync is not allowed,
3268
		// let's make sure to not disconnect the production site.
3269
		if ( ! self::validate_sync_error_idc_option() ) {
3270
			$this->tracking->record_user_event( 'disconnect_site', array() );
0 ignored issues
show
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
3271
			Jetpack::load_xml_rpc_client();
3272
			$xml = new Jetpack_IXR_Client();
3273
			$xml->query( 'jetpack.deregister' );
3274
		}
3275
3276
		Jetpack_Options::delete_option(
3277
			array(
3278
				'blog_token',
3279
				'user_token',
3280
				'user_tokens',
3281
				'master_user',
3282
				'time_diff',
3283
				'fallback_no_verify_ssl_certs',
3284
			)
3285
		);
3286
3287
		Jetpack_IDC::clear_all_idc_options();
3288
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3289
3290
		if ( $update_activated_state ) {
3291
			Jetpack_Options::update_option( 'activated', 4 );
3292
		}
3293
3294
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3295
			// Check then record unique disconnection if site has never been disconnected previously
3296
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3297
				$jetpack_unique_connection['disconnected'] = 1;
3298
			} else {
3299
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3300
					//track unique disconnect
3301
					$jetpack = Jetpack::init();
3302
3303
					$jetpack->stat( 'connections', 'unique-disconnect' );
3304
					$jetpack->do_stats( 'server_side' );
3305
				}
3306
				// increment number of times disconnected
3307
				$jetpack_unique_connection['disconnected'] += 1;
3308
			}
3309
3310
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3311
		}
3312
3313
		// Delete cached connected user data
3314
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3315
		delete_transient( $transient_key );
3316
3317
		// Delete all the sync related data. Since it could be taking up space.
3318
		Jetpack_Sync_Sender::get_instance()->uninstall();
3319
3320
		// Disable the Heartbeat cron
3321
		Jetpack_Heartbeat::init()->deactivate();
3322
	}
3323
3324
	/**
3325
	 * Unlinks the current user from the linked WordPress.com user
3326
	 */
3327
	public static function unlink_user( $user_id = null ) {
3328
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3329
			return false;
3330
3331
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3332
3333
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3334
			return false;
3335
3336
		if ( ! isset( $tokens[ $user_id ] ) )
3337
			return false;
3338
3339
		Jetpack::load_xml_rpc_client();
3340
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3341
		$xml->query( 'jetpack.unlink_user', $user_id );
3342
3343
		unset( $tokens[ $user_id ] );
3344
3345
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3346
3347
		/**
3348
		 * Fires after the current user has been unlinked from WordPress.com.
3349
		 *
3350
		 * @since 4.1.0
3351
		 *
3352
		 * @param int $user_id The current user's ID.
3353
		 */
3354
		do_action( 'jetpack_unlinked_user', $user_id );
3355
3356
		return true;
3357
	}
3358
3359
	/**
3360
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3361
	 */
3362
	public static function try_registration() {
3363
		// The user has agreed to the TOS at some point by now.
3364
		Jetpack_Options::update_option( 'tos_agreed', true );
3365
3366
		// Let's get some testing in beta versions and such.
3367
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3368
			// Before attempting to connect, let's make sure that the domains are viable.
3369
			$domains_to_check = array_unique( array(
3370
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3371
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3372
			) );
3373
			foreach ( $domains_to_check as $domain ) {
3374
				$result = self::connection()->is_usable_domain( $domain );
3375
				if ( is_wp_error( $result ) ) {
3376
					return $result;
3377
				}
3378
			}
3379
		}
3380
3381
		$result = Jetpack::register();
3382
3383
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3384
		if ( ! $result || is_wp_error( $result ) ) {
3385
			return $result;
3386
		} else {
3387
			return true;
3388
		}
3389
	}
3390
3391
	/**
3392
	 * Tracking an internal event log. Try not to put too much chaff in here.
3393
	 *
3394
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3395
	 */
3396
	public static function log( $code, $data = null ) {
3397
		// only grab the latest 200 entries
3398
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3399
3400
		// Append our event to the log
3401
		$log_entry = array(
3402
			'time'    => time(),
3403
			'user_id' => get_current_user_id(),
3404
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3405
			'code'    => $code,
3406
		);
3407
		// Don't bother storing it unless we've got some.
3408
		if ( ! is_null( $data ) ) {
3409
			$log_entry['data'] = $data;
3410
		}
3411
		$log[] = $log_entry;
3412
3413
		// Try add_option first, to make sure it's not autoloaded.
3414
		// @todo: Add an add_option method to Jetpack_Options
3415
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3416
			Jetpack_Options::update_option( 'log', $log );
3417
		}
3418
3419
		/**
3420
		 * Fires when Jetpack logs an internal event.
3421
		 *
3422
		 * @since 3.0.0
3423
		 *
3424
		 * @param array $log_entry {
3425
		 *	Array of details about the log entry.
3426
		 *
3427
		 *	@param string time Time of the event.
3428
		 *	@param int user_id ID of the user who trigerred the event.
3429
		 *	@param int blog_id Jetpack Blog ID.
3430
		 *	@param string code Unique name for the event.
3431
		 *	@param string data Data about the event.
3432
		 * }
3433
		 */
3434
		do_action( 'jetpack_log_entry', $log_entry );
3435
	}
3436
3437
	/**
3438
	 * Get the internal event log.
3439
	 *
3440
	 * @param $event (string) - only return the specific log events
3441
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3442
	 *
3443
	 * @return array of log events || WP_Error for invalid params
3444
	 */
3445
	public static function get_log( $event = false, $num = false ) {
3446
		if ( $event && ! is_string( $event ) ) {
3447
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3448
		}
3449
3450
		if ( $num && ! is_numeric( $num ) ) {
3451
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3452
		}
3453
3454
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3455
3456
		// If nothing set - act as it did before, otherwise let's start customizing the output
3457
		if ( ! $num && ! $event ) {
3458
			return $entire_log;
3459
		} else {
3460
			$entire_log = array_reverse( $entire_log );
3461
		}
3462
3463
		$custom_log_output = array();
3464
3465
		if ( $event ) {
3466
			foreach ( $entire_log as $log_event ) {
3467
				if ( $event == $log_event[ 'code' ] ) {
3468
					$custom_log_output[] = $log_event;
3469
				}
3470
			}
3471
		} else {
3472
			$custom_log_output = $entire_log;
3473
		}
3474
3475
		if ( $num ) {
3476
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3477
		}
3478
3479
		return $custom_log_output;
3480
	}
3481
3482
	/**
3483
	 * Log modification of important settings.
3484
	 */
3485
	public static function log_settings_change( $option, $old_value, $value ) {
3486
		switch( $option ) {
3487
			case 'jetpack_sync_non_public_post_stati':
3488
				self::log( $option, $value );
3489
				break;
3490
		}
3491
	}
3492
3493
	/**
3494
	 * Return stat data for WPCOM sync
3495
	 */
3496
	public static function get_stat_data( $encode = true, $extended = true ) {
3497
		$data = Jetpack_Heartbeat::generate_stats_array();
3498
3499
		if ( $extended ) {
3500
			$additional_data = self::get_additional_stat_data();
3501
			$data = array_merge( $data, $additional_data );
3502
		}
3503
3504
		if ( $encode ) {
3505
			return json_encode( $data );
3506
		}
3507
3508
		return $data;
3509
	}
3510
3511
	/**
3512
	 * Get additional stat data to sync to WPCOM
3513
	 */
3514
	public static function get_additional_stat_data( $prefix = '' ) {
3515
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3516
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3517
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3518
		$return["{$prefix}site-count"]     = 0;
3519
3520
		if ( function_exists( 'get_blog_count' ) ) {
3521
			$return["{$prefix}site-count"] = get_blog_count();
3522
		}
3523
		return $return;
3524
	}
3525
3526
	private static function get_site_user_count() {
3527
		global $wpdb;
3528
3529
		if ( function_exists( 'wp_is_large_network' ) ) {
3530
			if ( wp_is_large_network( 'users' ) ) {
3531
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3532
			}
3533
		}
3534 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3535
			// It wasn't there, so regenerate the data and save the transient
3536
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3537
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3538
		}
3539
		return $user_count;
3540
	}
3541
3542
	/* Admin Pages */
3543
3544
	function admin_init() {
3545
		// If the plugin is not connected, display a connect message.
3546
		if (
3547
			// the plugin was auto-activated and needs its candy
3548
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3549
		||
3550
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3551
			! Jetpack_Options::get_option( 'activated' )
3552
		) {
3553
			Jetpack::plugin_initialize();
3554
		}
3555
3556
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3557
			Jetpack_Connection_Banner::init();
3558
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3559
			// Upgrade: 1.1 -> 1.1.1
3560
			// Check and see if host can verify the Jetpack servers' SSL certificate
3561
			$args = array();
3562
			Jetpack_Client::_wp_remote_request(
3563
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3564
				$args,
3565
				true
3566
			);
3567
		}
3568
3569
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3570
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3571
		}
3572
3573
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3574
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3575
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3576
3577
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3578
			// Artificially throw errors in certain whitelisted cases during plugin activation
3579
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3580
		}
3581
3582
		// Add custom column in wp-admin/users.php to show whether user is linked.
3583
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3584
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3585
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3586
	}
3587
3588
	function admin_body_class( $admin_body_class = '' ) {
3589
		$classes = explode( ' ', trim( $admin_body_class ) );
3590
3591
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3592
3593
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3594
		return " $admin_body_class ";
3595
	}
3596
3597
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3598
		return $admin_body_class . ' jetpack-pagestyles ';
3599
	}
3600
3601
	/**
3602
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3603
	 * This function artificially throws errors for such cases (whitelisted).
3604
	 *
3605
	 * @param string $plugin The activated plugin.
3606
	 */
3607
	function throw_error_on_activate_plugin( $plugin ) {
3608
		$active_modules = Jetpack::get_active_modules();
3609
3610
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3611
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3612
			$throw = false;
3613
3614
			// Try and make sure it really was the stats plugin
3615
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3616
				if ( 'stats.php' == basename( $plugin ) ) {
3617
					$throw = true;
3618
				}
3619
			} else {
3620
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3621
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3622
					$throw = true;
3623
				}
3624
			}
3625
3626
			if ( $throw ) {
3627
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3628
			}
3629
		}
3630
	}
3631
3632
	function intercept_plugin_error_scrape_init() {
3633
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3634
	}
3635
3636
	function intercept_plugin_error_scrape( $action, $result ) {
3637
		if ( ! $result ) {
3638
			return;
3639
		}
3640
3641
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3642
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3643
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3644
			}
3645
		}
3646
	}
3647
3648
	function add_remote_request_handlers() {
3649
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3650
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3651
	}
3652
3653
	function remote_request_handlers() {
3654
		$action = current_filter();
3655
3656
		switch ( current_filter() ) {
3657
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3658
			$response = $this->upload_handler();
3659
			break;
3660
3661
		case 'wp_ajax_nopriv_jetpack_update_file' :
3662
			$response = $this->upload_handler( true );
3663
			break;
3664
		default :
3665
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3666
			break;
3667
		}
3668
3669
		if ( ! $response ) {
3670
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3671
		}
3672
3673
		if ( is_wp_error( $response ) ) {
3674
			$status_code       = $response->get_error_data();
3675
			$error             = $response->get_error_code();
3676
			$error_description = $response->get_error_message();
3677
3678
			if ( ! is_int( $status_code ) ) {
3679
				$status_code = 400;
3680
			}
3681
3682
			status_header( $status_code );
3683
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3684
		}
3685
3686
		status_header( 200 );
3687
		if ( true === $response ) {
3688
			exit;
3689
		}
3690
3691
		die( json_encode( (object) $response ) );
3692
	}
3693
3694
	/**
3695
	 * Uploads a file gotten from the global $_FILES.
3696
	 * If `$update_media_item` is true and `post_id` is defined
3697
	 * the attachment file of the media item (gotten through of the post_id)
3698
	 * will be updated instead of add a new one.
3699
	 *
3700
	 * @param  boolean $update_media_item - update media attachment
3701
	 * @return array - An array describing the uploadind files process
3702
	 */
3703
	function upload_handler( $update_media_item = false ) {
3704
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3705
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3706
		}
3707
3708
		$user = wp_authenticate( '', '' );
3709
		if ( ! $user || is_wp_error( $user ) ) {
3710
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3711
		}
3712
3713
		wp_set_current_user( $user->ID );
3714
3715
		if ( ! current_user_can( 'upload_files' ) ) {
3716
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3717
		}
3718
3719
		if ( empty( $_FILES ) ) {
3720
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3721
		}
3722
3723
		foreach ( array_keys( $_FILES ) as $files_key ) {
3724
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3725
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3726
			}
3727
		}
3728
3729
		$media_keys = array_keys( $_FILES['media'] );
3730
3731
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3732
		if ( ! $token || is_wp_error( $token ) ) {
3733
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3734
		}
3735
3736
		$uploaded_files = array();
3737
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3738
		unset( $GLOBALS['post'] );
3739
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3740
			$file = array();
3741
			foreach ( $media_keys as $media_key ) {
3742
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3743
			}
3744
3745
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3746
3747
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3748
			if ( $hmac_provided !== $hmac_file ) {
3749
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3750
				continue;
3751
			}
3752
3753
			$_FILES['.jetpack.upload.'] = $file;
3754
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3755
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3756
				$post_id = 0;
3757
			}
3758
3759
			if ( $update_media_item ) {
3760
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3761
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3762
				}
3763
3764
				$media_array = $_FILES['media'];
3765
3766
				$file_array['name'] = $media_array['name'][0];
3767
				$file_array['type'] = $media_array['type'][0];
3768
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3769
				$file_array['error'] = $media_array['error'][0];
3770
				$file_array['size'] = $media_array['size'][0];
3771
3772
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3773
3774
				if ( is_wp_error( $edited_media_item ) ) {
3775
					return $edited_media_item;
3776
				}
3777
3778
				$response = (object) array(
3779
					'id'   => (string) $post_id,
3780
					'file' => (string) $edited_media_item->post_title,
3781
					'url'  => (string) wp_get_attachment_url( $post_id ),
3782
					'type' => (string) $edited_media_item->post_mime_type,
3783
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3784
				);
3785
3786
				return (array) array( $response );
3787
			}
3788
3789
			$attachment_id = media_handle_upload(
3790
				'.jetpack.upload.',
3791
				$post_id,
3792
				array(),
3793
				array(
3794
					'action' => 'jetpack_upload_file',
3795
				)
3796
			);
3797
3798
			if ( ! $attachment_id ) {
3799
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3800
			} elseif ( is_wp_error( $attachment_id ) ) {
3801
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3802
			} else {
3803
				$attachment = get_post( $attachment_id );
3804
				$uploaded_files[$index] = (object) array(
3805
					'id'   => (string) $attachment_id,
3806
					'file' => $attachment->post_title,
3807
					'url'  => wp_get_attachment_url( $attachment_id ),
3808
					'type' => $attachment->post_mime_type,
3809
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3810
				);
3811
				// Zip files uploads are not supported unless they are done for installation purposed
3812
				// lets delete them in case something goes wrong in this whole process
3813
				if ( 'application/zip' === $attachment->post_mime_type ) {
3814
					// Schedule a cleanup for 2 hours from now in case of failed install.
3815
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3816
				}
3817
			}
3818
		}
3819
		if ( ! is_null( $global_post ) ) {
3820
			$GLOBALS['post'] = $global_post;
3821
		}
3822
3823
		return $uploaded_files;
3824
	}
3825
3826
	/**
3827
	 * Add help to the Jetpack page
3828
	 *
3829
	 * @since Jetpack (1.2.3)
3830
	 * @return false if not the Jetpack page
3831
	 */
3832
	function admin_help() {
3833
		$current_screen = get_current_screen();
3834
3835
		// Overview
3836
		$current_screen->add_help_tab(
3837
			array(
3838
				'id'		=> 'home',
3839
				'title'		=> __( 'Home', 'jetpack' ),
3840
				'content'	=>
3841
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3842
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3843
					'<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>',
3844
			)
3845
		);
3846
3847
		// Screen Content
3848
		if ( current_user_can( 'manage_options' ) ) {
3849
			$current_screen->add_help_tab(
3850
				array(
3851
					'id'		=> 'settings',
3852
					'title'		=> __( 'Settings', 'jetpack' ),
3853
					'content'	=>
3854
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3855
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3856
						'<ol>' .
3857
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3858
							'<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>' .
3859
						'</ol>' .
3860
						'<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>'
3861
				)
3862
			);
3863
		}
3864
3865
		// Help Sidebar
3866
		$current_screen->set_help_sidebar(
3867
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3868
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3869
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3870
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3871
		);
3872
	}
3873
3874
	function admin_menu_css() {
3875
		wp_enqueue_style( 'jetpack-icons' );
3876
	}
3877
3878
	function admin_menu_order() {
3879
		return true;
3880
	}
3881
3882 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3883
		$jp_menu_order = array();
3884
3885
		foreach ( $menu_order as $index => $item ) {
3886
			if ( $item != 'jetpack' ) {
3887
				$jp_menu_order[] = $item;
3888
			}
3889
3890
			if ( $index == 0 ) {
3891
				$jp_menu_order[] = 'jetpack';
3892
			}
3893
		}
3894
3895
		return $jp_menu_order;
3896
	}
3897
3898
	function admin_banner_styles() {
3899
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3900
3901
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3902
			wp_register_style(
3903
				'jetpack-dops-style',
3904
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3905
				array(),
3906
				JETPACK__VERSION
3907
			);
3908
		}
3909
3910
		wp_enqueue_style(
3911
			'jetpack',
3912
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3913
			array( 'jetpack-dops-style' ),
3914
			 JETPACK__VERSION . '-20121016'
3915
		);
3916
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3917
		wp_style_add_data( 'jetpack', 'suffix', $min );
3918
	}
3919
3920
	function plugin_action_links( $actions ) {
3921
3922
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3923
3924
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3925
			return array_merge(
3926
				$jetpack_home,
3927
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3928
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3929
				$actions
3930
				);
3931
			}
3932
3933
		return array_merge( $jetpack_home, $actions );
3934
	}
3935
3936
	/*
3937
	 * Registration flow:
3938
	 * 1 - ::admin_page_load() action=register
3939
	 * 2 - ::try_registration()
3940
	 * 3 - ::register()
3941
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3942
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3943
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3944
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3945
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3946
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3947
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3948
	 *       jetpack_id, jetpack_secret, jetpack_public
3949
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3950
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3951
	 * 5 - user logs in with WP.com account
3952
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3953
	 *		- Jetpack_Client_Server::authorize()
3954
	 *		- Jetpack_Client_Server::get_token()
3955
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3956
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3957
	 *			- which responds with access_token, token_type, scope
3958
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3959
	 *		- Jetpack::activate_default_modules()
3960
	 *     		- Deactivates deprecated plugins
3961
	 *     		- Activates all default modules
3962
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3963
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3964
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3965
	 *     Done!
3966
	 */
3967
3968
	/**
3969
	 * Handles the page load events for the Jetpack admin page
3970
	 */
3971
	function admin_page_load() {
3972
		$error = false;
3973
3974
		// Make sure we have the right body class to hook stylings for subpages off of.
3975
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3976
3977
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3978
			// Should only be used in intermediate redirects to preserve state across redirects
3979
			Jetpack::restate();
3980
		}
3981
3982
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3983
			// @todo: Add validation against a known whitelist
3984
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3985
			// User clicked in the iframe to link their accounts
3986
			if ( ! Jetpack::is_user_connected() ) {
3987
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3988
3989
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3990
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3991
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3992
3993
				if ( isset( $_GET['notes_iframe'] ) )
3994
					$connect_url .= '&notes_iframe';
3995
				wp_redirect( $connect_url );
3996
				exit;
3997
			} else {
3998
				if ( ! isset( $_GET['calypso_env'] ) ) {
3999
					Jetpack::state( 'message', 'already_authorized' );
4000
					wp_safe_redirect( Jetpack::admin_url() );
4001
					exit;
4002
				} else {
4003
					$connect_url = $this->build_connect_url( true, false, $from );
4004
					$connect_url .= '&already_authorized=true';
4005
					wp_redirect( $connect_url );
4006
					exit;
4007
				}
4008
			}
4009
		}
4010
4011
4012
		if ( isset( $_GET['action'] ) ) {
4013
			switch ( $_GET['action'] ) {
4014
			case 'authorize':
4015
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4016
					Jetpack::state( 'message', 'already_authorized' );
4017
					wp_safe_redirect( Jetpack::admin_url() );
4018
					exit;
4019
				}
4020
				Jetpack::log( 'authorize' );
4021
				$client_server = new Jetpack_Client_Server;
4022
				$client_server->client_authorize();
4023
				exit;
4024
			case 'register' :
4025
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4026
					$error = 'cheatin';
4027
					break;
4028
				}
4029
				check_admin_referer( 'jetpack-register' );
4030
				Jetpack::log( 'register' );
4031
				Jetpack::maybe_set_version_option();
4032
				$registered = Jetpack::try_registration();
4033
				if ( is_wp_error( $registered ) ) {
4034
					$error = $registered->get_error_code();
4035
					Jetpack::state( 'error', $error );
4036
					Jetpack::state( 'error', $registered->get_error_message() );
4037
					$this->tracking->record_user_event( 'jpc_register_fail', array(
4038
						'error_code' => $error,
4039
						'error_message' => $registered->get_error_message()
4040
					) );
4041
					break;
4042
				}
4043
4044
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4045
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4046
4047
				$this->tracking->record_user_event( 'jpc_register_success', array(
4048
					'from' => $from
4049
				) );
4050
4051
				$url = $this->build_connect_url( true, $redirect, $from );
4052
4053
				if ( ! empty( $_GET['onboarding'] ) ) {
4054
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4055
				}
4056
4057
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4058
					$url = add_query_arg( 'auth_approved', 'true', $url );
4059
				}
4060
4061
				wp_redirect( $url );
4062
				exit;
4063
			case 'activate' :
4064
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4065
					$error = 'cheatin';
4066
					break;
4067
				}
4068
4069
				$module = stripslashes( $_GET['module'] );
4070
				check_admin_referer( "jetpack_activate-$module" );
4071
				Jetpack::log( 'activate', $module );
4072
				if ( ! Jetpack::activate_module( $module ) ) {
4073
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4074
				}
4075
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4076
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4077
				exit;
4078
			case 'activate_default_modules' :
4079
				check_admin_referer( 'activate_default_modules' );
4080
				Jetpack::log( 'activate_default_modules' );
4081
				Jetpack::restate();
4082
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4083
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4084
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4085
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4086
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4087
				exit;
4088
			case 'disconnect' :
4089
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4090
					$error = 'cheatin';
4091
					break;
4092
				}
4093
4094
				check_admin_referer( 'jetpack-disconnect' );
4095
				Jetpack::log( 'disconnect' );
4096
				Jetpack::disconnect();
4097
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4098
				exit;
4099
			case 'reconnect' :
4100
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4101
					$error = 'cheatin';
4102
					break;
4103
				}
4104
4105
				check_admin_referer( 'jetpack-reconnect' );
4106
				Jetpack::log( 'reconnect' );
4107
				$this->disconnect();
4108
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4109
				exit;
4110 View Code Duplication
			case 'deactivate' :
4111
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4112
					$error = 'cheatin';
4113
					break;
4114
				}
4115
4116
				$modules = stripslashes( $_GET['module'] );
4117
				check_admin_referer( "jetpack_deactivate-$modules" );
4118
				foreach ( explode( ',', $modules ) as $module ) {
4119
					Jetpack::log( 'deactivate', $module );
4120
					Jetpack::deactivate_module( $module );
4121
					Jetpack::state( 'message', 'module_deactivated' );
4122
				}
4123
				Jetpack::state( 'module', $modules );
4124
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4125
				exit;
4126
			case 'unlink' :
4127
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4128
				check_admin_referer( 'jetpack-unlink' );
4129
				Jetpack::log( 'unlink' );
4130
				$this->unlink_user();
4131
				Jetpack::state( 'message', 'unlinked' );
4132
				if ( 'sub-unlink' == $redirect ) {
4133
					wp_safe_redirect( admin_url() );
4134
				} else {
4135
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4136
				}
4137
				exit;
4138
			case 'onboard' :
4139
				if ( ! current_user_can( 'manage_options' ) ) {
4140
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4141
				} else {
4142
					Jetpack::create_onboarding_token();
4143
					$url = $this->build_connect_url( true );
4144
4145
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4146
						$url = add_query_arg( 'onboarding', $token, $url );
4147
					}
4148
4149
					$calypso_env = $this->get_calypso_env();
4150
					if ( ! empty( $calypso_env ) ) {
4151
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4152
					}
4153
4154
					wp_redirect( $url );
4155
					exit;
4156
				}
4157
				exit;
4158
			default:
4159
				/**
4160
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4161
				 *
4162
				 * @since 2.6.0
4163
				 *
4164
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4165
				 */
4166
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4167
			}
4168
		}
4169
4170
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4171
			self::activate_new_modules( true );
4172
		}
4173
4174
		$message_code = Jetpack::state( 'message' );
4175
		if ( Jetpack::state( 'optin-manage' ) ) {
4176
			$activated_manage = $message_code;
4177
			$message_code = 'jetpack-manage';
4178
		}
4179
4180
		switch ( $message_code ) {
4181
		case 'jetpack-manage':
4182
			$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>';
4183
			if ( $activated_manage ) {
4184
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4185
			}
4186
			break;
4187
4188
		}
4189
4190
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4191
4192
		if ( ! empty( $deactivated_plugins ) ) {
4193
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4194
			$deactivated_titles  = array();
4195
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4196
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4197
					continue;
4198
				}
4199
4200
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4201
			}
4202
4203
			if ( $deactivated_titles ) {
4204
				if ( $this->message ) {
4205
					$this->message .= "<br /><br />\n";
4206
				}
4207
4208
				$this->message .= wp_sprintf(
4209
					_n(
4210
						'Jetpack contains the most recent version of the old %l plugin.',
4211
						'Jetpack contains the most recent versions of the old %l plugins.',
4212
						count( $deactivated_titles ),
4213
						'jetpack'
4214
					),
4215
					$deactivated_titles
4216
				);
4217
4218
				$this->message .= "<br />\n";
4219
4220
				$this->message .= _n(
4221
					'The old version has been deactivated and can be removed from your site.',
4222
					'The old versions have been deactivated and can be removed from your site.',
4223
					count( $deactivated_titles ),
4224
					'jetpack'
4225
				);
4226
			}
4227
		}
4228
4229
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4230
4231
		if ( $this->message || $this->error || $this->privacy_checks ) {
4232
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4233
		}
4234
4235
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4236
	}
4237
4238
	function admin_notices() {
4239
4240
		if ( $this->error ) {
4241
?>
4242
<div id="message" class="jetpack-message jetpack-err">
4243
	<div class="squeezer">
4244
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4245
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4246
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4247
<?php	endif; ?>
4248
	</div>
4249
</div>
4250
<?php
4251
		}
4252
4253
		if ( $this->message ) {
4254
?>
4255
<div id="message" class="jetpack-message">
4256
	<div class="squeezer">
4257
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4258
	</div>
4259
</div>
4260
<?php
4261
		}
4262
4263
		if ( $this->privacy_checks ) :
4264
			$module_names = $module_slugs = array();
4265
4266
			$privacy_checks = explode( ',', $this->privacy_checks );
4267
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4268
			foreach ( $privacy_checks as $module_slug ) {
4269
				$module = Jetpack::get_module( $module_slug );
4270
				if ( ! $module ) {
4271
					continue;
4272
				}
4273
4274
				$module_slugs[] = $module_slug;
4275
				$module_names[] = "<strong>{$module['name']}</strong>";
4276
			}
4277
4278
			$module_slugs = join( ',', $module_slugs );
4279
?>
4280
<div id="message" class="jetpack-message jetpack-err">
4281
	<div class="squeezer">
4282
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4283
		<p><?php
4284
			echo wp_kses(
4285
				wptexturize(
4286
					wp_sprintf(
4287
						_nx(
4288
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4289
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4290
							count( $privacy_checks ),
4291
							'%l = list of Jetpack module/feature names',
4292
							'jetpack'
4293
						),
4294
						$module_names
4295
					)
4296
				),
4297
				array( 'strong' => true )
4298
			);
4299
4300
			echo "\n<br />\n";
4301
4302
			echo wp_kses(
4303
				sprintf(
4304
					_nx(
4305
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4306
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4307
						count( $privacy_checks ),
4308
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4309
						'jetpack'
4310
					),
4311
					wp_nonce_url(
4312
						Jetpack::admin_url(
4313
							array(
4314
								'page'   => 'jetpack',
4315
								'action' => 'deactivate',
4316
								'module' => urlencode( $module_slugs ),
4317
							)
4318
						),
4319
						"jetpack_deactivate-$module_slugs"
4320
					),
4321
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4322
				),
4323
				array( 'a' => array( 'href' => true, 'title' => true ) )
4324
			);
4325
		?></p>
4326
	</div>
4327
</div>
4328
<?php endif;
4329
	}
4330
4331
	/**
4332
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4333
	 */
4334
	function stat( $group, $detail ) {
4335
		if ( ! isset( $this->stats[ $group ] ) )
4336
			$this->stats[ $group ] = array();
4337
		$this->stats[ $group ][] = $detail;
4338
	}
4339
4340
	/**
4341
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4342
	 */
4343
	function do_stats( $method = '' ) {
4344
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4345
			foreach ( $this->stats as $group => $stats ) {
4346
				if ( is_array( $stats ) && count( $stats ) ) {
4347
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4348
					if ( 'server_side' === $method ) {
4349
						self::do_server_side_stat( $args );
4350
					} else {
4351
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4352
					}
4353
				}
4354
				unset( $this->stats[ $group ] );
4355
			}
4356
		}
4357
	}
4358
4359
	/**
4360
	 * Runs stats code for a one-off, server-side.
4361
	 *
4362
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4363
	 *
4364
	 * @return bool If it worked.
4365
	 */
4366
	static function do_server_side_stat( $args ) {
4367
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4368
		if ( is_wp_error( $response ) )
4369
			return false;
4370
4371
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4372
			return false;
4373
4374
		return true;
4375
	}
4376
4377
	/**
4378
	 * Builds the stats url.
4379
	 *
4380
	 * @param $args array|string The arguments to append to the URL.
4381
	 *
4382
	 * @return string The URL to be pinged.
4383
	 */
4384
	static function build_stats_url( $args ) {
4385
		$defaults = array(
4386
			'v'    => 'wpcom2',
4387
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4388
		);
4389
		$args     = wp_parse_args( $args, $defaults );
4390
		/**
4391
		 * Filter the URL used as the Stats tracking pixel.
4392
		 *
4393
		 * @since 2.3.2
4394
		 *
4395
		 * @param string $url Base URL used as the Stats tracking pixel.
4396
		 */
4397
		$base_url = apply_filters(
4398
			'jetpack_stats_base_url',
4399
			'https://pixel.wp.com/g.gif'
4400
		);
4401
		$url      = add_query_arg( $args, $base_url );
4402
		return $url;
4403
	}
4404
4405
	static function translate_current_user_to_role() {
4406
		foreach ( self::$capability_translations as $role => $cap ) {
4407
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4408
				return $role;
4409
			}
4410
		}
4411
4412
		return false;
4413
	}
4414
4415
	static function translate_user_to_role( $user ) {
4416
		foreach ( self::$capability_translations as $role => $cap ) {
4417
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4418
				return $role;
4419
			}
4420
		}
4421
4422
		return false;
4423
    }
4424
4425
	static function translate_role_to_cap( $role ) {
4426
		if ( ! isset( self::$capability_translations[$role] ) ) {
4427
			return false;
4428
		}
4429
4430
		return self::$capability_translations[$role];
4431
	}
4432
4433
	static function sign_role( $role, $user_id = null ) {
4434
		if ( empty( $user_id ) ) {
4435
			$user_id = (int) get_current_user_id();
4436
		}
4437
4438
		if ( ! $user_id  ) {
4439
			return false;
4440
		}
4441
4442
		$token = Jetpack_Data::get_access_token();
4443
		if ( ! $token || is_wp_error( $token ) ) {
4444
			return false;
4445
		}
4446
4447
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4448
	}
4449
4450
4451
	/**
4452
	 * Builds a URL to the Jetpack connection auth page
4453
	 *
4454
	 * @since 3.9.5
4455
	 *
4456
	 * @param bool $raw If true, URL will not be escaped.
4457
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4458
	 *                              If string, will be a custom redirect.
4459
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4460
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4461
	 *
4462
	 * @return string Connect URL
4463
	 */
4464
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4465
		$site_id = Jetpack_Options::get_option( 'id' );
4466
		$blog_token = Jetpack_Data::get_access_token();
4467
4468
		if ( $register || ! $blog_token || ! $site_id ) {
4469
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4470
4471
			if ( ! empty( $redirect ) ) {
4472
				$url = add_query_arg(
4473
					'redirect',
4474
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4475
					$url
4476
				);
4477
			}
4478
4479
			if( is_network_admin() ) {
4480
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4481
			}
4482
		} else {
4483
4484
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4485
			// because otherwise this logic can get us in to a loop.
4486
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4487
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4488
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4489
4490
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4491
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4492
					'1.1'
4493
				);
4494
4495
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4496
4497
					// Generating a register URL instead to refresh the existing token
4498
					return $this->build_connect_url( $raw, $redirect, $from, true );
4499
				}
4500
			}
4501
4502
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4503
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4504
			}
4505
4506
			$role = self::translate_current_user_to_role();
4507
			$signed_role = self::sign_role( $role );
4508
4509
			$user = wp_get_current_user();
4510
4511
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4512
			$redirect = $redirect
4513
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4514
				: $jetpack_admin_page;
4515
4516
			if( isset( $_REQUEST['is_multisite'] ) ) {
4517
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4518
			}
4519
4520
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4521
4522
			/**
4523
			 * Filter the type of authorization.
4524
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4525
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4526
			 *
4527
			 * @since 4.3.3
4528
			 *
4529
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4530
			 */
4531
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4532
4533
4534
			$tracks = new Automattic\Jetpack\Tracking();
4535
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4536
4537
			$args = urlencode_deep(
4538
				array(
4539
					'response_type' => 'code',
4540
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4541
					'redirect_uri'  => add_query_arg(
4542
						array(
4543
							'action'   => 'authorize',
4544
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4545
							'redirect' => urlencode( $redirect ),
4546
						),
4547
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4548
					),
4549
					'state'         => $user->ID,
4550
					'scope'         => $signed_role,
4551
					'user_email'    => $user->user_email,
4552
					'user_login'    => $user->user_login,
4553
					'is_active'     => Jetpack::is_active(),
4554
					'jp_version'    => JETPACK__VERSION,
4555
					'auth_type'     => $auth_type,
4556
					'secret'        => $secrets['secret_1'],
4557
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4558
					'blogname'      => get_option( 'blogname' ),
4559
					'site_url'      => site_url(),
4560
					'home_url'      => home_url(),
4561
					'site_icon'     => get_site_icon_url(),
4562
					'site_lang'     => get_locale(),
4563
					'_ui'           => $tracks_identity['_ui'],
4564
					'_ut'           => $tracks_identity['_ut'],
4565
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4566
				)
4567
			);
4568
4569
			self::apply_activation_source_to_args( $args );
4570
4571
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4572
		}
4573
4574
		if ( $from ) {
4575
			$url = add_query_arg( 'from', $from, $url );
4576
		}
4577
4578
		// Ensure that class to get the affiliate code is loaded
4579
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4580
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4581
		}
4582
		// Get affiliate code and add it to the URL
4583
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4584
4585
		$calypso_env = $this->get_calypso_env();
4586
4587
		if ( ! empty( $calypso_env ) ) {
4588
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4589
		}
4590
4591
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4592
	}
4593
4594
	/**
4595
	 * Get our assumed site creation date.
4596
	 * Calculated based on the earlier date of either:
4597
	 * - Earliest admin user registration date.
4598
	 * - Earliest date of post of any post type.
4599
	 *
4600
	 * @since 7.2.0
4601
	 *
4602
	 * @return string Assumed site creation date and time.
4603
	 */
4604
	public static function get_assumed_site_creation_date() {
4605
		$earliest_registered_users = get_users( array(
4606
			'role'    => 'administrator',
4607
			'orderby' => 'user_registered',
4608
			'order'   => 'ASC',
4609
			'fields'  => array( 'user_registered' ),
4610
			'number'  => 1,
4611
		) );
4612
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4613
4614
		$earliest_posts = get_posts( array(
4615
			'posts_per_page' => 1,
4616
			'post_type'      => 'any',
4617
			'post_status'    => 'any',
4618
			'orderby'        => 'date',
4619
			'order'          => 'ASC',
4620
		) );
4621
4622
		// If there are no posts at all, we'll count only on user registration date.
4623
		if ( $earliest_posts ) {
4624
			$earliest_post_date = $earliest_posts[0]->post_date;
4625
		} else {
4626
			$earliest_post_date = PHP_INT_MAX;
4627
		}
4628
4629
		return min( $earliest_registration_date, $earliest_post_date );
4630
	}
4631
4632
	public static function apply_activation_source_to_args( &$args ) {
4633
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4634
4635
		if ( $activation_source_name ) {
4636
			$args['_as'] = urlencode( $activation_source_name );
4637
		}
4638
4639
		if ( $activation_source_keyword ) {
4640
			$args['_ak'] = urlencode( $activation_source_keyword );
4641
		}
4642
	}
4643
4644
	function build_reconnect_url( $raw = false ) {
4645
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4646
		return $raw ? $url : esc_url( $url );
4647
	}
4648
4649
	public static function admin_url( $args = null ) {
4650
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4651
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4652
		return $url;
4653
	}
4654
4655
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4656
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4657
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4658
	}
4659
4660
	function dismiss_jetpack_notice() {
4661
4662
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4663
			return;
4664
		}
4665
4666
		switch( $_GET['jetpack-notice'] ) {
4667
			case 'dismiss':
4668
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4669
4670
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4671
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4672
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4673
				}
4674
				break;
4675
			case 'jetpack-protect-multisite-opt-out':
4676
4677
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4678
					// Don't show the banner again
4679
4680
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4681
					// redirect back to the page that had the notice
4682
					if ( wp_get_referer() ) {
4683
						wp_safe_redirect( wp_get_referer() );
4684
					} else {
4685
						// Take me to Jetpack
4686
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4687
					}
4688
				}
4689
				break;
4690
		}
4691
	}
4692
4693
	public static function sort_modules( $a, $b ) {
4694
		if ( $a['sort'] == $b['sort'] )
4695
			return 0;
4696
4697
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4698
	}
4699
4700
	function ajax_recheck_ssl() {
4701
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4702
		$result = Jetpack::permit_ssl( true );
4703
		wp_send_json( array(
4704
			'enabled' => $result,
4705
			'message' => get_transient( 'jetpack_https_test_message' )
4706
		) );
4707
	}
4708
4709
/* Client API */
4710
4711
	/**
4712
	 * Returns the requested Jetpack API URL
4713
	 *
4714
	 * @return string
4715
	 */
4716
	public static function api_url( $relative_url ) {
4717
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4718
	}
4719
4720
	/**
4721
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4722
	 */
4723
	public static function fix_url_for_bad_hosts( $url ) {
4724
		if ( 0 !== strpos( $url, 'https://' ) ) {
4725
			return $url;
4726
		}
4727
4728
		switch ( JETPACK_CLIENT__HTTPS ) {
4729
			case 'ALWAYS' :
4730
				return $url;
4731
			case 'NEVER' :
4732
				return set_url_scheme( $url, 'http' );
4733
			// default : case 'AUTO' :
4734
		}
4735
4736
		// we now return the unmodified SSL URL by default, as a security precaution
4737
		return $url;
4738
	}
4739
4740
	/**
4741
	 * Create a random secret for validating onboarding payload
4742
	 *
4743
	 * @return string Secret token
4744
	 */
4745
	public static function create_onboarding_token() {
4746
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4747
			$token = wp_generate_password( 32, false );
4748
			Jetpack_Options::update_option( 'onboarding', $token );
4749
		}
4750
4751
		return $token;
4752
	}
4753
4754
	/**
4755
	 * Remove the onboarding token
4756
	 *
4757
	 * @return bool True on success, false on failure
4758
	 */
4759
	public static function invalidate_onboarding_token() {
4760
		return Jetpack_Options::delete_option( 'onboarding' );
4761
	}
4762
4763
	/**
4764
	 * Validate an onboarding token for a specific action
4765
	 *
4766
	 * @return boolean True if token/action pair is accepted, false if not
4767
	 */
4768
	public static function validate_onboarding_token_action( $token, $action ) {
4769
		// Compare tokens, bail if tokens do not match
4770
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4771
			return false;
4772
		}
4773
4774
		// List of valid actions we can take
4775
		$valid_actions = array(
4776
			'/jetpack/v4/settings',
4777
		);
4778
4779
		// Whitelist the action
4780
		if ( ! in_array( $action, $valid_actions ) ) {
4781
			return false;
4782
		}
4783
4784
		return true;
4785
	}
4786
4787
	/**
4788
	 * Checks to see if the URL is using SSL to connect with Jetpack
4789
	 *
4790
	 * @since 2.3.3
4791
	 * @return boolean
4792
	 */
4793
	public static function permit_ssl( $force_recheck = false ) {
4794
		// Do some fancy tests to see if ssl is being supported
4795
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4796
			$message = '';
4797
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4798
				$ssl = 0;
4799
			} else {
4800
				switch ( JETPACK_CLIENT__HTTPS ) {
4801
					case 'NEVER':
4802
						$ssl = 0;
4803
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4804
						break;
4805
					case 'ALWAYS':
4806
					case 'AUTO':
4807
					default:
4808
						$ssl = 1;
4809
						break;
4810
				}
4811
4812
				// If it's not 'NEVER', test to see
4813
				if ( $ssl ) {
4814
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4815
						$ssl = 0;
4816
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4817
					} else {
4818
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4819
						if ( is_wp_error( $response ) ) {
4820
							$ssl = 0;
4821
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4822
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4823
							$ssl = 0;
4824
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4825
						}
4826
					}
4827
				}
4828
			}
4829
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4830
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4831
		}
4832
4833
		return (bool) $ssl;
4834
	}
4835
4836
	/*
4837
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4838
	 */
4839
	public function alert_auto_ssl_fail() {
4840
		if ( ! current_user_can( 'manage_options' ) )
4841
			return;
4842
4843
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4844
		?>
4845
4846
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4847
			<div class="jp-banner__content">
4848
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4849
				<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>
4850
				<p>
4851
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4852
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4853
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4854
				</p>
4855
				<p>
4856
					<?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' ),
4857
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4858
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4859
				</p>
4860
			</div>
4861
		</div>
4862
		<style>
4863
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4864
		</style>
4865
		<script type="text/javascript">
4866
			jQuery( document ).ready( function( $ ) {
4867
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4868
					var $this = $( this );
4869
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4870
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4871
					e.preventDefault();
4872
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4873
					$.post( ajaxurl, data )
4874
					  .done( function( response ) {
4875
					  	if ( response.enabled ) {
4876
					  		$( '#jetpack-ssl-warning' ).hide();
4877
					  	} else {
4878
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4879
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4880
					  	}
4881
					  }.bind( $this ) );
4882
				} );
4883
			} );
4884
		</script>
4885
4886
		<?php
4887
	}
4888
4889
	/**
4890
	 * Returns the Jetpack XML-RPC API
4891
	 *
4892
	 * @return string
4893
	 */
4894
	public static function xmlrpc_api_url() {
4895
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4896
		return untrailingslashit( $base ) . '/xmlrpc.php';
4897
	}
4898
4899
	public static function connection() {
4900
		return self::init()->connection_manager;
4901
	}
4902
4903
	/**
4904
	 * Creates two secret tokens and the end of life timestamp for them.
4905
	 *
4906
	 * Note these tokens are unique per call, NOT static per site for connecting.
4907
	 *
4908
	 * @since 2.6
4909
	 * @return array
4910
	 */
4911
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4912
		if ( false === $user_id ) {
4913
			$user_id = get_current_user_id();
4914
		}
4915
4916
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4917
	}
4918
4919
	public static function get_secrets( $action, $user_id ) {
4920
		$secrets = self::connection()->get_secrets( $action, $user_id );
4921
4922
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4923
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4924
		}
4925
4926
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4927
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4928
		}
4929
4930
		return $secrets;
4931
	}
4932
4933
	/**
4934
	 * @deprecated 7.5 Use Connection_Manager instead.
4935
	 *
4936
	 * @param $action
4937
	 * @param $user_id
4938
	 */
4939
	public static function delete_secrets( $action, $user_id ) {
4940
		return self::connection()->delete_secrets( $action, $user_id );
4941
	}
4942
4943
	/**
4944
	 * Builds the timeout limit for queries talking with the wpcom servers.
4945
	 *
4946
	 * Based on local php max_execution_time in php.ini
4947
	 *
4948
	 * @since 2.6
4949
	 * @return int
4950
	 * @deprecated
4951
	 **/
4952
	public function get_remote_query_timeout_limit() {
4953
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4954
		return Jetpack::get_max_execution_time();
4955
	}
4956
4957
	/**
4958
	 * Builds the timeout limit for queries talking with the wpcom servers.
4959
	 *
4960
	 * Based on local php max_execution_time in php.ini
4961
	 *
4962
	 * @since 5.4
4963
	 * @return int
4964
	 **/
4965
	public static function get_max_execution_time() {
4966
		$timeout = (int) ini_get( 'max_execution_time' );
4967
4968
		// Ensure exec time set in php.ini
4969
		if ( ! $timeout ) {
4970
			$timeout = 30;
4971
		}
4972
		return $timeout;
4973
	}
4974
4975
	/**
4976
	 * Sets a minimum request timeout, and returns the current timeout
4977
	 *
4978
	 * @since 5.4
4979
	 **/
4980
	public static function set_min_time_limit( $min_timeout ) {
4981
		$timeout = self::get_max_execution_time();
4982
		if ( $timeout < $min_timeout ) {
4983
			$timeout = $min_timeout;
4984
			set_time_limit( $timeout );
4985
		}
4986
		return $timeout;
4987
	}
4988
4989
4990
	/**
4991
	 * Takes the response from the Jetpack register new site endpoint and
4992
	 * verifies it worked properly.
4993
	 *
4994
	 * @since 2.6
4995
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4996
	 **/
4997
	public function validate_remote_register_response( $response ) {
4998
	  if ( is_wp_error( $response ) ) {
4999
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5000
		}
5001
5002
		$code   = wp_remote_retrieve_response_code( $response );
5003
		$entity = wp_remote_retrieve_body( $response );
5004
		if ( $entity )
5005
			$registration_response = json_decode( $entity );
5006
		else
5007
			$registration_response = false;
5008
5009
		$code_type = intval( $code / 100 );
5010
		if ( 5 == $code_type ) {
5011
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5012
		} elseif ( 408 == $code ) {
5013
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5014
		} elseif ( ! empty( $registration_response->error ) ) {
5015
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5016
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5017
			} else {
5018
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5019
			}
5020
5021
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5022
		} elseif ( 200 != $code ) {
5023
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5024
		}
5025
5026
		// Jetpack ID error block
5027
		if ( empty( $registration_response->jetpack_id ) ) {
5028
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5029
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5030
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5031
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5032
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5033
		}
5034
5035
	    return $registration_response;
5036
	}
5037
	/**
5038
	 * @return bool|WP_Error
5039
	 */
5040
	public static function register() {
5041
		$this->tracking->record_user_event( 'jpc_register_begin' );
0 ignored issues
show
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
5042
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5043
		$secrets = Jetpack::generate_secrets( 'register' );
5044
5045 View Code Duplication
		if (
5046
			empty( $secrets['secret_1'] ) ||
5047
			empty( $secrets['secret_2'] ) ||
5048
			empty( $secrets['exp'] )
5049
		) {
5050
			return new Jetpack_Error( 'missing_secrets' );
5051
		}
5052
5053
		// better to try (and fail) to set a higher timeout than this system
5054
		// supports than to have register fail for more users than it should
5055
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5056
5057
		$gmt_offset = get_option( 'gmt_offset' );
5058
		if ( ! $gmt_offset ) {
5059
			$gmt_offset = 0;
5060
		}
5061
5062
		$stats_options = get_option( 'stats_options' );
5063
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5064
5065
		$tracks = new Automattic\Jetpack\Tracking();
5066
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5067
5068
		$args = array(
5069
			'method'  => 'POST',
5070
			'body'    => array(
5071
				'siteurl'         => site_url(),
5072
				'home'            => home_url(),
5073
				'gmt_offset'      => $gmt_offset,
5074
				'timezone_string' => (string) get_option( 'timezone_string' ),
5075
				'site_name'       => (string) get_option( 'blogname' ),
5076
				'secret_1'        => $secrets['secret_1'],
5077
				'secret_2'        => $secrets['secret_2'],
5078
				'site_lang'       => get_locale(),
5079
				'timeout'         => $timeout,
5080
				'stats_id'        => $stats_id,
5081
				'state'           => get_current_user_id(),
5082
				'_ui'             => $tracks_identity['_ui'],
5083
				'_ut'             => $tracks_identity['_ut'],
5084
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5085
				'jetpack_version' => JETPACK__VERSION
5086
			),
5087
			'headers' => array(
5088
				'Accept' => 'application/json',
5089
			),
5090
			'timeout' => $timeout,
5091
		);
5092
5093
		self::apply_activation_source_to_args( $args['body'] );
5094
5095
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5096
5097
		// Make sure the response is valid and does not contain any Jetpack errors
5098
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5099
		if ( is_wp_error( $registration_details ) ) {
5100
			return $registration_details;
5101
		} elseif ( ! $registration_details ) {
5102
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5103
		}
5104
5105 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5106
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5107
		}
5108
5109
		if ( isset( $registration_details->jetpack_public ) ) {
5110
			$jetpack_public = (int) $registration_details->jetpack_public;
5111
		} else {
5112
			$jetpack_public = false;
5113
		}
5114
5115
		Jetpack_Options::update_options(
5116
			array(
5117
				'id'         => (int)    $registration_details->jetpack_id,
5118
				'blog_token' => (string) $registration_details->jetpack_secret,
5119
				'public'     => $jetpack_public,
5120
			)
5121
		);
5122
5123
		/**
5124
		 * Fires when a site is registered on WordPress.com.
5125
		 *
5126
		 * @since 3.7.0
5127
		 *
5128
		 * @param int $json->jetpack_id Jetpack Blog ID.
5129
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5130
		 * @param int|bool $jetpack_public Is the site public.
5131
		 */
5132
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5133
5134
		// Initialize Jump Start for the first and only time.
5135
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5136
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5137
5138
			$jetpack = Jetpack::init();
5139
5140
			$jetpack->stat( 'jumpstart', 'unique-views' );
5141
			$jetpack->do_stats( 'server_side' );
5142
		};
5143
5144
		return true;
5145
	}
5146
5147
	/**
5148
	 * If the db version is showing something other that what we've got now, bump it to current.
5149
	 *
5150
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5151
	 */
5152
	public static function maybe_set_version_option() {
5153
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5154
		if ( JETPACK__VERSION != $version ) {
5155
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5156
5157
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5158
				/** This action is documented in class.jetpack.php */
5159
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5160
			}
5161
5162
			return true;
5163
		}
5164
		return false;
5165
	}
5166
5167
/* Client Server API */
5168
5169
	/**
5170
	 * Loads the Jetpack XML-RPC client
5171
	 */
5172
	public static function load_xml_rpc_client() {
5173
		require_once ABSPATH . WPINC . '/class-IXR.php';
5174
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5175
	}
5176
5177
	/**
5178
	 * Resets the saved authentication state in between testing requests.
5179
	 */
5180
	public function reset_saved_auth_state() {
5181
		$this->xmlrpc_verification = null;
5182
		$this->rest_authentication_status = null;
5183
	}
5184
5185
	function verify_xml_rpc_signature() {
5186
		if ( $this->xmlrpc_verification ) {
5187
			return $this->xmlrpc_verification;
5188
		}
5189
5190
		// It's not for us
5191
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5192
			return false;
5193
		}
5194
5195
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5196
		if (
5197
			empty( $token_key )
5198
		||
5199
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5200
		) {
5201
			return false;
5202
		}
5203
5204
		if ( '0' === $user_id ) {
5205
			$token_type = 'blog';
5206
			$user_id = 0;
5207
		} else {
5208
			$token_type = 'user';
5209
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5210
				return false;
5211
			}
5212
			$user_id = (int) $user_id;
5213
5214
			$user = new WP_User( $user_id );
5215
			if ( ! $user || ! $user->exists() ) {
5216
				return false;
5217
			}
5218
		}
5219
5220
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
5221
		if ( ! $token ) {
5222
			return false;
5223
		}
5224
5225
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5226
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5227
			$post_data   = $_POST;
5228
			$file_hashes = array();
5229
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5230
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5231
					continue;
5232
				}
5233
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5234
				$file_hashes[$post_data_key] = $post_data_value;
5235
			}
5236
5237
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5238
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5239
				$post_data[$post_data_key] = $post_data_value;
5240
			}
5241
5242
			ksort( $post_data );
5243
5244
			$body = http_build_query( stripslashes_deep( $post_data ) );
5245
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5246
			$body = file_get_contents( 'php://input' );
5247
		} else {
5248
			$body = null;
5249
		}
5250
5251
		$signature = $jetpack_signature->sign_current_request(
5252
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5253
		);
5254
5255
		if ( ! $signature ) {
5256
			return false;
5257
		} else if ( is_wp_error( $signature ) ) {
5258
			return $signature;
5259
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5260
			return false;
5261
		}
5262
5263
		$timestamp = (int) $_GET['timestamp'];
5264
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5265
5266
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5267
			return false;
5268
		}
5269
5270
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5271
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5272
			if ( ! empty( $_GET['onboarding'] ) ) {
5273
				$jpo = $_GET;
5274
			} else {
5275
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5276
			}
5277
5278
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5279
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5280
5281
			if (
5282
				isset( $jpo_user ) && isset( $jpo_token ) &&
5283
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5284
				isset( $_GET['rest_route'] ) &&
5285
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5286
			) {
5287
				$jpUser = get_user_by( 'email', $jpo_user );
5288
				if ( is_a( $jpUser, 'WP_User' ) ) {
5289
					wp_set_current_user( $jpUser->ID );
5290
					$user_can = is_multisite()
5291
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5292
						: current_user_can( 'manage_options' );
5293
					if ( $user_can ) {
5294
						$token_type = 'user';
5295
						$token->external_user_id = $jpUser->ID;
5296
					}
5297
				}
5298
			}
5299
		}
5300
5301
		$this->xmlrpc_verification = array(
5302
			'type'      => $token_type,
5303
			'token_key' => $token_key,
5304
			'user_id'   => $token->external_user_id,
5305
		);
5306
5307
		return $this->xmlrpc_verification;
5308
	}
5309
5310
	/**
5311
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5312
	 */
5313
	function authenticate_jetpack( $user, $username, $password ) {
5314
		if ( is_a( $user, 'WP_User' ) ) {
5315
			return $user;
5316
		}
5317
5318
		$token_details = $this->verify_xml_rpc_signature();
5319
5320
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5321
			return $user;
5322
		}
5323
5324
		if ( 'user' !== $token_details['type'] ) {
5325
			return $user;
5326
		}
5327
5328
		if ( ! $token_details['user_id'] ) {
5329
			return $user;
5330
		}
5331
5332
		nocache_headers();
5333
5334
		return new WP_User( $token_details['user_id'] );
5335
	}
5336
5337
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5338
	// Uses the existing XMLRPC request signing implementation.
5339
	function wp_rest_authenticate( $user ) {
5340
		if ( ! empty( $user ) ) {
5341
			// Another authentication method is in effect.
5342
			return $user;
5343
		}
5344
5345
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5346
			// Nothing to do for this authentication method.
5347
			return null;
5348
		}
5349
5350
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5351
			// Nothing to do for this authentication method.
5352
			return null;
5353
		}
5354
5355
		// Ensure that we always have the request body available.  At this
5356
		// point, the WP REST API code to determine the request body has not
5357
		// run yet.  That code may try to read from 'php://input' later, but
5358
		// this can only be done once per request in PHP versions prior to 5.6.
5359
		// So we will go ahead and perform this read now if needed, and save
5360
		// the request body where both the Jetpack signature verification code
5361
		// and the WP REST API code can see it.
5362
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5363
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5364
		}
5365
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5366
5367
		// Only support specific request parameters that have been tested and
5368
		// are known to work with signature verification.  A different method
5369
		// can be passed to the WP REST API via the '?_method=' parameter if
5370
		// needed.
5371
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5372
			$this->rest_authentication_status = new WP_Error(
5373
				'rest_invalid_request',
5374
				__( 'This request method is not supported.', 'jetpack' ),
5375
				array( 'status' => 400 )
5376
			);
5377
			return null;
5378
		}
5379
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5380
			$this->rest_authentication_status = new WP_Error(
5381
				'rest_invalid_request',
5382
				__( 'This request method does not support body parameters.', 'jetpack' ),
5383
				array( 'status' => 400 )
5384
			);
5385
			return null;
5386
		}
5387
5388
		$verified = $this->verify_xml_rpc_signature();
5389
5390
		if ( is_wp_error( $verified ) ) {
5391
			$this->rest_authentication_status = $verified;
5392
			return null;
5393
		}
5394
5395
		if (
5396
			$verified &&
5397
			isset( $verified['type'] ) &&
5398
			'user' === $verified['type'] &&
5399
			! empty( $verified['user_id'] )
5400
		) {
5401
			// Authentication successful.
5402
			$this->rest_authentication_status = true;
5403
			return $verified['user_id'];
5404
		}
5405
5406
		// Something else went wrong.  Probably a signature error.
5407
		$this->rest_authentication_status = new WP_Error(
5408
			'rest_invalid_signature',
5409
			__( 'The request is not signed correctly.', 'jetpack' ),
5410
			array( 'status' => 400 )
5411
		);
5412
		return null;
5413
	}
5414
5415
	/**
5416
	 * Report authentication status to the WP REST API.
5417
	 *
5418
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5419
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5420
	 */
5421
	public function wp_rest_authentication_errors( $value ) {
5422
		if ( $value !== null ) {
5423
			return $value;
5424
		}
5425
		return $this->rest_authentication_status;
5426
	}
5427
5428
	function add_nonce( $timestamp, $nonce ) {
5429
		global $wpdb;
5430
		static $nonces_used_this_request = array();
5431
5432
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5433
			return $nonces_used_this_request["$timestamp:$nonce"];
5434
		}
5435
5436
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5437
		$timestamp = (int) $timestamp;
5438
		$nonce     = esc_sql( $nonce );
5439
5440
		// Raw query so we can avoid races: add_option will also update
5441
		$show_errors = $wpdb->show_errors( false );
5442
5443
		$old_nonce = $wpdb->get_row(
5444
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5445
		);
5446
5447
		if ( is_null( $old_nonce ) ) {
5448
			$return = $wpdb->query(
5449
				$wpdb->prepare(
5450
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5451
					"jetpack_nonce_{$timestamp}_{$nonce}",
5452
					time(),
5453
					'no'
5454
				)
5455
			);
5456
		} else {
5457
			$return = false;
5458
		}
5459
5460
		$wpdb->show_errors( $show_errors );
5461
5462
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5463
5464
		return $return;
5465
	}
5466
5467
	/**
5468
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5469
	 * Capture it here so we can verify the signature later.
5470
	 */
5471
	function xmlrpc_methods( $methods ) {
5472
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5473
		return $methods;
5474
	}
5475
5476
	function public_xmlrpc_methods( $methods ) {
5477
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5478
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5479
		}
5480
		return $methods;
5481
	}
5482
5483
	function jetpack_getOptions( $args ) {
5484
		global $wp_xmlrpc_server;
5485
5486
		$wp_xmlrpc_server->escape( $args );
5487
5488
		$username	= $args[1];
5489
		$password	= $args[2];
5490
5491
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5492
			return $wp_xmlrpc_server->error;
5493
		}
5494
5495
		$options = array();
5496
		$user_data = $this->get_connected_user_data();
5497
		if ( is_array( $user_data ) ) {
5498
			$options['jetpack_user_id'] = array(
5499
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5500
				'readonly'      => true,
5501
				'value'         => $user_data['ID'],
5502
			);
5503
			$options['jetpack_user_login'] = array(
5504
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5505
				'readonly'      => true,
5506
				'value'         => $user_data['login'],
5507
			);
5508
			$options['jetpack_user_email'] = array(
5509
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5510
				'readonly'      => true,
5511
				'value'         => $user_data['email'],
5512
			);
5513
			$options['jetpack_user_site_count'] = array(
5514
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5515
				'readonly'      => true,
5516
				'value'         => $user_data['site_count'],
5517
			);
5518
		}
5519
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5520
		$args = stripslashes_deep( $args );
5521
		return $wp_xmlrpc_server->wp_getOptions( $args );
5522
	}
5523
5524
	function xmlrpc_options( $options ) {
5525
		$jetpack_client_id = false;
5526
		if ( self::is_active() ) {
5527
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5528
		}
5529
		$options['jetpack_version'] = array(
5530
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5531
				'readonly'      => true,
5532
				'value'         => JETPACK__VERSION,
5533
		);
5534
5535
		$options['jetpack_client_id'] = array(
5536
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5537
				'readonly'      => true,
5538
				'value'         => $jetpack_client_id,
5539
		);
5540
		return $options;
5541
	}
5542
5543
	public static function clean_nonces( $all = false ) {
5544
		global $wpdb;
5545
5546
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5547
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5548
5549
		if ( true !== $all ) {
5550
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5551
			$sql_args[] = time() - 3600;
5552
		}
5553
5554
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5555
5556
		$sql = $wpdb->prepare( $sql, $sql_args );
5557
5558
		for ( $i = 0; $i < 1000; $i++ ) {
5559
			if ( ! $wpdb->query( $sql ) ) {
5560
				break;
5561
			}
5562
		}
5563
	}
5564
5565
	/**
5566
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5567
	 * SET: state( $key, $value );
5568
	 * GET: $value = state( $key );
5569
	 *
5570
	 * @param string $key
5571
	 * @param string $value
5572
	 * @param bool $restate private
5573
	 */
5574
	public static function state( $key = null, $value = null, $restate = false ) {
5575
		static $state = array();
5576
		static $path, $domain;
5577
		if ( ! isset( $path ) ) {
5578
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5579
			$admin_url = Jetpack::admin_url();
5580
			$bits      = wp_parse_url( $admin_url );
5581
5582
			if ( is_array( $bits ) ) {
5583
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5584
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5585
			} else {
5586
				$path = $domain = null;
5587
			}
5588
		}
5589
5590
		// Extract state from cookies and delete cookies
5591
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5592
			$yum = $_COOKIE[ 'jetpackState' ];
5593
			unset( $_COOKIE[ 'jetpackState' ] );
5594
			foreach ( $yum as $k => $v ) {
5595
				if ( strlen( $v ) )
5596
					$state[ $k ] = $v;
5597
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5598
			}
5599
		}
5600
5601
		if ( $restate ) {
5602
			foreach ( $state as $k => $v ) {
5603
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5604
			}
5605
			return;
5606
		}
5607
5608
		// Get a state variable
5609
		if ( isset( $key ) && ! isset( $value ) ) {
5610
			if ( array_key_exists( $key, $state ) )
5611
				return $state[ $key ];
5612
			return null;
5613
		}
5614
5615
		// Set a state variable
5616
		if ( isset ( $key ) && isset( $value ) ) {
5617
			if( is_array( $value ) && isset( $value[0] ) ) {
5618
				$value = $value[0];
5619
			}
5620
			$state[ $key ] = $value;
5621
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5622
		}
5623
	}
5624
5625
	public static function restate() {
5626
		Jetpack::state( null, null, true );
5627
	}
5628
5629
	public static function check_privacy( $file ) {
5630
		static $is_site_publicly_accessible = null;
5631
5632
		if ( is_null( $is_site_publicly_accessible ) ) {
5633
			$is_site_publicly_accessible = false;
5634
5635
			Jetpack::load_xml_rpc_client();
5636
			$rpc = new Jetpack_IXR_Client();
5637
5638
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5639
			if ( $success ) {
5640
				$response = $rpc->getResponse();
5641
				if ( $response ) {
5642
					$is_site_publicly_accessible = true;
5643
				}
5644
			}
5645
5646
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5647
		}
5648
5649
		if ( $is_site_publicly_accessible ) {
5650
			return;
5651
		}
5652
5653
		$module_slug = self::get_module_slug( $file );
5654
5655
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5656
		if ( ! $privacy_checks ) {
5657
			$privacy_checks = $module_slug;
5658
		} else {
5659
			$privacy_checks .= ",$module_slug";
5660
		}
5661
5662
		Jetpack::state( 'privacy_checks', $privacy_checks );
5663
	}
5664
5665
	/**
5666
	 * Helper method for multicall XMLRPC.
5667
	 */
5668
	public static function xmlrpc_async_call() {
5669
		global $blog_id;
5670
		static $clients = array();
5671
5672
		$client_blog_id = is_multisite() ? $blog_id : 0;
5673
5674
		if ( ! isset( $clients[$client_blog_id] ) ) {
5675
			Jetpack::load_xml_rpc_client();
5676
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5677
			if ( function_exists( 'ignore_user_abort' ) ) {
5678
				ignore_user_abort( true );
5679
			}
5680
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5681
		}
5682
5683
		$args = func_get_args();
5684
5685
		if ( ! empty( $args[0] ) ) {
5686
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5687
		} elseif ( is_multisite() ) {
5688
			foreach ( $clients as $client_blog_id => $client ) {
5689
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5690
					continue;
5691
				}
5692
5693
				$switch_success = switch_to_blog( $client_blog_id, true );
5694
				if ( ! $switch_success ) {
5695
					continue;
5696
				}
5697
5698
				flush();
5699
				$client->query();
5700
5701
				restore_current_blog();
5702
			}
5703
		} else {
5704
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5705
				flush();
5706
				$clients[0]->query();
5707
			}
5708
		}
5709
	}
5710
5711
	public static function staticize_subdomain( $url ) {
5712
5713
		// Extract hostname from URL
5714
		$host = parse_url( $url, PHP_URL_HOST );
5715
5716
		// Explode hostname on '.'
5717
		$exploded_host = explode( '.', $host );
5718
5719
		// Retrieve the name and TLD
5720
		if ( count( $exploded_host ) > 1 ) {
5721
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5722
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5723
			// Rebuild domain excluding subdomains
5724
			$domain = $name . '.' . $tld;
5725
		} else {
5726
			$domain = $host;
5727
		}
5728
		// Array of Automattic domains
5729
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5730
5731
		// Return $url if not an Automattic domain
5732
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5733
			return $url;
5734
		}
5735
5736
		if ( is_ssl() ) {
5737
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5738
		}
5739
5740
		srand( crc32( basename( $url ) ) );
5741
		$static_counter = rand( 0, 2 );
5742
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5743
5744
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5745
	}
5746
5747
/* JSON API Authorization */
5748
5749
	/**
5750
	 * Handles the login action for Authorizing the JSON API
5751
	 */
5752
	function login_form_json_api_authorization() {
5753
		$this->verify_json_api_authorization_request();
5754
5755
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5756
5757
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5758
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5759
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5760
	}
5761
5762
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5763
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5764
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5765
			return $url;
5766
		}
5767
5768
		$parsed_url = parse_url( $url );
5769
		$url = strtok( $url, '?' );
5770
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5771
		if ( ! empty( $parsed_url['query'] ) )
5772
			$url .= "&{$parsed_url['query']}";
5773
5774
		return $url;
5775
	}
5776
5777
	// Make sure the POSTed request is handled by the same action
5778
	function preserve_action_in_login_form_for_json_api_authorization() {
5779
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5780
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5781
	}
5782
5783
	// If someone logs in to approve API access, store the Access Code in usermeta
5784
	function store_json_api_authorization_token( $user_login, $user ) {
5785
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5786
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5787
		$token = wp_generate_password( 32, false );
5788
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5789
	}
5790
5791
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5792
	function allow_wpcom_public_api_domain( $domains ) {
5793
		$domains[] = 'public-api.wordpress.com';
5794
		return $domains;
5795
	}
5796
5797
	static function is_redirect_encoded( $redirect_url ) {
5798
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5799
	}
5800
5801
	// Add all wordpress.com environments to the safe redirect whitelist
5802
	function allow_wpcom_environments( $domains ) {
5803
		$domains[] = 'wordpress.com';
5804
		$domains[] = 'wpcalypso.wordpress.com';
5805
		$domains[] = 'horizon.wordpress.com';
5806
		$domains[] = 'calypso.localhost';
5807
		return $domains;
5808
	}
5809
5810
	// Add the Access Code details to the public-api.wordpress.com redirect
5811
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5812
		return add_query_arg(
5813
			urlencode_deep(
5814
				array(
5815
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5816
					'jetpack-user-id' => (int) $user->ID,
5817
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5818
				)
5819
			),
5820
			$redirect_to
5821
		);
5822
	}
5823
5824
5825
	/**
5826
	 * Verifies the request by checking the signature
5827
	 *
5828
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5829
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5830
	 *
5831
	 * @param null|array $environment
5832
	 */
5833
	function verify_json_api_authorization_request( $environment = null ) {
5834
		$environment = is_null( $environment )
5835
			? $_REQUEST
5836
			: $environment;
5837
5838
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5839
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5840
		if ( ! $token || empty( $token->secret ) ) {
5841
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5842
		}
5843
5844
		$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' );
5845
5846
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5847
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5848
			$this->tracking->record_user_event( 'error_double_encode' );
5849
5850
			$die_error = sprintf(
5851
				/* translators: %s is a URL */
5852
				__( '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' ),
5853
				'https://jetpack.com/support/double-encoding/'
5854
			);
5855
		}
5856
5857
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5858
5859
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5860
			$signature = $jetpack_signature->sign_request(
5861
				$environment['token'],
5862
				$environment['timestamp'],
5863
				$environment['nonce'],
5864
				'',
5865
				'GET',
5866
				$environment['jetpack_json_api_original_query'],
5867
				null,
5868
				true
5869
			);
5870
		} else {
5871
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5872
		}
5873
5874
		if ( ! $signature ) {
5875
			wp_die( $die_error );
5876
		} else if ( is_wp_error( $signature ) ) {
5877
			wp_die( $die_error );
5878
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5879
			if ( is_ssl() ) {
5880
				// 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
5881
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5882
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5883
					wp_die( $die_error );
5884
				}
5885
			} else {
5886
				wp_die( $die_error );
5887
			}
5888
		}
5889
5890
		$timestamp = (int) $environment['timestamp'];
5891
		$nonce     = stripslashes( (string) $environment['nonce'] );
5892
5893
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5894
			// De-nonce the nonce, at least for 5 minutes.
5895
			// 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)
5896
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5897
			if ( $old_nonce_time < time() - 300 ) {
5898
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5899
			}
5900
		}
5901
5902
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5903
		$data_filters = array(
5904
			'state'        => 'opaque',
5905
			'client_id'    => 'int',
5906
			'client_title' => 'string',
5907
			'client_image' => 'url',
5908
		);
5909
5910
		foreach ( $data_filters as $key => $sanitation ) {
5911
			if ( ! isset( $data->$key ) ) {
5912
				wp_die( $die_error );
5913
			}
5914
5915
			switch ( $sanitation ) {
5916
			case 'int' :
5917
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5918
				break;
5919
			case 'opaque' :
5920
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5921
				break;
5922
			case 'string' :
5923
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5924
				break;
5925
			case 'url' :
5926
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5927
				break;
5928
			}
5929
		}
5930
5931
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5932
			wp_die( $die_error );
5933
		}
5934
	}
5935
5936
	function login_message_json_api_authorization( $message ) {
5937
		return '<p class="message">' . sprintf(
5938
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5939
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5940
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5941
	}
5942
5943
	/**
5944
	 * Get $content_width, but with a <s>twist</s> filter.
5945
	 */
5946
	public static function get_content_width() {
5947
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5948
			? $GLOBALS['content_width']
5949
			: false;
5950
		/**
5951
		 * Filter the Content Width value.
5952
		 *
5953
		 * @since 2.2.3
5954
		 *
5955
		 * @param string $content_width Content Width value.
5956
		 */
5957
		return apply_filters( 'jetpack_content_width', $content_width );
5958
	}
5959
5960
	/**
5961
	 * Pings the WordPress.com Mirror Site for the specified options.
5962
	 *
5963
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5964
	 *
5965
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5966
	 */
5967
	public function get_cloud_site_options( $option_names ) {
5968
		$option_names = array_filter( (array) $option_names, 'is_string' );
5969
5970
		Jetpack::load_xml_rpc_client();
5971
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5972
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5973
		if ( $xml->isError() ) {
5974
			return array(
5975
				'error_code' => $xml->getErrorCode(),
5976
				'error_msg'  => $xml->getErrorMessage(),
5977
			);
5978
		}
5979
		$cloud_site_options = $xml->getResponse();
5980
5981
		return $cloud_site_options;
5982
	}
5983
5984
	/**
5985
	 * Checks if the site is currently in an identity crisis.
5986
	 *
5987
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5988
	 */
5989
	public static function check_identity_crisis() {
5990
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5991
			return false;
5992
		}
5993
5994
		return Jetpack_Options::get_option( 'sync_error_idc' );
5995
	}
5996
5997
	/**
5998
	 * Checks whether the home and siteurl specifically are whitelisted
5999
	 * Written so that we don't have re-check $key and $value params every time
6000
	 * we want to check if this site is whitelisted, for example in footer.php
6001
	 *
6002
	 * @since  3.8.0
6003
	 * @return bool True = already whitelisted False = not whitelisted
6004
	 */
6005
	public static function is_staging_site() {
6006
		$is_staging = false;
6007
6008
		$known_staging = array(
6009
			'urls' => array(
6010
				'#\.staging\.wpengine\.com$#i', // WP Engine
6011
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6012
				'#\.stage\.site$#i'             // DreamPress
6013
			),
6014
			'constants' => array(
6015
				'IS_WPE_SNAPSHOT',      // WP Engine
6016
				'KINSTA_DEV_ENV',       // Kinsta.com
6017
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6018
				'JETPACK_STAGING_MODE', // Generic
6019
			)
6020
		);
6021
		/**
6022
		 * Filters the flags of known staging sites.
6023
		 *
6024
		 * @since 3.9.0
6025
		 *
6026
		 * @param array $known_staging {
6027
		 *     An array of arrays that each are used to check if the current site is staging.
6028
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6029
		 *     @type array $constants PHP constants of known staging/developement environments.
6030
		 *  }
6031
		 */
6032
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6033
6034
		if ( isset( $known_staging['urls'] ) ) {
6035
			foreach ( $known_staging['urls'] as $url ){
6036
				if ( preg_match( $url, site_url() ) ) {
6037
					$is_staging = true;
6038
					break;
6039
				}
6040
			}
6041
		}
6042
6043
		if ( isset( $known_staging['constants'] ) ) {
6044
			foreach ( $known_staging['constants'] as $constant ) {
6045
				if ( defined( $constant ) && constant( $constant ) ) {
6046
					$is_staging = true;
6047
				}
6048
			}
6049
		}
6050
6051
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6052
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6053
			$is_staging = true;
6054
		}
6055
6056
		/**
6057
		 * Filters is_staging_site check.
6058
		 *
6059
		 * @since 3.9.0
6060
		 *
6061
		 * @param bool $is_staging If the current site is a staging site.
6062
		 */
6063
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6064
	}
6065
6066
	/**
6067
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6068
	 *
6069
	 * @since 4.4.0
6070
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6071
	 *
6072
	 * @return bool
6073
	 */
6074
	public static function validate_sync_error_idc_option() {
6075
		$is_valid = false;
6076
6077
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6078
		if ( false === $idc_allowed ) {
6079
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6080
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6081
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6082
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6083
				$transient_duration = HOUR_IN_SECONDS;
6084
			} else {
6085
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6086
				$idc_allowed = '1';
6087
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6088
			}
6089
6090
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6091
		}
6092
6093
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6094
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6095
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6096
			$local_options = self::get_sync_error_idc_option();
6097
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6098
				$is_valid = true;
6099
			}
6100
		}
6101
6102
		/**
6103
		 * Filters whether the sync_error_idc option is valid.
6104
		 *
6105
		 * @since 4.4.0
6106
		 *
6107
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6108
		 */
6109
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6110
6111
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6112
			// Since the option exists, and did not validate, delete it
6113
			Jetpack_Options::delete_option( 'sync_error_idc' );
6114
		}
6115
6116
		return $is_valid;
6117
	}
6118
6119
	/**
6120
	 * Normalizes a url by doing three things:
6121
	 *  - Strips protocol
6122
	 *  - Strips www
6123
	 *  - Adds a trailing slash
6124
	 *
6125
	 * @since 4.4.0
6126
	 * @param string $url
6127
	 * @return WP_Error|string
6128
	 */
6129
	public static function normalize_url_protocol_agnostic( $url ) {
6130
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6131
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6132
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6133
		}
6134
6135
		// Strip www and protocols
6136
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6137
		return $url;
6138
	}
6139
6140
	/**
6141
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6142
	 *
6143
	 * @since 4.4.0
6144
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6145
	 *
6146
	 * @param array $response
6147
	 * @return array Array of the local urls, wpcom urls, and error code
6148
	 */
6149
	public static function get_sync_error_idc_option( $response = array() ) {
6150
		// Since the local options will hit the database directly, store the values
6151
		// in a transient to allow for autoloading and caching on subsequent views.
6152
		$local_options = get_transient( 'jetpack_idc_local' );
6153
		if ( false === $local_options ) {
6154
			$local_options = array(
6155
				'home'    => Jetpack_Sync_Functions::home_url(),
6156
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6157
			);
6158
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6159
		}
6160
6161
		$options = array_merge( $local_options, $response );
6162
6163
		$returned_values = array();
6164
		foreach( $options as $key => $option ) {
6165
			if ( 'error_code' === $key ) {
6166
				$returned_values[ $key ] = $option;
6167
				continue;
6168
			}
6169
6170
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6171
				continue;
6172
			}
6173
6174
			$returned_values[ $key ] = $normalized_url;
6175
		}
6176
6177
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6178
6179
		return $returned_values;
6180
	}
6181
6182
	/**
6183
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6184
	 * If set to true, the site will be put into staging mode.
6185
	 *
6186
	 * @since 4.3.2
6187
	 * @return bool
6188
	 */
6189
	public static function sync_idc_optin() {
6190
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6191
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6192
		} else {
6193
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6194
		}
6195
6196
		/**
6197
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6198
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6199
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6200
		 *
6201
		 * @since 4.3.2
6202
		 *
6203
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6204
		 */
6205
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6206
	}
6207
6208
	/**
6209
	 * Maybe Use a .min.css stylesheet, maybe not.
6210
	 *
6211
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6212
	 */
6213
	public static function maybe_min_asset( $url, $path, $plugin ) {
6214
		// Short out on things trying to find actual paths.
6215
		if ( ! $path || empty( $plugin ) ) {
6216
			return $url;
6217
		}
6218
6219
		$path = ltrim( $path, '/' );
6220
6221
		// Strip out the abspath.
6222
		$base = dirname( plugin_basename( $plugin ) );
6223
6224
		// Short out on non-Jetpack assets.
6225
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6226
			return $url;
6227
		}
6228
6229
		// File name parsing.
6230
		$file              = "{$base}/{$path}";
6231
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6232
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6233
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6234
		$extension         = array_shift( $file_name_parts_r );
6235
6236
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6237
			// Already pointing at the minified version.
6238
			if ( 'min' === $file_name_parts_r[0] ) {
6239
				return $url;
6240
			}
6241
6242
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6243
			if ( file_exists( $min_full_path ) ) {
6244
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6245
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6246
				if ( 'css' === $extension ) {
6247
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6248
					self::$min_assets[ $key ] = $path;
6249
				}
6250
			}
6251
		}
6252
6253
		return $url;
6254
	}
6255
6256
	/**
6257
	 * If the asset is minified, let's flag .min as the suffix.
6258
	 *
6259
	 * Attached to `style_loader_src` filter.
6260
	 *
6261
	 * @param string $tag The tag that would link to the external asset.
6262
	 * @param string $handle The registered handle of the script in question.
6263
	 * @param string $href The url of the asset in question.
6264
	 */
6265
	public static function set_suffix_on_min( $src, $handle ) {
6266
		if ( false === strpos( $src, '.min.css' ) ) {
6267
			return $src;
6268
		}
6269
6270
		if ( ! empty( self::$min_assets ) ) {
6271
			foreach ( self::$min_assets as $file => $path ) {
6272
				if ( false !== strpos( $src, $file ) ) {
6273
					wp_style_add_data( $handle, 'suffix', '.min' );
6274
					return $src;
6275
				}
6276
			}
6277
		}
6278
6279
		return $src;
6280
	}
6281
6282
	/**
6283
	 * Maybe inlines a stylesheet.
6284
	 *
6285
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6286
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6287
	 *
6288
	 * Attached to `style_loader_tag` filter.
6289
	 *
6290
	 * @param string $tag The tag that would link to the external asset.
6291
	 * @param string $handle The registered handle of the script in question.
6292
	 *
6293
	 * @return string
6294
	 */
6295
	public static function maybe_inline_style( $tag, $handle ) {
6296
		global $wp_styles;
6297
		$item = $wp_styles->registered[ $handle ];
6298
6299
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6300
			return $tag;
6301
		}
6302
6303
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6304
			$href = $matches[1];
6305
			// Strip off query string
6306
			if ( $pos = strpos( $href, '?' ) ) {
6307
				$href = substr( $href, 0, $pos );
6308
			}
6309
			// Strip off fragment
6310
			if ( $pos = strpos( $href, '#' ) ) {
6311
				$href = substr( $href, 0, $pos );
6312
			}
6313
		} else {
6314
			return $tag;
6315
		}
6316
6317
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6318
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6319
			return $tag;
6320
		}
6321
6322
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6323
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6324
			// And this isn't the pass that actually deals with the RTL version...
6325
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6326
				// Short out, as the RTL version will deal with it in a moment.
6327
				return $tag;
6328
			}
6329
		}
6330
6331
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6332
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6333
		if ( $css ) {
6334
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6335
			if ( empty( $item->extra['after'] ) ) {
6336
				wp_add_inline_style( $handle, $css );
6337
			} else {
6338
				array_unshift( $item->extra['after'], $css );
6339
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6340
			}
6341
		}
6342
6343
		return $tag;
6344
	}
6345
6346
	/**
6347
	 * Loads a view file from the views
6348
	 *
6349
	 * Data passed in with the $data parameter will be available in the
6350
	 * template file as $data['value']
6351
	 *
6352
	 * @param string $template - Template file to load
6353
	 * @param array $data - Any data to pass along to the template
6354
	 * @return boolean - If template file was found
6355
	 **/
6356
	public function load_view( $template, $data = array() ) {
6357
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6358
6359
		if( file_exists( $views_dir . $template ) ) {
6360
			require_once( $views_dir . $template );
6361
			return true;
6362
		}
6363
6364
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6365
		return false;
6366
	}
6367
6368
	/**
6369
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6370
	 */
6371
	public function deprecated_hooks() {
6372
		global $wp_filter;
6373
6374
		/*
6375
		 * Format:
6376
		 * deprecated_filter_name => replacement_name
6377
		 *
6378
		 * If there is no replacement, use null for replacement_name
6379
		 */
6380
		$deprecated_list = array(
6381
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6382
			'wpl_sharing_2014_1'                                     => null,
6383
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6384
			'jetpack_identity_crisis_options_to_check'               => null,
6385
			'update_option_jetpack_single_user_site'                 => null,
6386
			'audio_player_default_colors'                            => null,
6387
			'add_option_jetpack_featured_images_enabled'             => null,
6388
			'add_option_jetpack_update_details'                      => null,
6389
			'add_option_jetpack_updates'                             => null,
6390
			'add_option_jetpack_network_name'                        => null,
6391
			'add_option_jetpack_network_allow_new_registrations'     => null,
6392
			'add_option_jetpack_network_add_new_users'               => null,
6393
			'add_option_jetpack_network_site_upload_space'           => null,
6394
			'add_option_jetpack_network_upload_file_types'           => null,
6395
			'add_option_jetpack_network_enable_administration_menus' => null,
6396
			'add_option_jetpack_is_multi_site'                       => null,
6397
			'add_option_jetpack_is_main_network'                     => null,
6398
			'add_option_jetpack_main_network_site'                   => null,
6399
			'jetpack_sync_all_registered_options'                    => null,
6400
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6401
			'jetpack_is_post_mailable'                               => null,
6402
			'jetpack_seo_site_host'                                  => null,
6403
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6404
			'jetpack_holiday_snow_option_name'                       => null,
6405
			'jetpack_holiday_chance_of_snow'                         => null,
6406
			'jetpack_holiday_snow_js_url'                            => null,
6407
			'jetpack_is_holiday_snow_season'                         => null,
6408
			'jetpack_holiday_snow_option_updated'                    => null,
6409
			'jetpack_holiday_snowing'                                => null,
6410
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6411
			'jetpack_cache_plans'                                    => null,
6412
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6413
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6414
			'jetpack_enable_site_verification'                       => null,
6415
			'can_display_jetpack_manage_notice'                      => null,
6416
			// Removed in Jetpack 7.3.0
6417
			'atd_load_scripts'                                       => null,
6418
			'atd_http_post_timeout'                                  => null,
6419
			'atd_http_post_error'                                    => null,
6420
			'atd_service_domain'                                     => null,
6421
		);
6422
6423
		// This is a silly loop depth. Better way?
6424
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6425
			if ( has_action( $hook ) ) {
6426
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6427
					foreach( $values AS $hooked ) {
6428
						if ( is_callable( $hooked['function'] ) ) {
6429
							$function_name = 'an anonymous function';
6430
						} else {
6431
							$function_name = $hooked['function'];
6432
						}
6433
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6434
					}
6435
				}
6436
			}
6437
		}
6438
	}
6439
6440
	/**
6441
	 * Converts any url in a stylesheet, to the correct absolute url.
6442
	 *
6443
	 * Considerations:
6444
	 *  - Normal, relative URLs     `feh.png`
6445
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6446
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6447
	 *  - Absolute URLs             `http://domain.com/feh.png`
6448
	 *  - Domain root relative URLs `/feh.png`
6449
	 *
6450
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6451
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6452
	 *
6453
	 * @return mixed|string
6454
	 */
6455
	public static function absolutize_css_urls( $css, $css_file_url ) {
6456
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6457
		$css_dir = dirname( $css_file_url );
6458
		$p       = parse_url( $css_dir );
6459
		$domain  = sprintf(
6460
					'%1$s//%2$s%3$s%4$s',
6461
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6462
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6463
					$p['host'],
6464
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6465
				);
6466
6467
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6468
			$find = $replace = array();
6469
			foreach ( $matches as $match ) {
6470
				$url = trim( $match['path'], "'\" \t" );
6471
6472
				// If this is a data url, we don't want to mess with it.
6473
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6474
					continue;
6475
				}
6476
6477
				// If this is an absolute or protocol-agnostic url,
6478
				// we don't want to mess with it.
6479
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6480
					continue;
6481
				}
6482
6483
				switch ( substr( $url, 0, 1 ) ) {
6484
					case '/':
6485
						$absolute = $domain . $url;
6486
						break;
6487
					default:
6488
						$absolute = $css_dir . '/' . $url;
6489
				}
6490
6491
				$find[]    = $match[0];
6492
				$replace[] = sprintf( 'url("%s")', $absolute );
6493
			}
6494
			$css = str_replace( $find, $replace, $css );
6495
		}
6496
6497
		return $css;
6498
	}
6499
6500
	/**
6501
	 * This methods removes all of the registered css files on the front end
6502
	 * from Jetpack in favor of using a single file. In effect "imploding"
6503
	 * all the files into one file.
6504
	 *
6505
	 * Pros:
6506
	 * - Uses only ONE css asset connection instead of 15
6507
	 * - Saves a minimum of 56k
6508
	 * - Reduces server load
6509
	 * - Reduces time to first painted byte
6510
	 *
6511
	 * Cons:
6512
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6513
	 *		should not cause any issues with themes.
6514
	 * - Plugins/themes dequeuing styles no longer do anything. See
6515
	 *		jetpack_implode_frontend_css filter for a workaround
6516
	 *
6517
	 * For some situations developers may wish to disable css imploding and
6518
	 * instead operate in legacy mode where each file loads seperately and
6519
	 * can be edited individually or dequeued. This can be accomplished with
6520
	 * the following line:
6521
	 *
6522
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6523
	 *
6524
	 * @since 3.2
6525
	 **/
6526
	public function implode_frontend_css( $travis_test = false ) {
6527
		$do_implode = true;
6528
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6529
			$do_implode = false;
6530
		}
6531
6532
		// Do not implode CSS when the page loads via the AMP plugin.
6533
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6534
			$do_implode = false;
6535
		}
6536
6537
		/**
6538
		 * Allow CSS to be concatenated into a single jetpack.css file.
6539
		 *
6540
		 * @since 3.2.0
6541
		 *
6542
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6543
		 */
6544
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6545
6546
		// Do not use the imploded file when default behavior was altered through the filter
6547
		if ( ! $do_implode ) {
6548
			return;
6549
		}
6550
6551
		// We do not want to use the imploded file in dev mode, or if not connected
6552
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6553
			if ( ! $travis_test ) {
6554
				return;
6555
			}
6556
		}
6557
6558
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6559
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6560
			return;
6561
		}
6562
6563
		/*
6564
		 * Now we assume Jetpack is connected and able to serve the single
6565
		 * file.
6566
		 *
6567
		 * In the future there will be a check here to serve the file locally
6568
		 * or potentially from the Jetpack CDN
6569
		 *
6570
		 * For now:
6571
		 * - Enqueue a single imploded css file
6572
		 * - Zero out the style_loader_tag for the bundled ones
6573
		 * - Be happy, drink scotch
6574
		 */
6575
6576
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6577
6578
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6579
6580
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6581
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6582
	}
6583
6584
	function concat_remove_style_loader_tag( $tag, $handle ) {
6585
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6586
			$tag = '';
6587
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6588
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6589
			}
6590
		}
6591
6592
		return $tag;
6593
	}
6594
6595
	/*
6596
	 * Check the heartbeat data
6597
	 *
6598
	 * Organizes the heartbeat data by severity.  For example, if the site
6599
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6600
	 *
6601
	 * Data will be added to "caution" array, if it either:
6602
	 *  - Out of date Jetpack version
6603
	 *  - Out of date WP version
6604
	 *  - Out of date PHP version
6605
	 *
6606
	 * $return array $filtered_data
6607
	 */
6608
	public static function jetpack_check_heartbeat_data() {
6609
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6610
6611
		$good    = array();
6612
		$caution = array();
6613
		$bad     = array();
6614
6615
		foreach ( $raw_data as $stat => $value ) {
6616
6617
			// Check jetpack version
6618
			if ( 'version' == $stat ) {
6619
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6620
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6621
					continue;
6622
				}
6623
			}
6624
6625
			// Check WP version
6626
			if ( 'wp-version' == $stat ) {
6627
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6628
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6629
					continue;
6630
				}
6631
			}
6632
6633
			// Check PHP version
6634
			if ( 'php-version' == $stat ) {
6635
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6636
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6637
					continue;
6638
				}
6639
			}
6640
6641
			// Check ID crisis
6642
			if ( 'identitycrisis' == $stat ) {
6643
				if ( 'yes' == $value ) {
6644
					$bad[ $stat ] = $value;
6645
					continue;
6646
				}
6647
			}
6648
6649
			// The rest are good :)
6650
			$good[ $stat ] = $value;
6651
		}
6652
6653
		$filtered_data = array(
6654
			'good'    => $good,
6655
			'caution' => $caution,
6656
			'bad'     => $bad
6657
		);
6658
6659
		return $filtered_data;
6660
	}
6661
6662
6663
	/*
6664
	 * This method is used to organize all options that can be reset
6665
	 * without disconnecting Jetpack.
6666
	 *
6667
	 * It is used in class.jetpack-cli.php to reset options
6668
	 *
6669
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6670
	 *
6671
	 * @return array of options to delete.
6672
	 */
6673
	public static function get_jetpack_options_for_reset() {
6674
		return Jetpack_Options::get_options_for_reset();
6675
	}
6676
6677
	/*
6678
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6679
	 * so we can bring them directly to their site in calypso.
6680
	 *
6681
	 * @param string | url
6682
	 * @return string | url without the guff
6683
	 */
6684
	public static function build_raw_urls( $url ) {
6685
		$strip_http = '/.*?:\/\//i';
6686
		$url = preg_replace( $strip_http, '', $url  );
6687
		$url = str_replace( '/', '::', $url );
6688
		return $url;
6689
	}
6690
6691
	/**
6692
	 * Stores and prints out domains to prefetch for page speed optimization.
6693
	 *
6694
	 * @param mixed $new_urls
6695
	 */
6696
	public static function dns_prefetch( $new_urls = null ) {
6697
		static $prefetch_urls = array();
6698
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6699
			echo "\r\n";
6700
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6701
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6702
			}
6703
		} elseif ( ! empty( $new_urls ) ) {
6704
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6705
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6706
			}
6707
			foreach ( (array) $new_urls as $this_new_url ) {
6708
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6709
			}
6710
			$prefetch_urls = array_unique( $prefetch_urls );
6711
		}
6712
	}
6713
6714
	public function wp_dashboard_setup() {
6715
		if ( self::is_active() ) {
6716
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6717
		}
6718
6719
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6720
			$jetpack_logo = new Jetpack_Logo();
6721
			$widget_title = sprintf(
6722
				wp_kses(
6723
					/* translators: Placeholder is a Jetpack logo. */
6724
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6725
					array( 'span' => array() )
6726
				),
6727
				$jetpack_logo->get_jp_emblem( true )
6728
			);
6729
6730
			wp_add_dashboard_widget(
6731
				'jetpack_summary_widget',
6732
				$widget_title,
6733
				array( __CLASS__, 'dashboard_widget' )
6734
			);
6735
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6736
6737
			// If we're inactive and not in development mode, sort our box to the top.
6738
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6739
				global $wp_meta_boxes;
6740
6741
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6742
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6743
6744
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6745
			}
6746
		}
6747
	}
6748
6749
	/**
6750
	 * @param mixed $result Value for the user's option
6751
	 * @return mixed
6752
	 */
6753
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6754
		if ( ! is_array( $sorted ) ) {
6755
			return $sorted;
6756
		}
6757
6758
		foreach ( $sorted as $box_context => $ids ) {
6759
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6760
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6761
				continue;
6762
			}
6763
6764
			$ids_array = explode( ',', $ids );
6765
			$key = array_search( 'dashboard_stats', $ids_array );
6766
6767
			if ( false !== $key ) {
6768
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6769
				$ids_array[ $key ] = 'jetpack_summary_widget';
6770
				$sorted[ $box_context ] = implode( ',', $ids_array );
6771
				// We've found it, stop searching, and just return.
6772
				break;
6773
			}
6774
		}
6775
6776
		return $sorted;
6777
	}
6778
6779
	public static function dashboard_widget() {
6780
		/**
6781
		 * Fires when the dashboard is loaded.
6782
		 *
6783
		 * @since 3.4.0
6784
		 */
6785
		do_action( 'jetpack_dashboard_widget' );
6786
	}
6787
6788
	public static function dashboard_widget_footer() {
6789
		?>
6790
		<footer>
6791
6792
		<div class="protect">
6793
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6794
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6795
				<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>
6796
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6797
				<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' ); ?>">
6798
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6799
				</a>
6800
			<?php else : ?>
6801
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6802
			<?php endif; ?>
6803
		</div>
6804
6805
		<div class="akismet">
6806
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6807
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6808
				<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>
6809
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6810
				<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">
6811
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6812
				</a>
6813
			<?php else : ?>
6814
				<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>
6815
			<?php endif; ?>
6816
		</div>
6817
6818
		</footer>
6819
		<?php
6820
	}
6821
6822
	/*
6823
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6824
	 */
6825
	function jetpack_icon_user_connected( $columns ) {
6826
		$columns['user_jetpack'] = '';
6827
		return $columns;
6828
	}
6829
6830
	/*
6831
	 * Show Jetpack icon if the user is linked.
6832
	 */
6833
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6834
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6835
			$jetpack_logo = new Jetpack_Logo();
6836
			$emblem_html = sprintf(
6837
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6838
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6839
				$jetpack_logo->get_jp_emblem()
6840
			);
6841
			return $emblem_html;
6842
		}
6843
6844
		return $val;
6845
	}
6846
6847
	/*
6848
	 * Style the Jetpack user column
6849
	 */
6850
	function jetpack_user_col_style() {
6851
		global $current_screen;
6852
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6853
			<style>
6854
				.fixed .column-user_jetpack {
6855
					width: 21px;
6856
				}
6857
				.jp-emblem-user-admin svg {
6858
					width: 20px;
6859
					height: 20px;
6860
				}
6861
				.jp-emblem-user-admin path {
6862
					fill: #00BE28;
6863
				}
6864
			</style>
6865
		<?php }
6866
	}
6867
6868
	/**
6869
	 * Checks if Akismet is active and working.
6870
	 *
6871
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6872
	 * that implied usage of methods present since more recent version.
6873
	 * See https://github.com/Automattic/jetpack/pull/9585
6874
	 *
6875
	 * @since  5.1.0
6876
	 *
6877
	 * @return bool True = Akismet available. False = Aksimet not available.
6878
	 */
6879
	public static function is_akismet_active() {
6880
		static $status = null;
6881
6882
		if ( ! is_null( $status ) ) {
6883
			return $status;
6884
		}
6885
6886
		// Check if a modern version of Akismet is active.
6887
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6888
			$status = false;
6889
			return $status;
6890
		}
6891
6892
		// Make sure there is a key known to Akismet at all before verifying key.
6893
		$akismet_key = Akismet::get_api_key();
6894
		if ( ! $akismet_key ) {
6895
			$status = false;
6896
			return $status;
6897
		}
6898
6899
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6900
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6901
6902
		// 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.
6903
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6904
		// We cache the result of the Akismet key verification for ten minutes.
6905
		if ( ! $akismet_key_state || $recheck ) {
6906
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6907
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6908
		}
6909
6910
		$status = 'valid' === $akismet_key_state;
6911
6912
		return $status;
6913
	}
6914
6915
	/**
6916
	 * Checks if one or more function names is in debug_backtrace
6917
	 *
6918
	 * @param $names Mixed string name of function or array of string names of functions
6919
	 *
6920
	 * @return bool
6921
	 */
6922
	public static function is_function_in_backtrace( $names ) {
6923
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6924
		if ( ! is_array( $names ) ) {
6925
			$names = array( $names );
6926
		}
6927
		$names_as_keys = array_flip( $names );
6928
6929
		//Do check in constant O(1) time for PHP5.5+
6930
		if ( function_exists( 'array_column' ) ) {
6931
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6932
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6933
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6934
			return ! empty ( $intersection );
6935
		}
6936
6937
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6938
		foreach ( $backtrace as $call ) {
6939
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6940
				return true;
6941
			}
6942
		}
6943
		return false;
6944
	}
6945
6946
	/**
6947
	 * Given a minified path, and a non-minified path, will return
6948
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6949
	 *
6950
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6951
	 * root Jetpack directory.
6952
	 *
6953
	 * @since 5.6.0
6954
	 *
6955
	 * @param string $min_path
6956
	 * @param string $non_min_path
6957
	 * @return string The URL to the file
6958
	 */
6959
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6960
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6961
			? $non_min_path
6962
			: $min_path;
6963
6964
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6965
	}
6966
6967
	/**
6968
	 * Checks for whether Jetpack Backup & Scan is enabled.
6969
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6970
	 * @return bool|int|mixed
6971
	 */
6972
	public static function is_rewind_enabled() {
6973
		if ( ! Jetpack::is_active() ) {
6974
			return false;
6975
		}
6976
6977
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6978
		if ( false === $rewind_enabled ) {
6979
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6980
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6981
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6982
				&& ! empty( $rewind_data['state'] )
6983
				&& 'active' === $rewind_data['state'] )
6984
				? 1
6985
				: 0;
6986
6987
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6988
		}
6989
		return $rewind_enabled;
6990
	}
6991
6992
	/**
6993
	 * Return Calypso environment value; used for developing Jetpack and pairing
6994
	 * it with different Calypso enrionments, such as localhost.
6995
	 *
6996
	 * @since 7.4.0
6997
	 *
6998
	 * @return string Calypso environment
6999
	 */
7000
	public static function get_calypso_env() {
7001
		if ( isset( $_GET['calypso_env'] ) ) {
7002
			return sanitize_key( $_GET['calypso_env'] );
7003
		}
7004
7005
		if ( getenv( 'CALYPSO_ENV' ) ) {
7006
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7007
		}
7008
7009
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7010
			return sanitize_key( CALYPSO_ENV );
7011
		}
7012
7013
		return '';
7014
	}
7015
7016
	/**
7017
	 * Checks whether or not TOS has been agreed upon.
7018
	 * Will return true if a user has clicked to register, or is already connected.
7019
	 */
7020
	public static function jetpack_tos_agreed() {
7021
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7022
	}
7023
7024
	/**
7025
	 * Handles activating default modules as well general cleanup for the new connection.
7026
	 *
7027
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7028
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7029
	 * @param boolean $send_state_messages          Whether to send state messages.
7030
	 * @return void
7031
	 */
7032
	public static function handle_post_authorization_actions(
7033
		$activate_sso = false,
7034
		$redirect_on_activation_error = false,
7035
		$send_state_messages = true
7036
	) {
7037
		$other_modules = $activate_sso
7038
			? array( 'sso' )
7039
			: array();
7040
7041
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7042
			Jetpack::delete_active_modules();
7043
7044
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7045
		} else {
7046
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7047
		}
7048
7049
		// Since this is a fresh connection, be sure to clear out IDC options
7050
		Jetpack_IDC::clear_all_idc_options();
7051
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7052
7053
		// Start nonce cleaner
7054
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7055
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7056
7057
		if ( $send_state_messages ) {
7058
			Jetpack::state( 'message', 'authorized' );
7059
		}
7060
	}
7061
7062
	/**
7063
	 * Returns a boolean for whether backups UI should be displayed or not.
7064
	 *
7065
	 * @return bool Should backups UI be displayed?
7066
	 */
7067
	public static function show_backups_ui() {
7068
		/**
7069
		 * Whether UI for backups should be displayed.
7070
		 *
7071
		 * @since 6.5.0
7072
		 *
7073
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7074
		 */
7075
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7076
	}
7077
7078
	/*
7079
	 * Deprecated manage functions
7080
	 */
7081
	function prepare_manage_jetpack_notice() {
7082
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7083
	}
7084
	function manage_activate_screen() {
7085
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7086
	}
7087
	function admin_jetpack_manage_notice() {
7088
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7089
	}
7090
	function opt_out_jetpack_manage_url() {
7091
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7092
	}
7093
	function opt_in_jetpack_manage_url() {
7094
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7095
	}
7096
	function opt_in_jetpack_manage_notice() {
7097
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7098
	}
7099
	function can_display_jetpack_manage_notice() {
7100
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7101
	}
7102
7103
	/**
7104
	 * Clean leftoveruser meta.
7105
	 *
7106
	 * Delete Jetpack-related user meta when it is no longer needed.
7107
	 *
7108
	 * @since 7.3.0
7109
	 *
7110
	 * @param int $user_id User ID being updated.
7111
	 */
7112
	public static function user_meta_cleanup( $user_id ) {
7113
		$meta_keys = array(
7114
			// AtD removed from Jetpack 7.3
7115
			'AtD_options',
7116
			'AtD_check_when',
7117
			'AtD_guess_lang',
7118
			'AtD_ignored_phrases',
7119
		);
7120
7121
		foreach ( $meta_keys as $meta_key ) {
7122
			if ( get_user_meta( $user_id, $meta_key ) ) {
7123
				delete_user_meta( $user_id, $meta_key );
7124
			}
7125
		}
7126
	}
7127
7128
	function is_active_and_not_development_mode( $maybe ) {
7129
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7130
			return false;
7131
		}
7132
		return true;
7133
	}
7134
7135
	/* Activated module */
7136
	function track_activate_module( $module ) {
7137
		$this->tracking->record_user_event( 'module_activated', array( 'module' => $module ) );
7138
	}
7139
7140
	/* Deactivated module */
7141
	function track_deactivate_module( $module ) {
7142
		$this->tracking->record_user_event( 'module_deactivated', array( 'module' => $module ) );
7143
	}
7144
7145
	/* User has linked their account */
7146
	function track_user_linked() {
7147
		$user_id = get_current_user_id();
7148
		$anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
7149
7150
		if ( $anon_id ) {
7151
			self::record_user_event( '_aliasUser', array( 'anonId' => $anon_id ) );
7152
			delete_user_meta( $user_id, 'jetpack_tracks_anon_id' );
7153
			if ( ! headers_sent() ) {
7154
				setcookie( 'tk_ai', 'expired', time() - 1000 );
7155
			}
7156
		}
7157
7158
		$wpcom_user_data = Jetpack::get_connected_user_data( $user_id );
7159
		update_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_user_data['ID'] );
7160
7161
		self::record_user_event( 'wpa_user_linked', array() );
7162
	}
7163
7164
	/* Failed login attempts */
7165
	function track_failed_login_attempts( $login ) {
7166
		require_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
7167
		self::record_user_event(
7168
			'failed_login',
7169
			array(
7170
				'origin_ip' => jetpack_protect_get_ip(),
7171
				'login'     => $login,
7172
			)
7173
		);
7174
	}
7175
7176
	function track_jetpack_usage() {
7177
		if ( ! self::jetpack_tos_agreed() ) {
7178
			return;
7179
		}
7180
7181
		// For tracking stuff via js/ajax
7182
		add_action( 'admin_enqueue_scripts', array( $this->tracking, 'enqueue_tracks_scripts' ) );
7183
7184
		add_action( 'jetpack_activate_module', array( $this, 'track_activate_module' ), 1, 1 );
7185
		add_action( 'jetpack_deactivate_module', array( $this, 'track_deactivate_module' ), 1, 1 );
7186
		add_action( 'jetpack_user_authorized', array( $this, 'track_user_linked' ) );
7187
		add_action( 'wp_login_failed', array( $this, 'track_failed_login_attempts' ) );
7188
	}
7189
7190
7191
}
7192