Completed
Push — update/akismet-dashitem ( 001fc7...3a6c16 )
by
unknown
08:51 queued 01:45
created

class.jetpack.php (22 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $xmlrpc_verification = null;
44
	private $rest_authentication_status = null;
45
46
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
47
48
	private $tracking;
49
50
	/**
51
	 * @var array The handles of styles that are concatenated into jetpack.css.
52
	 *
53
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
54
	 */
55
	public $concatenated_style_handles = array(
56
		'jetpack-carousel',
57
		'grunion.css',
58
		'the-neverending-homepage',
59
		'jetpack_likes',
60
		'jetpack_related-posts',
61
		'sharedaddy',
62
		'jetpack-slideshow',
63
		'presentations',
64
		'quiz',
65
		'jetpack-subscriptions',
66
		'jetpack-responsive-videos-style',
67
		'jetpack-social-menu',
68
		'tiled-gallery',
69
		'jetpack_display_posts_widget',
70
		'gravatar-profile-widget',
71
		'goodreads-widget',
72
		'jetpack_social_media_icons_widget',
73
		'jetpack-top-posts-widget',
74
		'jetpack_image_widget',
75
		'jetpack-my-community-widget',
76
		'jetpack-authors-widget',
77
		'wordads',
78
		'eu-cookie-law-style',
79
		'flickr-widget-style',
80
		'jetpack-search-widget',
81
		'jetpack-simple-payments-widget-style',
82
		'jetpack-widget-social-icons-styles',
83
	);
84
85
	/**
86
	 * Contains all assets that have had their URL rewritten to minified versions.
87
	 *
88
	 * @var array
89
	 */
90
	static $min_assets = array();
91
92
	public $plugins_to_deactivate = array(
93
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
94
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
95
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
96
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
97
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
98
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
99
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
100
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
101
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
102
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
103
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
104
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
105
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
106
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
107
	);
108
109
	/**
110
	 * Map of roles we care about, and their corresponding minimum capabilities.
111
	 *
112
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
113
	 *
114
	 * @access public
115
	 * @static
116
	 *
117
	 * @var array
118
	 */
119
	public static $capability_translations = array(
120
		'administrator' => 'manage_options',
121
		'editor'        => 'edit_others_posts',
122
		'author'        => 'publish_posts',
123
		'contributor'   => 'edit_posts',
124
		'subscriber'    => 'read',
125
	);
126
127
	/**
128
	 * Map of modules that have conflicts with plugins and should not be auto-activated
129
	 * if the plugins are active.  Used by filter_default_modules
130
	 *
131
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
132
	 * change `module-slug` and add this to your plugin:
133
	 *
134
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
135
	 * function my_jetpack_get_default_modules( $modules ) {
136
	 *     return array_diff( $modules, array( 'module-slug' ) );
137
	 * }
138
	 *
139
	 * @var array
140
	 */
141
	private $conflicting_plugins = array(
142
		'comments'          => array(
143
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
144
			'Disqus'                               => 'disqus-comment-system/disqus.php',
145
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
146
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
147
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
148
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
149
		),
150
		'comment-likes' => array(
151
			'Epoch'                                => 'epoch/plugincore.php',
152
		),
153
		'contact-form'      => array(
154
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
155
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
156
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
157
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
158
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
159
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
160
		),
161
		'minileven'         => array(
162
			'WPtouch'                              => 'wptouch/wptouch.php',
163
		),
164
		'latex'             => array(
165
			'LaTeX for WordPress'                  => 'latex/latex.php',
166
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'           => array(
173
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                              => 'captcha/captcha.php',
175
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
180
			'Security-protection'                  => 'security-protection/security-protection.php',
181
			'Login Security'                       => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                   => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'   => array(
188
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'     => array(
191
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                             => 'outbrain/outbrain.php',
197
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'        => array(
201
			'AddThis'                              => 'addthis/addthis_social_widget.php',
202
			'Add To Any'                           => 'add-to-any/add-to-any.php',
203
			'ShareThis'                            => 'share-this/sharethis.php',
204
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools' => array(
207
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'                    => 'autodescription/autodescription.php',
212
		),
213
		'verification-tools' => array(
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
		),
220
		'widget-visibility' => array(
221
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
222
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
223
		),
224
		'sitemaps' => array(
225
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
226
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
227
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
228
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
229
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
230
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
231
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
232
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
233
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
234
			'The SEO Framework'                    => 'autodescription/autodescription.php',
235
			'Sitemap'                              => 'sitemap/sitemap.php',
236
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
237
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
238
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
239
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
240
		),
241
		'lazy-images' => array(
242
			'Lazy Load'              => 'lazy-load/lazy-load.php',
243
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
244
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
245
		),
246
	);
247
248
	/**
249
	 * Plugins for which we turn off our Facebook OG Tags implementation.
250
	 *
251
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
252
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
253
	 *
254
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
255
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
256
	 */
257
	private $open_graph_conflicting_plugins = array(
258
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
259
		                                                         // 2 Click Social Media Buttons
260
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
261
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
262
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
263
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
264
		                                                         // Open Graph Meta Tags by Heateor
265
		'facebook/facebook.php',                                 // Facebook (official plugin)
266
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
267
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
268
		                                                         // Facebook Featured Image & OG Meta Tags
269
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
270
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
271
		                                                         // Facebook Open Graph Meta Tags for WordPress
272
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
273
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
274
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
275
		                                                         // Fedmich's Facebook Open Graph Meta
276
		'network-publisher/networkpub.php',                      // Network Publisher
277
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
278
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
279
		                                                         // NextScripts SNAP
280
		'og-tags/og-tags.php',                                   // OG Tags
281
		'opengraph/opengraph.php',                               // Open Graph
282
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
283
		                                                         // Open Graph Protocol Framework
284
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
285
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
286
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
287
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
288
		'sharepress/sharepress.php',                             // SharePress
289
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
290
		'social-discussions/social-discussions.php',             // Social Discussions
291
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
292
		'socialize/socialize.php',                               // Socialize
293
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
294
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
295
		                                                         // Tweet, Like, Google +1 and Share
296
		'wordbooker/wordbooker.php',                             // Wordbooker
297
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
298
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
299
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
300
		                                                         // WP Facebook Like Send & Open Graph Meta
301
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
302
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
303
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
304
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
305
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
306
	);
307
308
	/**
309
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
310
	 */
311
	private $twitter_cards_conflicting_plugins = array(
312
	//	'twitter/twitter.php',                       // The official one handles this on its own.
313
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
314
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
315
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
316
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
317
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
318
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
319
		'twitter-cards/twitter-cards.php',           // Twitter Cards
320
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
321
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
322
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
323
	);
324
325
	/**
326
	 * Message to display in admin_notice
327
	 * @var string
328
	 */
329
	public $message = '';
330
331
	/**
332
	 * Error to display in admin_notice
333
	 * @var string
334
	 */
335
	public $error = '';
336
337
	/**
338
	 * Modules that need more privacy description.
339
	 * @var string
340
	 */
341
	public $privacy_checks = '';
342
343
	/**
344
	 * Stats to record once the page loads
345
	 *
346
	 * @var array
347
	 */
348
	public $stats = array();
349
350
	/**
351
	 * Jetpack_Sync object
352
	 */
353
	public $sync;
354
355
	/**
356
	 * Verified data for JSON authorization request
357
	 */
358
	public $json_api_authorization_request = array();
359
360
	/**
361
	 * @var \Automattic\Jetpack\Connection\Manager
362
	 */
363
	protected $connection_manager;
364
365
	/**
366
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
367
	 */
368
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
369
370
	/**
371
	 * Holds the singleton instance of this class
372
	 * @since 2.3.3
373
	 * @var Jetpack
374
	 */
375
	static $instance = false;
376
377
	/**
378
	 * Singleton
379
	 * @static
380
	 */
381
	public static function init() {
382
		if ( ! self::$instance ) {
383
			self::$instance = new Jetpack;
384
385
			self::$instance->plugin_upgrade();
386
		}
387
388
		return self::$instance;
389
	}
390
391
	/**
392
	 * Must never be called statically
393
	 */
394
	function plugin_upgrade() {
395
		if ( Jetpack::is_active() ) {
396
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
397
			if ( JETPACK__VERSION != $version ) {
398
				// Prevent multiple upgrades at once - only a single process should trigger
399
				// an upgrade to avoid stampedes
400
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
401
					return;
402
				}
403
404
				// Set a short lock to prevent multiple instances of the upgrade
405
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
406
407
				// check which active modules actually exist and remove others from active_modules list
408
				$unfiltered_modules = Jetpack::get_active_modules();
409
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
410
				if ( array_diff( $unfiltered_modules, $modules ) ) {
411
					Jetpack::update_active_modules( $modules );
412
				}
413
414
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
415
416
				// Upgrade to 4.3.0
417
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
418
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
419
				}
420
421
				// Make sure Markdown for posts gets turned back on
422
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
423
					update_option( 'wpcom_publish_posts_with_markdown', true );
424
				}
425
426
				if ( did_action( 'wp_loaded' ) ) {
427
					self::upgrade_on_load();
428
				} else {
429
					add_action(
430
						'wp_loaded',
431
						array( __CLASS__, 'upgrade_on_load' )
432
					);
433
				}
434
			}
435
		}
436
	}
437
438
	/**
439
	 * Runs upgrade routines that need to have modules loaded.
440
	 */
441
	static function upgrade_on_load() {
442
443
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
444
		// This can happen in case Jetpack has been just upgraded and is
445
		// being initialized late during the page load. In this case we wait
446
		// until the next proper admin page load with Jetpack active.
447
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
448
			delete_transient( self::$plugin_upgrade_lock_key );
449
450
			return;
451
		}
452
453
		Jetpack::maybe_set_version_option();
454
455
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
456
			Jetpack_Widget_Conditions::migrate_post_type_rules();
457
		}
458
459
		if (
460
			class_exists( 'Jetpack_Sitemap_Manager' )
461
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
462
		) {
463
			do_action( 'jetpack_sitemaps_purge_data' );
464
		}
465
466
		delete_transient( self::$plugin_upgrade_lock_key );
467
	}
468
469
	/**
470
	 * Saves all the currently active modules to options.
471
	 * Also fires Action hooks for each newly activated and deactivated module.
472
	 *
473
	 * @param $modules Array Array of active modules to be saved in options.
474
	 *
475
	 * @return $success bool true for success, false for failure.
476
	 */
477
	static function update_active_modules( $modules ) {
478
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
479
		$active_modules       = Jetpack::get_active_modules();
480
		$new_active_modules   = array_diff( $modules, $current_modules );
481
		$new_inactive_modules = array_diff( $active_modules, $modules );
482
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
483
		$reindexed_modules    = array_values( $new_current_modules );
484
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
485
486
		foreach ( $new_active_modules as $module ) {
487
			/**
488
			 * Fires when a specific module is activated.
489
			 *
490
			 * @since 1.9.0
491
			 *
492
			 * @param string $module Module slug.
493
			 * @param boolean $success whether the module was activated. @since 4.2
494
			 */
495
			do_action( 'jetpack_activate_module', $module, $success );
496
			/**
497
			 * Fires when a module is activated.
498
			 * The dynamic part of the filter, $module, is the module slug.
499
			 *
500
			 * @since 1.9.0
501
			 *
502
			 * @param string $module Module slug.
503
			 */
504
			do_action( "jetpack_activate_module_$module", $module );
505
		}
506
507
		foreach ( $new_inactive_modules as $module ) {
508
			/**
509
			 * Fired after a module has been deactivated.
510
			 *
511
			 * @since 4.2.0
512
			 *
513
			 * @param string $module Module slug.
514
			 * @param boolean $success whether the module was deactivated.
515
			 */
516
			do_action( 'jetpack_deactivate_module', $module, $success );
517
			/**
518
			 * Fires when a module is deactivated.
519
			 * The dynamic part of the filter, $module, is the module slug.
520
			 *
521
			 * @since 1.9.0
522
			 *
523
			 * @param string $module Module slug.
524
			 */
525
			do_action( "jetpack_deactivate_module_$module", $module );
526
		}
527
528
		return $success;
529
	}
530
531
	static function delete_active_modules() {
532
		self::update_active_modules( array() );
533
	}
534
535
	/**
536
	 * Constructor.  Initializes WordPress hooks
537
	 */
538
	private function __construct() {
539
		/*
540
		 * Check for and alert any deprecated hooks
541
		 */
542
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
543
544
		/*
545
		 * Enable enhanced handling of previewing sites in Calypso
546
		 */
547
		if ( Jetpack::is_active() ) {
548
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
549
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
550
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
551
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
552
		}
553
554
		if ( self::jetpack_tos_agreed() ) {
555
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
556
			add_action( 'init', array( $tracking, 'init' ) );
557
		}
558
559
		/*
560
		 * Load things that should only be in Network Admin.
561
		 *
562
		 * For now blow away everything else until a more full
563
		 * understanding of what is needed at the network level is
564
		 * available
565
		 */
566
		if ( is_multisite() ) {
567
			Jetpack_Network::init();
568
		}
569
570
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
571
			return function() {
572
				return wp_generate_password( 32, false );
573
			};
574
		} );
575
576
		$this->connection_manager = new Connection_Manager( );
577
578
		/**
579
		 * Prepare Gutenberg Editor functionality
580
		 */
581
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
582
		Jetpack_Gutenberg::init();
583
		Jetpack_Gutenberg::load_independent_blocks();
584
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
585
586
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
587
588
		// Unlink user before deleting the user from .com
589
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
590
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
591
592
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
593
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
594
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
595
				define( 'XMLRPC_REQUEST', true );
596
			}
597
598
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
599
600
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
601
		}
602
603
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
604
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
605
606
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
607
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
608
609
			$this->require_jetpack_authentication();
610
611
			if ( Jetpack::is_active() ) {
612
				// Hack to preserve $HTTP_RAW_POST_DATA
613
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
614
615 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
616
					// The actual API methods.
617
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
618
				} else {
619
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
620
					// active Jetpack connection, so that additional users can link their account.
621
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
622
				}
623 View Code Duplication
			} else {
624
				new XMLRPC_Connector( $this->connection_manager );
625
626
				// The bootstrap API methods.
627
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
628
629
				if ( $this->verify_xml_rpc_signature() ) {
630
					// the jetpack Provision method is available for blog-token-signed requests
631
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
632
				}
633
			}
634
635
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
636
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
637
		} elseif (
638
			is_admin() &&
639
			isset( $_POST['action'] ) && (
640
				'jetpack_upload_file' == $_POST['action'] ||
641
				'jetpack_update_file' == $_POST['action']
642
			)
643
		) {
644
			$this->require_jetpack_authentication();
645
			$this->add_remote_request_handlers();
646
		} else {
647
			if ( Jetpack::is_active() ) {
648
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
649
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
650
			} else {
651
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
652
			}
653
		}
654
655
		if ( Jetpack::is_active() ) {
656
			Jetpack_Heartbeat::init();
657
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
658
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
659
				Jetpack_Search_Performance_Logger::init();
660
			}
661
		}
662
663
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
664
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
665
666
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
667
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
668
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
669
		}
670
671
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
672
673
		add_action( 'admin_init', array( $this, 'admin_init' ) );
674
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
675
676
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
677
678
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
679
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
680
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
681
682
		// returns HTTPS support status
683
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
684
685
		// JITM AJAX callback function
686
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
687
688
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
689
690
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
691
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
692
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
693
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
694
695
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
696
697
		/**
698
		 * These actions run checks to load additional files.
699
		 * They check for external files or plugins, so they need to run as late as possible.
700
		 */
701
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
702
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
703
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
704
705
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
706
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
707
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
708
709
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
710
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
711
712
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
713
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
714
715
		// A filter to control all just in time messages
716
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
717
718
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
719
720
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
721
		// We should make sure to only do this for front end links.
722
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
723
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
724
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
725
726
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
727
			//so they point moderation links on emails to Calypso
728
			jetpack_require_lib( 'functions.wp-notify' );
729
		}
730
731
		// Hide edit post link if mobile app.
732
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
733
			add_filter( 'edit_post_link', '__return_empty_string' );
734
		}
735
736
		// Update the Jetpack plan from API on heartbeats
737
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
738
739
		/**
740
		 * This is the hack to concatenate all css files into one.
741
		 * For description and reasoning see the implode_frontend_css method
742
		 *
743
		 * Super late priority so we catch all the registered styles
744
		 */
745
		if( !is_admin() ) {
746
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
747
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
748
		}
749
750
751
		/**
752
		 * These are sync actions that we need to keep track of for jitms
753
		 */
754
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
755
756
		// Actually push the stats on shutdown.
757
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
758
			add_action( 'shutdown', array( $this, 'push_stats' ) );
759
		}
760
761
	}
762
763
	function initialize_rest_api_registration_connector() {
764
		new REST_Connector( $this->connection_manager );
765
	}
766
767
	/**
768
	 * This is ported over from the manage module, which has been deprecated and baked in here.
769
	 *
770
	 * @param $domains
771
	 */
772
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
773
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
774
	}
775
776
	/**
777
	 * Return $domains, with 'wordpress.com' appended.
778
	 * This is ported over from the manage module, which has been deprecated and baked in here.
779
	 *
780
	 * @param $domains
781
	 * @return array
782
	 */
783
	function allow_wpcom_domain( $domains ) {
784
		if ( empty( $domains ) ) {
785
			$domains = array();
786
		}
787
		$domains[] = 'wordpress.com';
788
		return array_unique( $domains );
789
	}
790
791
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
792
		$post = get_post( $post_id );
793
794
		if ( empty( $post ) ) {
795
			return $default_url;
796
		}
797
798
		$post_type = $post->post_type;
799
800
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
801
		// https://en.support.wordpress.com/custom-post-types/
802
		$allowed_post_types = array(
803
			'post' => 'post',
804
			'page' => 'page',
805
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
806
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
807
		);
808
809
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
810
			return $default_url;
811
		}
812
813
		$path_prefix = $allowed_post_types[ $post_type ];
814
815
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
816
817
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
818
	}
819
820
	function point_edit_comment_links_to_calypso( $url ) {
821
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
822
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
823
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
824
			Jetpack::build_raw_urls( get_home_url() ),
825
			$query_args['amp;c']
826
		) );
827
	}
828
829
	function jetpack_track_last_sync_callback( $params ) {
830
		/**
831
		 * Filter to turn off jitm caching
832
		 *
833
		 * @since 5.4.0
834
		 *
835
		 * @param bool false Whether to cache just in time messages
836
		 */
837
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
838
			return $params;
839
		}
840
841
		if ( is_array( $params ) && isset( $params[0] ) ) {
842
			$option = $params[0];
843
			if ( 'active_plugins' === $option ) {
844
				// use the cache if we can, but not terribly important if it gets evicted
845
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
846
			}
847
		}
848
849
		return $params;
850
	}
851
852
	function jetpack_connection_banner_callback() {
853
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
854
855
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
856
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
857
			wp_send_json_success();
858
		}
859
860
		wp_die();
861
	}
862
863
	/**
864
	 * Removes all XML-RPC methods that are not `jetpack.*`.
865
	 * Only used in our alternate XML-RPC endpoint, where we want to
866
	 * ensure that Core and other plugins' methods are not exposed.
867
	 *
868
	 * @param array $methods
869
	 * @return array filtered $methods
870
	 */
871
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
872
		$jetpack_methods = array();
873
874
		foreach ( $methods as $method => $callback ) {
875
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
876
				$jetpack_methods[ $method ] = $callback;
877
			}
878
		}
879
880
		return $jetpack_methods;
881
	}
882
883
	/**
884
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
885
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
886
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
887
	 * which is accessible via a different URI. Most of the below is copied directly
888
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
889
	 */
890
	function alternate_xmlrpc() {
891
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
892
		global $HTTP_RAW_POST_DATA;
893
894
		// Some browser-embedded clients send cookies. We don't want them.
895
		$_COOKIE = array();
896
897
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
898
		// but we can do it ourself.
899
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
900
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
901
		}
902
903
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
904
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
905
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
906
		}
907
908
		// phpcs:enable
909
910
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
911
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
912
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
913
914
		/**
915
		 * Filters the class used for handling XML-RPC requests.
916
		 *
917
		 * @since 3.1.0
918
		 *
919
		 * @param string $class The name of the XML-RPC server class.
920
		 */
921
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
922
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
923
924
		// Fire off the request
925
		nocache_headers();
926
		$wp_xmlrpc_server->serve_request();
927
928
		exit;
929
	}
930
931
	/**
932
	 * The callback for the JITM ajax requests.
933
	 */
934
	function jetpack_jitm_ajax_callback() {
935
		// Check for nonce
936
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
937
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
938
		}
939
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
940
			$module_slug = $_REQUEST['jitmModule'];
941
			Jetpack::log( 'activate', $module_slug );
942
			Jetpack::activate_module( $module_slug, false, false );
943
			Jetpack::state( 'message', 'no_message' );
944
945
			//A Jetpack module is being activated through a JITM, track it
946
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
947
			$this->do_stats( 'server_side' );
948
949
			wp_send_json_success();
950
		}
951
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
952
			// get the hide_jitm options array
953
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
954
			$module_slug = $_REQUEST['jitmModule'];
955
956
			if( ! $jetpack_hide_jitm ) {
957
				$jetpack_hide_jitm = array(
958
					$module_slug => 'hide'
959
				);
960
			} else {
961
				$jetpack_hide_jitm[$module_slug] = 'hide';
962
			}
963
964
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
965
966
			//jitm is being dismissed forever, track it
967
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
968
			$this->do_stats( 'server_side' );
969
970
			wp_send_json_success();
971
		}
972 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
973
			$module_slug = $_REQUEST['jitmModule'];
974
975
			// User went to WordPress.com, track this
976
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
977
			$this->do_stats( 'server_side' );
978
979
			wp_send_json_success();
980
		}
981 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
982
			$track = $_REQUEST['jitmModule'];
983
984
			// User is viewing JITM, track it.
985
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
986
			$this->do_stats( 'server_side' );
987
988
			wp_send_json_success();
989
		}
990
	}
991
992
	/**
993
	 * If there are any stats that need to be pushed, but haven't been, push them now.
994
	 */
995
	function push_stats() {
996
		if ( ! empty( $this->stats ) ) {
997
			$this->do_stats( 'server_side' );
998
		}
999
	}
1000
1001
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1002
		switch( $cap ) {
1003
			case 'jetpack_connect' :
1004
			case 'jetpack_reconnect' :
1005
				if ( Jetpack::is_development_mode() ) {
1006
					$caps = array( 'do_not_allow' );
1007
					break;
1008
				}
1009
				/**
1010
				 * Pass through. If it's not development mode, these should match disconnect.
1011
				 * Let users disconnect if it's development mode, just in case things glitch.
1012
				 */
1013
			case 'jetpack_disconnect' :
1014
				/**
1015
				 * In multisite, can individual site admins manage their own connection?
1016
				 *
1017
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1018
				 */
1019
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1020
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1021
						/**
1022
						 * We need to update the option name -- it's terribly unclear which
1023
						 * direction the override goes.
1024
						 *
1025
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1026
						 */
1027
						$caps = array( 'do_not_allow' );
1028
						break;
1029
					}
1030
				}
1031
1032
				$caps = array( 'manage_options' );
1033
				break;
1034
			case 'jetpack_manage_modules' :
1035
			case 'jetpack_activate_modules' :
1036
			case 'jetpack_deactivate_modules' :
1037
				$caps = array( 'manage_options' );
1038
				break;
1039
			case 'jetpack_configure_modules' :
1040
				$caps = array( 'manage_options' );
1041
				break;
1042
			case 'jetpack_manage_autoupdates' :
1043
				$caps = array(
1044
					'manage_options',
1045
					'update_plugins',
1046
				);
1047
				break;
1048
			case 'jetpack_network_admin_page':
1049
			case 'jetpack_network_settings_page':
1050
				$caps = array( 'manage_network_plugins' );
1051
				break;
1052
			case 'jetpack_network_sites_page':
1053
				$caps = array( 'manage_sites' );
1054
				break;
1055
			case 'jetpack_admin_page' :
1056
				if ( Jetpack::is_development_mode() ) {
1057
					$caps = array( 'manage_options' );
1058
					break;
1059
				} else {
1060
					$caps = array( 'read' );
1061
				}
1062
				break;
1063
			case 'jetpack_connect_user' :
1064
				if ( Jetpack::is_development_mode() ) {
1065
					$caps = array( 'do_not_allow' );
1066
					break;
1067
				}
1068
				$caps = array( 'read' );
1069
				break;
1070
		}
1071
		return $caps;
1072
	}
1073
1074
	function require_jetpack_authentication() {
1075
		// Don't let anyone authenticate
1076
		$_COOKIE = array();
1077
		remove_all_filters( 'authenticate' );
1078
		remove_all_actions( 'wp_login_failed' );
1079
1080
		if ( Jetpack::is_active() ) {
1081
			// Allow Jetpack authentication
1082
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1083
		}
1084
	}
1085
1086
	/**
1087
	 * Load language files
1088
	 * @action plugins_loaded
1089
	 */
1090
	public static function plugin_textdomain() {
1091
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1092
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1093
	}
1094
1095
	/**
1096
	 * Register assets for use in various modules and the Jetpack admin page.
1097
	 *
1098
	 * @uses wp_script_is, wp_register_script, plugins_url
1099
	 * @action wp_loaded
1100
	 * @return null
1101
	 */
1102
	public function register_assets() {
1103
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1104
			wp_register_script(
1105
				'spin',
1106
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1107
				false,
1108
				'1.3'
1109
			);
1110
		}
1111
1112 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1113
			wp_register_script(
1114
				'jquery.spin',
1115
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1116
				array( 'jquery', 'spin' ),
1117
				'1.3'
1118
			);
1119
		}
1120
1121 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1122
			wp_register_script(
1123
				'jetpack-gallery-settings',
1124
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1125
				array( 'media-views' ),
1126
				'20121225'
1127
			);
1128
		}
1129
1130 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1131
			wp_register_script(
1132
				'jetpack-twitter-timeline',
1133
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1134
				array( 'jquery' ),
1135
				'4.0.0',
1136
				true
1137
			);
1138
		}
1139
1140
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1141
			wp_register_script(
1142
				'jetpack-facebook-embed',
1143
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1144
				array( 'jquery' ),
1145
				null,
1146
				true
1147
			);
1148
1149
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1150
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1151
			if ( ! is_numeric( $fb_app_id ) ) {
1152
				$fb_app_id = '';
1153
			}
1154
			wp_localize_script(
1155
				'jetpack-facebook-embed',
1156
				'jpfbembed',
1157
				array(
1158
					'appid' => $fb_app_id,
1159
					'locale' => $this->get_locale(),
1160
				)
1161
			);
1162
		}
1163
1164
		/**
1165
		 * As jetpack_register_genericons is by default fired off a hook,
1166
		 * the hook may have already fired by this point.
1167
		 * So, let's just trigger it manually.
1168
		 */
1169
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1170
		jetpack_register_genericons();
1171
1172
		/**
1173
		 * Register the social logos
1174
		 */
1175
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1176
		jetpack_register_social_logos();
1177
1178 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1179
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1180
	}
1181
1182
	/**
1183
	 * Guess locale from language code.
1184
	 *
1185
	 * @param string $lang Language code.
1186
	 * @return string|bool
1187
	 */
1188 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1189
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1190
			return 'en_US';
1191
		}
1192
1193
		if ( ! class_exists( 'GP_Locales' ) ) {
1194
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1195
				return false;
1196
			}
1197
1198
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1199
		}
1200
1201
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1202
			// WP.com: get_locale() returns 'it'
1203
			$locale = GP_Locales::by_slug( $lang );
1204
		} else {
1205
			// Jetpack: get_locale() returns 'it_IT';
1206
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1207
		}
1208
1209
		if ( ! $locale ) {
1210
			return false;
1211
		}
1212
1213
		if ( empty( $locale->facebook_locale ) ) {
1214
			if ( empty( $locale->wp_locale ) ) {
1215
				return false;
1216
			} else {
1217
				// Facebook SDK is smart enough to fall back to en_US if a
1218
				// locale isn't supported. Since supported Facebook locales
1219
				// can fall out of sync, we'll attempt to use the known
1220
				// wp_locale value and rely on said fallback.
1221
				return $locale->wp_locale;
1222
			}
1223
		}
1224
1225
		return $locale->facebook_locale;
1226
	}
1227
1228
	/**
1229
	 * Get the locale.
1230
	 *
1231
	 * @return string|bool
1232
	 */
1233
	function get_locale() {
1234
		$locale = $this->guess_locale_from_lang( get_locale() );
1235
1236
		if ( ! $locale ) {
1237
			$locale = 'en_US';
1238
		}
1239
1240
		return $locale;
1241
	}
1242
1243
	/**
1244
	 * Device Pixels support
1245
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1246
	 */
1247
	function devicepx() {
1248
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1249
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1250
		}
1251
	}
1252
1253
	/**
1254
	 * Return the network_site_url so that .com knows what network this site is a part of.
1255
	 * @param  bool $option
1256
	 * @return string
1257
	 */
1258
	public function jetpack_main_network_site_option( $option ) {
1259
		return network_site_url();
1260
	}
1261
	/**
1262
	 * Network Name.
1263
	 */
1264
	static function network_name( $option = null ) {
1265
		global $current_site;
1266
		return $current_site->site_name;
1267
	}
1268
	/**
1269
	 * Does the network allow new user and site registrations.
1270
	 * @return string
1271
	 */
1272
	static function network_allow_new_registrations( $option = null ) {
1273
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1274
	}
1275
	/**
1276
	 * Does the network allow admins to add new users.
1277
	 * @return boolian
1278
	 */
1279
	static function network_add_new_users( $option = null ) {
1280
		return (bool) get_site_option( 'add_new_users' );
1281
	}
1282
	/**
1283
	 * File upload psace left per site in MB.
1284
	 *  -1 means NO LIMIT.
1285
	 * @return number
1286
	 */
1287
	static function network_site_upload_space( $option = null ) {
1288
		// value in MB
1289
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1290
	}
1291
1292
	/**
1293
	 * Network allowed file types.
1294
	 * @return string
1295
	 */
1296
	static function network_upload_file_types( $option = null ) {
1297
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1298
	}
1299
1300
	/**
1301
	 * Maximum file upload size set by the network.
1302
	 * @return number
1303
	 */
1304
	static function network_max_upload_file_size( $option = null ) {
1305
		// value in KB
1306
		return get_site_option( 'fileupload_maxk', 300 );
1307
	}
1308
1309
	/**
1310
	 * Lets us know if a site allows admins to manage the network.
1311
	 * @return array
1312
	 */
1313
	static function network_enable_administration_menus( $option = null ) {
1314
		return get_site_option( 'menu_items' );
1315
	}
1316
1317
	/**
1318
	 * If a user has been promoted to or demoted from admin, we need to clear the
1319
	 * jetpack_other_linked_admins transient.
1320
	 *
1321
	 * @since 4.3.2
1322
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1323
	 *
1324
	 * @param int    $user_id   The user ID whose role changed.
1325
	 * @param string $role      The new role.
1326
	 * @param array  $old_roles An array of the user's previous roles.
1327
	 */
1328
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1329
		if ( 'administrator' == $role
1330
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1331
			|| is_null( $old_roles )
1332
		) {
1333
			delete_transient( 'jetpack_other_linked_admins' );
1334
		}
1335
	}
1336
1337
	/**
1338
	 * Checks to see if there are any other users available to become primary
1339
	 * Users must both:
1340
	 * - Be linked to wpcom
1341
	 * - Be an admin
1342
	 *
1343
	 * @return mixed False if no other users are linked, Int if there are.
1344
	 */
1345
	static function get_other_linked_admins() {
1346
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1347
1348
		if ( false === $other_linked_users ) {
1349
			$admins = get_users( array( 'role' => 'administrator' ) );
1350
			if ( count( $admins ) > 1 ) {
1351
				$available = array();
1352
				foreach ( $admins as $admin ) {
1353
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1354
						$available[] = $admin->ID;
1355
					}
1356
				}
1357
1358
				$count_connected_admins = count( $available );
1359
				if ( count( $available ) > 1 ) {
1360
					$other_linked_users = $count_connected_admins;
1361
				} else {
1362
					$other_linked_users = 0;
1363
				}
1364
			} else {
1365
				$other_linked_users = 0;
1366
			}
1367
1368
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1369
		}
1370
1371
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1372
	}
1373
1374
	/**
1375
	 * Return whether we are dealing with a multi network setup or not.
1376
	 * The reason we are type casting this is because we want to avoid the situation where
1377
	 * the result is false since when is_main_network_option return false it cases
1378
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1379
	 * database which could be set to anything as opposed to what this function returns.
1380
	 * @param  bool  $option
1381
	 *
1382
	 * @return boolean
1383
	 */
1384
	public function is_main_network_option( $option ) {
1385
		// return '1' or ''
1386
		return (string) (bool) Jetpack::is_multi_network();
1387
	}
1388
1389
	/**
1390
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1391
	 *
1392
	 * @param  string  $option
1393
	 * @return boolean
1394
	 */
1395
	public function is_multisite( $option ) {
1396
		return (string) (bool) is_multisite();
1397
	}
1398
1399
	/**
1400
	 * Implemented since there is no core is multi network function
1401
	 * Right now there is no way to tell if we which network is the dominant network on the system
1402
	 *
1403
	 * @since  3.3
1404
	 * @return boolean
1405
	 */
1406 View Code Duplication
	public static function is_multi_network() {
1407
		global  $wpdb;
1408
1409
		// if we don't have a multi site setup no need to do any more
1410
		if ( ! is_multisite() ) {
1411
			return false;
1412
		}
1413
1414
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1415
		if ( $num_sites > 1 ) {
1416
			return true;
1417
		} else {
1418
			return false;
1419
		}
1420
	}
1421
1422
	/**
1423
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1424
	 * @return null
1425
	 */
1426
	function update_jetpack_main_network_site_option() {
1427
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1428
	}
1429
	/**
1430
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1431
	 *
1432
	 */
1433
	function update_jetpack_network_settings() {
1434
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1435
		// Only sync this info for the main network site.
1436
	}
1437
1438
	/**
1439
	 * Get back if the current site is single user site.
1440
	 *
1441
	 * @return bool
1442
	 */
1443 View Code Duplication
	public static function is_single_user_site() {
1444
		global $wpdb;
1445
1446
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1447
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1448
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1449
		}
1450
		return 1 === (int) $some_users;
1451
	}
1452
1453
	/**
1454
	 * Returns true if the site has file write access false otherwise.
1455
	 * @return string ( '1' | '0' )
1456
	 **/
1457
	public static function file_system_write_access() {
1458
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1459
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1460
		}
1461
1462
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1463
1464
		$filesystem_method = get_filesystem_method();
1465
		if ( $filesystem_method === 'direct' ) {
1466
			return 1;
1467
		}
1468
1469
		ob_start();
1470
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1471
		ob_end_clean();
1472
		if ( $filesystem_credentials_are_stored ) {
1473
			return 1;
1474
		}
1475
		return 0;
1476
	}
1477
1478
	/**
1479
	 * Finds out if a site is using a version control system.
1480
	 * @return string ( '1' | '0' )
1481
	 **/
1482
	public static function is_version_controlled() {
1483
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1484
		return (string) (int) Functions::is_version_controlled();
1485
	}
1486
1487
	/**
1488
	 * Determines whether the current theme supports featured images or not.
1489
	 * @return string ( '1' | '0' )
1490
	 */
1491
	public static function featured_images_enabled() {
1492
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1493
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1494
	}
1495
1496
	/**
1497
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1498
	 *
1499
	 * @deprecated 4.7 use get_avatar_url instead.
1500
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1501
	 * @param int $size Size of the avatar image
1502
	 * @param string $default URL to a default image to use if no avatar is available
1503
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1504
	 *
1505
	 * @return array
1506
	 */
1507
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1508
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1509
		return get_avatar_url( $id_or_email, array(
1510
			'size' => $size,
1511
			'default' => $default,
1512
			'force_default' => $force_display,
1513
		) );
1514
	}
1515
1516
	/**
1517
	 * jetpack_updates is saved in the following schema:
1518
	 *
1519
	 * array (
1520
	 *      'plugins'                       => (int) Number of plugin updates available.
1521
	 *      'themes'                        => (int) Number of theme updates available.
1522
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1523
	 *      'translations'                  => (int) Number of translation updates available.
1524
	 *      'total'                         => (int) Total of all available updates.
1525
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1526
	 * )
1527
	 * @return array
1528
	 */
1529
	public static function get_updates() {
1530
		$update_data = wp_get_update_data();
1531
1532
		// Stores the individual update counts as well as the total count.
1533
		if ( isset( $update_data['counts'] ) ) {
1534
			$updates = $update_data['counts'];
1535
		}
1536
1537
		// If we need to update WordPress core, let's find the latest version number.
1538 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1539
			$cur = get_preferred_from_update_core();
1540
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1541
				$updates['wp_update_version'] = $cur->current;
1542
			}
1543
		}
1544
		return isset( $updates ) ? $updates : array();
1545
	}
1546
1547
	public static function get_update_details() {
1548
		$update_details = array(
1549
			'update_core' => get_site_transient( 'update_core' ),
1550
			'update_plugins' => get_site_transient( 'update_plugins' ),
1551
			'update_themes' => get_site_transient( 'update_themes' ),
1552
		);
1553
		return $update_details;
1554
	}
1555
1556
	public static function refresh_update_data() {
1557
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1558
1559
	}
1560
1561
	public static function refresh_theme_data() {
1562
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1563
	}
1564
1565
	/**
1566
	 * Is Jetpack active?
1567
	 */
1568
	public static function is_active() {
1569
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1570
	}
1571
1572
	/**
1573
	 * Make an API call to WordPress.com for plan status
1574
	 *
1575
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1576
	 *
1577
	 * @return bool True if plan is updated, false if no update
1578
	 */
1579
	public static function refresh_active_plan_from_wpcom() {
1580
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1581
		return Jetpack_Plan::refresh_from_wpcom();
1582
	}
1583
1584
	/**
1585
	 * Get the plan that this Jetpack site is currently using
1586
	 *
1587
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1588
	 * @return array Active Jetpack plan details.
1589
	 */
1590
	public static function get_active_plan() {
1591
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1592
		return Jetpack_Plan::get();
1593
	}
1594
1595
	/**
1596
	 * Determine whether the active plan supports a particular feature
1597
	 *
1598
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1599
	 * @return bool True if plan supports feature, false if not.
1600
	 */
1601
	public static function active_plan_supports( $feature ) {
1602
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1603
		return Jetpack_Plan::supports( $feature );
1604
	}
1605
1606
	/**
1607
	 * Is Jetpack in development (offline) mode?
1608
	 */
1609 View Code Duplication
	public static function is_development_mode() {
1610
		$development_mode = false;
1611
1612
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1613
			$development_mode = JETPACK_DEV_DEBUG;
1614
		} elseif ( $site_url = site_url() ) {
1615
			$development_mode = false === strpos( $site_url, '.' );
1616
		}
1617
1618
		/**
1619
		 * Filters Jetpack's development mode.
1620
		 *
1621
		 * @see https://jetpack.com/support/development-mode/
1622
		 *
1623
		 * @since 2.2.1
1624
		 *
1625
		 * @param bool $development_mode Is Jetpack's development mode active.
1626
		 */
1627
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1628
		return $development_mode;
1629
	}
1630
1631
	/**
1632
	 * Whether the site is currently onboarding or not.
1633
	 * A site is considered as being onboarded if it currently has an onboarding token.
1634
	 *
1635
	 * @since 5.8
1636
	 *
1637
	 * @access public
1638
	 * @static
1639
	 *
1640
	 * @return bool True if the site is currently onboarding, false otherwise
1641
	 */
1642
	public static function is_onboarding() {
1643
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1644
	}
1645
1646
	/**
1647
	 * Determines reason for Jetpack development mode.
1648
	 */
1649
	public static function development_mode_trigger_text() {
1650
		if ( ! Jetpack::is_development_mode() ) {
1651
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1652
		}
1653
1654
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1655
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1656
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1657
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1658
		} else {
1659
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1660
		}
1661
1662
		return $notice;
1663
1664
	}
1665
	/**
1666
	* Get Jetpack development mode notice text and notice class.
1667
	*
1668
	* Mirrors the checks made in Jetpack::is_development_mode
1669
	*
1670
	*/
1671
	public static function show_development_mode_notice() {
1672 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1673
			$notice = sprintf(
1674
			/* translators: %s is a URL */
1675
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1676
				'https://jetpack.com/support/development-mode/'
1677
			);
1678
1679
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1680
1681
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1682
		}
1683
1684
		// Throw up a notice if using a development version and as for feedback.
1685
		if ( Jetpack::is_development_version() ) {
1686
			/* translators: %s is a URL */
1687
			$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/' );
1688
1689
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1690
		}
1691
		// Throw up a notice if using staging mode
1692
		if ( Jetpack::is_staging_site() ) {
1693
			/* translators: %s is a URL */
1694
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1695
1696
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1697
		}
1698
	}
1699
1700
	/**
1701
	 * Whether Jetpack's version maps to a public release, or a development version.
1702
	 */
1703
	public static function is_development_version() {
1704
		/**
1705
		 * Allows filtering whether this is a development version of Jetpack.
1706
		 *
1707
		 * This filter is especially useful for tests.
1708
		 *
1709
		 * @since 4.3.0
1710
		 *
1711
		 * @param bool $development_version Is this a develoment version of Jetpack?
1712
		 */
1713
		return (bool) apply_filters(
1714
			'jetpack_development_version',
1715
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1716
		);
1717
	}
1718
1719
	/**
1720
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1721
	 */
1722
	public static function is_user_connected( $user_id = false ) {
1723
		return self::connection()->is_user_connected( $user_id );
1724
	}
1725
1726
	/**
1727
	 * Get the wpcom user data of the current|specified connected user.
1728
	 */
1729 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1730
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1731
		if ( ! $user_id ) {
1732
			$user_id = get_current_user_id();
1733
		}
1734
1735
		$transient_key = "jetpack_connected_user_data_$user_id";
1736
1737
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1738
			return $cached_user_data;
1739
		}
1740
1741
		Jetpack::load_xml_rpc_client();
1742
		$xml = new Jetpack_IXR_Client( array(
1743
			'user_id' => $user_id,
1744
		) );
1745
		$xml->query( 'wpcom.getUser' );
1746
		if ( ! $xml->isError() ) {
1747
			$user_data = $xml->getResponse();
1748
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1749
			return $user_data;
1750
		}
1751
1752
		return false;
1753
	}
1754
1755
	/**
1756
	 * Get the wpcom email of the current|specified connected user.
1757
	 */
1758 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1759
		if ( ! $user_id ) {
1760
			$user_id = get_current_user_id();
1761
		}
1762
		Jetpack::load_xml_rpc_client();
1763
		$xml = new Jetpack_IXR_Client( array(
1764
			'user_id' => $user_id,
1765
		) );
1766
		$xml->query( 'wpcom.getUserEmail' );
1767
		if ( ! $xml->isError() ) {
1768
			return $xml->getResponse();
1769
		}
1770
		return false;
1771
	}
1772
1773
	/**
1774
	 * Get the wpcom email of the master user.
1775
	 */
1776
	public static function get_master_user_email() {
1777
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1778
		if ( $master_user_id ) {
1779
			return self::get_connected_user_email( $master_user_id );
1780
		}
1781
		return '';
1782
	}
1783
1784
	function current_user_is_connection_owner() {
1785
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1786
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1787
	}
1788
1789
	/**
1790
	 * Gets current user IP address.
1791
	 *
1792
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1793
	 *
1794
	 * @return string                  Current user IP address.
1795
	 */
1796
	public static function current_user_ip( $check_all_headers = false ) {
1797
		if ( $check_all_headers ) {
1798
			foreach ( array(
1799
				'HTTP_CF_CONNECTING_IP',
1800
				'HTTP_CLIENT_IP',
1801
				'HTTP_X_FORWARDED_FOR',
1802
				'HTTP_X_FORWARDED',
1803
				'HTTP_X_CLUSTER_CLIENT_IP',
1804
				'HTTP_FORWARDED_FOR',
1805
				'HTTP_FORWARDED',
1806
				'HTTP_VIA',
1807
			) as $key ) {
1808
				if ( ! empty( $_SERVER[ $key ] ) ) {
1809
					return $_SERVER[ $key ];
1810
				}
1811
			}
1812
		}
1813
1814
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1815
	}
1816
1817
	/**
1818
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1819
	 */
1820
	function extra_oembed_providers() {
1821
		// Cloudup: https://dev.cloudup.com/#oembed
1822
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1823
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1824
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1825
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1826
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1827
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1828
	}
1829
1830
	/**
1831
	 * Synchronize connected user role changes
1832
	 */
1833
	function user_role_change( $user_id ) {
1834
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1835
		Users::user_role_change( $user_id );
1836
	}
1837
1838
	/**
1839
	 * Loads the currently active modules.
1840
	 */
1841
	public static function load_modules() {
1842
		if (
1843
			! self::is_active()
1844
			&& ! self::is_development_mode()
1845
			&& ! self::is_onboarding()
1846
			&& (
1847
				! is_multisite()
1848
				|| ! get_site_option( 'jetpack_protect_active' )
1849
			)
1850
		) {
1851
			return;
1852
		}
1853
1854
		$version = Jetpack_Options::get_option( 'version' );
1855 View Code Duplication
		if ( ! $version ) {
1856
			$version = $old_version = JETPACK__VERSION . ':' . time();
1857
			/** This action is documented in class.jetpack.php */
1858
			do_action( 'updating_jetpack_version', $version, false );
1859
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1860
		}
1861
		list( $version ) = explode( ':', $version );
1862
1863
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1864
1865
		$modules_data = array();
1866
1867
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1868
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1869
			$updated_modules = array();
1870
			foreach ( $modules as $module ) {
1871
				$modules_data[ $module ] = Jetpack::get_module( $module );
1872
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1873
					continue;
1874
				}
1875
1876
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1877
					continue;
1878
				}
1879
1880
				$updated_modules[] = $module;
1881
			}
1882
1883
			$modules = array_diff( $modules, $updated_modules );
1884
		}
1885
1886
		$is_development_mode = Jetpack::is_development_mode();
1887
1888
		foreach ( $modules as $index => $module ) {
1889
			// If we're in dev mode, disable modules requiring a connection
1890
			if ( $is_development_mode ) {
1891
				// Prime the pump if we need to
1892
				if ( empty( $modules_data[ $module ] ) ) {
1893
					$modules_data[ $module ] = Jetpack::get_module( $module );
1894
				}
1895
				// If the module requires a connection, but we're in local mode, don't include it.
1896
				if ( $modules_data[ $module ]['requires_connection'] ) {
1897
					continue;
1898
				}
1899
			}
1900
1901
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1902
				continue;
1903
			}
1904
1905
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1906
				unset( $modules[ $index ] );
1907
				self::update_active_modules( array_values( $modules ) );
1908
				continue;
1909
			}
1910
1911
			/**
1912
			 * Fires when a specific module is loaded.
1913
			 * The dynamic part of the hook, $module, is the module slug.
1914
			 *
1915
			 * @since 1.1.0
1916
			 */
1917
			do_action( 'jetpack_module_loaded_' . $module );
1918
		}
1919
1920
		/**
1921
		 * Fires when all the modules are loaded.
1922
		 *
1923
		 * @since 1.1.0
1924
		 */
1925
		do_action( 'jetpack_modules_loaded' );
1926
1927
		// 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.
1928
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1929
	}
1930
1931
	/**
1932
	 * Check if Jetpack's REST API compat file should be included
1933
	 * @action plugins_loaded
1934
	 * @return null
1935
	 */
1936
	public function check_rest_api_compat() {
1937
		/**
1938
		 * Filters the list of REST API compat files to be included.
1939
		 *
1940
		 * @since 2.2.5
1941
		 *
1942
		 * @param array $args Array of REST API compat files to include.
1943
		 */
1944
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1945
1946
		if ( function_exists( 'bbpress' ) )
1947
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1948
1949
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1950
			require_once $_jetpack_rest_api_compat_include;
1951
	}
1952
1953
	/**
1954
	 * Gets all plugins currently active in values, regardless of whether they're
1955
	 * traditionally activated or network activated.
1956
	 *
1957
	 * @todo Store the result in core's object cache maybe?
1958
	 */
1959
	public static function get_active_plugins() {
1960
		$active_plugins = (array) get_option( 'active_plugins', array() );
1961
1962
		if ( is_multisite() ) {
1963
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1964
			// whereas active_plugins stores them in the values.
1965
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1966
			if ( $network_plugins ) {
1967
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1968
			}
1969
		}
1970
1971
		sort( $active_plugins );
1972
1973
		return array_unique( $active_plugins );
1974
	}
1975
1976
	/**
1977
	 * Gets and parses additional plugin data to send with the heartbeat data
1978
	 *
1979
	 * @since 3.8.1
1980
	 *
1981
	 * @return array Array of plugin data
1982
	 */
1983
	public static function get_parsed_plugin_data() {
1984
		if ( ! function_exists( 'get_plugins' ) ) {
1985
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1986
		}
1987
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1988
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1989
		$active_plugins = Jetpack::get_active_plugins();
1990
1991
		$plugins = array();
1992
		foreach ( $all_plugins as $path => $plugin_data ) {
1993
			$plugins[ $path ] = array(
1994
					'is_active' => in_array( $path, $active_plugins ),
1995
					'file'      => $path,
1996
					'name'      => $plugin_data['Name'],
1997
					'version'   => $plugin_data['Version'],
1998
					'author'    => $plugin_data['Author'],
1999
			);
2000
		}
2001
2002
		return $plugins;
2003
	}
2004
2005
	/**
2006
	 * Gets and parses theme data to send with the heartbeat data
2007
	 *
2008
	 * @since 3.8.1
2009
	 *
2010
	 * @return array Array of theme data
2011
	 */
2012
	public static function get_parsed_theme_data() {
2013
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2014
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2015
2016
		$themes = array();
2017
		foreach ( $all_themes as $slug => $theme_data ) {
2018
			$theme_headers = array();
2019
			foreach ( $header_keys as $header_key ) {
2020
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2021
			}
2022
2023
			$themes[ $slug ] = array(
2024
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2025
					'slug' => $slug,
2026
					'theme_root' => $theme_data->get_theme_root_uri(),
2027
					'parent' => $theme_data->parent(),
2028
					'headers' => $theme_headers
2029
			);
2030
		}
2031
2032
		return $themes;
2033
	}
2034
2035
	/**
2036
	 * Checks whether a specific plugin is active.
2037
	 *
2038
	 * We don't want to store these in a static variable, in case
2039
	 * there are switch_to_blog() calls involved.
2040
	 */
2041
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2042
		return in_array( $plugin, self::get_active_plugins() );
2043
	}
2044
2045
	/**
2046
	 * Check if Jetpack's Open Graph tags should be used.
2047
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2048
	 *
2049
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2050
	 * @action plugins_loaded
2051
	 * @return null
2052
	 */
2053
	public function check_open_graph() {
2054
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2055
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2056
		}
2057
2058
		$active_plugins = self::get_active_plugins();
2059
2060
		if ( ! empty( $active_plugins ) ) {
2061
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2062
				if ( in_array( $plugin, $active_plugins ) ) {
2063
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2064
					break;
2065
				}
2066
			}
2067
		}
2068
2069
		/**
2070
		 * Allow the addition of Open Graph Meta Tags to all pages.
2071
		 *
2072
		 * @since 2.0.3
2073
		 *
2074
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2075
		 */
2076
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2077
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2078
		}
2079
	}
2080
2081
	/**
2082
	 * Check if Jetpack's Twitter tags should be used.
2083
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2084
	 *
2085
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2086
	 * @action plugins_loaded
2087
	 * @return null
2088
	 */
2089
	public function check_twitter_tags() {
2090
2091
		$active_plugins = self::get_active_plugins();
2092
2093
		if ( ! empty( $active_plugins ) ) {
2094
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2095
				if ( in_array( $plugin, $active_plugins ) ) {
2096
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2097
					break;
2098
				}
2099
			}
2100
		}
2101
2102
		/**
2103
		 * Allow Twitter Card Meta tags to be disabled.
2104
		 *
2105
		 * @since 2.6.0
2106
		 *
2107
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2108
		 */
2109
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2110
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2111
		}
2112
	}
2113
2114
	/**
2115
	 * Allows plugins to submit security reports.
2116
 	 *
2117
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2118
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2119
	 * @param array   $args         See definitions above
2120
	 */
2121
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2122
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2123
	}
2124
2125
/* Jetpack Options API */
2126
2127
	public static function get_option_names( $type = 'compact' ) {
2128
		return Jetpack_Options::get_option_names( $type );
2129
	}
2130
2131
	/**
2132
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2133
 	 *
2134
	 * @param string $name    Option name
2135
	 * @param mixed  $default (optional)
2136
	 */
2137
	public static function get_option( $name, $default = false ) {
2138
		return Jetpack_Options::get_option( $name, $default );
2139
	}
2140
2141
	/**
2142
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2143
 	 *
2144
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2145
	 * @param string $name  Option name
2146
	 * @param mixed  $value Option value
2147
	 */
2148
	public static function update_option( $name, $value ) {
2149
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2150
		return Jetpack_Options::update_option( $name, $value );
2151
	}
2152
2153
	/**
2154
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2155
 	 *
2156
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2157
	 * @param array $array array( option name => option value, ... )
2158
	 */
2159
	public static function update_options( $array ) {
2160
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2161
		return Jetpack_Options::update_options( $array );
2162
	}
2163
2164
	/**
2165
	 * Deletes the given option.  May be passed multiple option names as an array.
2166
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2167
	 *
2168
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2169
	 * @param string|array $names
2170
	 */
2171
	public static function delete_option( $names ) {
2172
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2173
		return Jetpack_Options::delete_option( $names );
2174
	}
2175
2176
	/**
2177
	 * Enters a user token into the user_tokens option
2178
	 *
2179
	 * @param int $user_id
2180
	 * @param string $token
2181
	 * return bool
2182
	 */
2183
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2184
		// not designed for concurrent updates
2185
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2186
		if ( ! is_array( $user_tokens ) )
2187
			$user_tokens = array();
2188
		$user_tokens[$user_id] = $token;
2189
		if ( $is_master_user ) {
2190
			$master_user = $user_id;
2191
			$options     = compact( 'user_tokens', 'master_user' );
2192
		} else {
2193
			$options = compact( 'user_tokens' );
2194
		}
2195
		return Jetpack_Options::update_options( $options );
2196
	}
2197
2198
	/**
2199
	 * Returns an array of all PHP files in the specified absolute path.
2200
	 * Equivalent to glob( "$absolute_path/*.php" ).
2201
	 *
2202
	 * @param string $absolute_path The absolute path of the directory to search.
2203
	 * @return array Array of absolute paths to the PHP files.
2204
	 */
2205
	public static function glob_php( $absolute_path ) {
2206
		if ( function_exists( 'glob' ) ) {
2207
			return glob( "$absolute_path/*.php" );
2208
		}
2209
2210
		$absolute_path = untrailingslashit( $absolute_path );
2211
		$files = array();
2212
		if ( ! $dir = @opendir( $absolute_path ) ) {
2213
			return $files;
2214
		}
2215
2216
		while ( false !== $file = readdir( $dir ) ) {
2217
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2218
				continue;
2219
			}
2220
2221
			$file = "$absolute_path/$file";
2222
2223
			if ( ! is_file( $file ) ) {
2224
				continue;
2225
			}
2226
2227
			$files[] = $file;
2228
		}
2229
2230
		closedir( $dir );
2231
2232
		return $files;
2233
	}
2234
2235
	public static function activate_new_modules( $redirect = false ) {
2236
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2237
			return;
2238
		}
2239
2240
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2241 View Code Duplication
		if ( ! $jetpack_old_version ) {
2242
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2243
			/** This action is documented in class.jetpack.php */
2244
			do_action( 'updating_jetpack_version', $version, false );
2245
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2246
		}
2247
2248
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2249
2250
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2251
			return;
2252
		}
2253
2254
		$active_modules     = Jetpack::get_active_modules();
2255
		$reactivate_modules = array();
2256
		foreach ( $active_modules as $active_module ) {
2257
			$module = Jetpack::get_module( $active_module );
2258
			if ( ! isset( $module['changed'] ) ) {
2259
				continue;
2260
			}
2261
2262
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2263
				continue;
2264
			}
2265
2266
			$reactivate_modules[] = $active_module;
2267
			Jetpack::deactivate_module( $active_module );
2268
		}
2269
2270
		$new_version = JETPACK__VERSION . ':' . time();
2271
		/** This action is documented in class.jetpack.php */
2272
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2273
		Jetpack_Options::update_options(
2274
			array(
2275
				'version'     => $new_version,
2276
				'old_version' => $jetpack_old_version,
2277
			)
2278
		);
2279
2280
		Jetpack::state( 'message', 'modules_activated' );
2281
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2282
2283
		if ( $redirect ) {
2284
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2285
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2286
				$page = $_GET['page'];
2287
			}
2288
2289
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2290
			exit;
2291
		}
2292
	}
2293
2294
	/**
2295
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2296
	 * Make sure to tuck away module "library" files in a sub-directory.
2297
	 */
2298
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2299
		static $modules = null;
2300
2301
		if ( ! isset( $modules ) ) {
2302
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2303
			// Use the cache if we're on the front-end and it's available...
2304
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2305
				$modules = $available_modules_option[ JETPACK__VERSION ];
2306
			} else {
2307
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2308
2309
				$modules = array();
2310
2311
				foreach ( $files as $file ) {
2312
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2313
						continue;
2314
					}
2315
2316
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2317
				}
2318
2319
				Jetpack_Options::update_option( 'available_modules', array(
2320
					JETPACK__VERSION => $modules,
2321
				) );
2322
			}
2323
		}
2324
2325
		/**
2326
		 * Filters the array of modules available to be activated.
2327
		 *
2328
		 * @since 2.4.0
2329
		 *
2330
		 * @param array $modules Array of available modules.
2331
		 * @param string $min_version Minimum version number required to use modules.
2332
		 * @param string $max_version Maximum version number required to use modules.
2333
		 */
2334
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2335
2336
		if ( ! $min_version && ! $max_version ) {
2337
			return array_keys( $mods );
2338
		}
2339
2340
		$r = array();
2341
		foreach ( $mods as $slug => $introduced ) {
2342
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2343
				continue;
2344
			}
2345
2346
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2347
				continue;
2348
			}
2349
2350
			$r[] = $slug;
2351
		}
2352
2353
		return $r;
2354
	}
2355
2356
	/**
2357
	 * Default modules loaded on activation.
2358
	 */
2359
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2360
		$return = array();
2361
2362
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2363
			$module_data = Jetpack::get_module( $module );
2364
2365
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2366
				case 'yes' :
2367
					$return[] = $module;
2368
					break;
2369
				case 'public' :
2370
					if ( Jetpack_Options::get_option( 'public' ) ) {
2371
						$return[] = $module;
2372
					}
2373
					break;
2374
				case 'no' :
2375
				default :
2376
					break;
2377
			}
2378
		}
2379
		/**
2380
		 * Filters the array of default modules.
2381
		 *
2382
		 * @since 2.5.0
2383
		 *
2384
		 * @param array $return Array of default modules.
2385
		 * @param string $min_version Minimum version number required to use modules.
2386
		 * @param string $max_version Maximum version number required to use modules.
2387
		 */
2388
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2389
	}
2390
2391
	/**
2392
	 * Checks activated modules during auto-activation to determine
2393
	 * if any of those modules are being deprecated.  If so, close
2394
	 * them out, and add any replacement modules.
2395
	 *
2396
	 * Runs at priority 99 by default.
2397
	 *
2398
	 * This is run late, so that it can still activate a module if
2399
	 * the new module is a replacement for another that the user
2400
	 * currently has active, even if something at the normal priority
2401
	 * would kibosh everything.
2402
	 *
2403
	 * @since 2.6
2404
	 * @uses jetpack_get_default_modules filter
2405
	 * @param array $modules
2406
	 * @return array
2407
	 */
2408
	function handle_deprecated_modules( $modules ) {
2409
		$deprecated_modules = array(
2410
			'debug'            => null,  // Closed out and moved to the debugger library.
2411
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2412
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2413
		);
2414
2415
		// Don't activate SSO if they never completed activating WPCC.
2416
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2417
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2418
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2419
				$deprecated_modules['wpcc'] = null;
2420
			}
2421
		}
2422
2423
		foreach ( $deprecated_modules as $module => $replacement ) {
2424
			if ( Jetpack::is_module_active( $module ) ) {
2425
				self::deactivate_module( $module );
2426
				if ( $replacement ) {
2427
					$modules[] = $replacement;
2428
				}
2429
			}
2430
		}
2431
2432
		return array_unique( $modules );
2433
	}
2434
2435
	/**
2436
	 * Checks activated plugins during auto-activation to determine
2437
	 * if any of those plugins are in the list with a corresponding module
2438
	 * that is not compatible with the plugin. The module will not be allowed
2439
	 * to auto-activate.
2440
	 *
2441
	 * @since 2.6
2442
	 * @uses jetpack_get_default_modules filter
2443
	 * @param array $modules
2444
	 * @return array
2445
	 */
2446
	function filter_default_modules( $modules ) {
2447
2448
		$active_plugins = self::get_active_plugins();
2449
2450
		if ( ! empty( $active_plugins ) ) {
2451
2452
			// For each module we'd like to auto-activate...
2453
			foreach ( $modules as $key => $module ) {
2454
				// If there are potential conflicts for it...
2455
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2456
					// For each potential conflict...
2457
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2458
						// If that conflicting plugin is active...
2459
						if ( in_array( $plugin, $active_plugins ) ) {
2460
							// Remove that item from being auto-activated.
2461
							unset( $modules[ $key ] );
2462
						}
2463
					}
2464
				}
2465
			}
2466
		}
2467
2468
		return $modules;
2469
	}
2470
2471
	/**
2472
	 * Extract a module's slug from its full path.
2473
	 */
2474
	public static function get_module_slug( $file ) {
2475
		return str_replace( '.php', '', basename( $file ) );
2476
	}
2477
2478
	/**
2479
	 * Generate a module's path from its slug.
2480
	 */
2481
	public static function get_module_path( $slug ) {
2482
		/**
2483
		 * Filters the path of a modules.
2484
		 *
2485
		 * @since 7.4.0
2486
		 *
2487
		 * @param array $return The absolute path to a module's root php file
2488
		 * @param string $slug The module slug
2489
		 */
2490
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2491
	}
2492
2493
	/**
2494
	 * Load module data from module file. Headers differ from WordPress
2495
	 * plugin headers to avoid them being identified as standalone
2496
	 * plugins on the WordPress plugins page.
2497
	 */
2498
	public static function get_module( $module ) {
2499
		$headers = array(
2500
			'name'                      => 'Module Name',
2501
			'description'               => 'Module Description',
2502
			'sort'                      => 'Sort Order',
2503
			'recommendation_order'      => 'Recommendation Order',
2504
			'introduced'                => 'First Introduced',
2505
			'changed'                   => 'Major Changes In',
2506
			'deactivate'                => 'Deactivate',
2507
			'free'                      => 'Free',
2508
			'requires_connection'       => 'Requires Connection',
2509
			'auto_activate'             => 'Auto Activate',
2510
			'module_tags'               => 'Module Tags',
2511
			'feature'                   => 'Feature',
2512
			'additional_search_queries' => 'Additional Search Queries',
2513
			'plan_classes'              => 'Plans',
2514
		);
2515
2516
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2517
2518
		$mod = Jetpack::get_file_data( $file, $headers );
2519
		if ( empty( $mod['name'] ) ) {
2520
			return false;
2521
		}
2522
2523
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2524
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2525
		$mod['deactivate']              = empty( $mod['deactivate'] );
2526
		$mod['free']                    = empty( $mod['free'] );
2527
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2528
2529
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2530
			$mod['auto_activate'] = 'No';
2531
		} else {
2532
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2533
		}
2534
2535
		if ( $mod['module_tags'] ) {
2536
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2537
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2538
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2539
		} else {
2540
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2541
		}
2542
2543 View Code Duplication
		if ( $mod['plan_classes'] ) {
2544
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2545
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2546
		} else {
2547
			$mod['plan_classes'] = array( 'free' );
2548
		}
2549
2550 View Code Duplication
		if ( $mod['feature'] ) {
2551
			$mod['feature'] = explode( ',', $mod['feature'] );
2552
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2553
		} else {
2554
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2555
		}
2556
2557
		/**
2558
		 * Filters the feature array on a module.
2559
		 *
2560
		 * This filter allows you to control where each module is filtered: Recommended,
2561
		 * and the default "Other" listing.
2562
		 *
2563
		 * @since 3.5.0
2564
		 *
2565
		 * @param array   $mod['feature'] The areas to feature this module:
2566
		 *     'Recommended' shows on the main Jetpack admin screen.
2567
		 *     'Other' should be the default if no other value is in the array.
2568
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2569
		 * @param array   $mod All the currently assembled module data.
2570
		 */
2571
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2572
2573
		/**
2574
		 * Filter the returned data about a module.
2575
		 *
2576
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2577
		 * so please be careful.
2578
		 *
2579
		 * @since 3.6.0
2580
		 *
2581
		 * @param array   $mod    The details of the requested module.
2582
		 * @param string  $module The slug of the module, e.g. sharedaddy
2583
		 * @param string  $file   The path to the module source file.
2584
		 */
2585
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2586
	}
2587
2588
	/**
2589
	 * Like core's get_file_data implementation, but caches the result.
2590
	 */
2591
	public static function get_file_data( $file, $headers ) {
2592
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2593
		$file_name = basename( $file );
2594
2595
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2596
2597
		$file_data_option = get_transient( $cache_key );
2598
2599
		if ( false === $file_data_option ) {
2600
			$file_data_option = array();
2601
		}
2602
2603
		$key           = md5( $file_name . serialize( $headers ) );
2604
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2605
2606
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2607
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2608
			return $file_data_option[ $key ];
2609
		}
2610
2611
		$data = get_file_data( $file, $headers );
2612
2613
		$file_data_option[ $key ] = $data;
2614
2615
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2616
2617
		return $data;
2618
	}
2619
2620
2621
	/**
2622
	 * Return translated module tag.
2623
	 *
2624
	 * @param string $tag Tag as it appears in each module heading.
2625
	 *
2626
	 * @return mixed
2627
	 */
2628
	public static function translate_module_tag( $tag ) {
2629
		return jetpack_get_module_i18n_tag( $tag );
2630
	}
2631
2632
	/**
2633
	 * Get i18n strings as a JSON-encoded string
2634
	 *
2635
	 * @return string The locale as JSON
2636
	 */
2637
	public static function get_i18n_data_json() {
2638
2639
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2640
		// JSON files with the file they should be included for. This is an md5
2641
		// of '_inc/build/admin.js'.
2642
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2643
2644
		$i18n_json =
2645
				   JETPACK__PLUGIN_DIR
2646
				   . 'languages/json/jetpack-'
2647
				   . get_user_locale()
2648
				   . '-'
2649
				   . $path_md5
2650
				   . '.json';
2651
2652
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2653
			$locale_data = @file_get_contents( $i18n_json );
2654
			if ( $locale_data ) {
2655
				return $locale_data;
2656
			}
2657
		}
2658
2659
		// Return valid empty Jed locale
2660
		return '{ "locale_data": { "messages": { "": {} } } }';
2661
	}
2662
2663
	/**
2664
	 * Add locale data setup to wp-i18n
2665
	 *
2666
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2667
	 *
2668
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2669
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2670
	 *
2671
	 * This method provides a safe way to request the setup multiple times but add the script at
2672
	 * most once.
2673
	 *
2674
	 * @since 6.7.0
2675
	 *
2676
	 * @return void
2677
	 */
2678
	public static function setup_wp_i18n_locale_data() {
2679
		static $script_added = false;
2680
		if ( ! $script_added ) {
2681
			$script_added = true;
2682
			wp_add_inline_script(
2683
				'wp-i18n',
2684
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2685
			);
2686
		}
2687
	}
2688
2689
	/**
2690
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2691
	 *
2692
	 * @since 3.9.2
2693
	 *
2694
	 * @param array $modules
2695
	 *
2696
	 * @return string|void
2697
	 */
2698
	public static function get_translated_modules( $modules ) {
2699
		foreach ( $modules as $index => $module ) {
2700
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2701
			if ( isset( $module['name'] ) ) {
2702
				$modules[ $index ]['name'] = $i18n_module['name'];
2703
			}
2704
			if ( isset( $module['description'] ) ) {
2705
				$modules[ $index ]['description'] = $i18n_module['description'];
2706
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2707
			}
2708
		}
2709
		return $modules;
2710
	}
2711
2712
	/**
2713
	 * Get a list of activated modules as an array of module slugs.
2714
	 */
2715
	public static function get_active_modules() {
2716
		$active = Jetpack_Options::get_option( 'active_modules' );
2717
2718
		if ( ! is_array( $active ) ) {
2719
			$active = array();
2720
		}
2721
2722
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2723
			$active[] = 'vaultpress';
2724
		} else {
2725
			$active = array_diff( $active, array( 'vaultpress' ) );
2726
		}
2727
2728
		//If protect is active on the main site of a multisite, it should be active on all sites.
2729
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2730
			$active[] = 'protect';
2731
		}
2732
2733
		/**
2734
		 * Allow filtering of the active modules.
2735
		 *
2736
		 * Gives theme and plugin developers the power to alter the modules that
2737
		 * are activated on the fly.
2738
		 *
2739
		 * @since 5.8.0
2740
		 *
2741
		 * @param array $active Array of active module slugs.
2742
		 */
2743
		$active = apply_filters( 'jetpack_active_modules', $active );
2744
2745
		return array_unique( $active );
2746
	}
2747
2748
	/**
2749
	 * Check whether or not a Jetpack module is active.
2750
	 *
2751
	 * @param string $module The slug of a Jetpack module.
2752
	 * @return bool
2753
	 *
2754
	 * @static
2755
	 */
2756
	public static function is_module_active( $module ) {
2757
		return in_array( $module, self::get_active_modules() );
2758
	}
2759
2760
	public static function is_module( $module ) {
2761
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2762
	}
2763
2764
	/**
2765
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2766
	 *
2767
	 * @param bool $catch True to start catching, False to stop.
2768
	 *
2769
	 * @static
2770
	 */
2771
	public static function catch_errors( $catch ) {
2772
		static $display_errors, $error_reporting;
2773
2774
		if ( $catch ) {
2775
			$display_errors  = @ini_set( 'display_errors', 1 );
2776
			$error_reporting = @error_reporting( E_ALL );
2777
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2778
		} else {
2779
			@ini_set( 'display_errors', $display_errors );
2780
			@error_reporting( $error_reporting );
2781
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2782
		}
2783
	}
2784
2785
	/**
2786
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2787
	 */
2788
	public static function catch_errors_on_shutdown() {
2789
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2790
	}
2791
2792
	/**
2793
	 * Rewrite any string to make paths easier to read.
2794
	 *
2795
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2796
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2797
	 *
2798
	 * @param $string
2799
	 * @return mixed
2800
	 */
2801
	public static function alias_directories( $string ) {
2802
		// ABSPATH has a trailing slash.
2803
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2804
		// WP_CONTENT_DIR does not have a trailing slash.
2805
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2806
2807
		return $string;
2808
	}
2809
2810
	public static function activate_default_modules(
2811
		$min_version = false,
2812
		$max_version = false,
2813
		$other_modules = array(),
2814
		$redirect = true,
2815
		$send_state_messages = true
2816
	) {
2817
		$jetpack = Jetpack::init();
2818
2819
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2820
		$modules = array_merge( $other_modules, $modules );
2821
2822
		// Look for standalone plugins and disable if active.
2823
2824
		$to_deactivate = array();
2825
		foreach ( $modules as $module ) {
2826
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2827
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2828
			}
2829
		}
2830
2831
		$deactivated = array();
2832
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2833
			list( $probable_file, $probable_title ) = $deactivate_me;
2834
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2835
				$deactivated[] = $module;
2836
			}
2837
		}
2838
2839
		if ( $deactivated && $redirect ) {
2840
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2841
2842
			$url = add_query_arg(
2843
				array(
2844
					'action'   => 'activate_default_modules',
2845
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2846
				),
2847
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2848
			);
2849
			wp_safe_redirect( $url );
2850
			exit;
2851
		}
2852
2853
		/**
2854
		 * Fires before default modules are activated.
2855
		 *
2856
		 * @since 1.9.0
2857
		 *
2858
		 * @param string $min_version Minimum version number required to use modules.
2859
		 * @param string $max_version Maximum version number required to use modules.
2860
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2861
		 */
2862
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2863
2864
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2865
		if ( $send_state_messages ) {
2866
			Jetpack::restate();
2867
			Jetpack::catch_errors( true );
2868
		}
2869
2870
		$active = Jetpack::get_active_modules();
2871
2872
		foreach ( $modules as $module ) {
2873
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2874
				$active[] = $module;
2875
				self::update_active_modules( $active );
2876
				continue;
2877
			}
2878
2879
			if ( $send_state_messages && in_array( $module, $active ) ) {
2880
				$module_info = Jetpack::get_module( $module );
2881 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2882
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2883
					if ( $active_state = Jetpack::state( $state ) ) {
2884
						$active_state = explode( ',', $active_state );
2885
					} else {
2886
						$active_state = array();
2887
					}
2888
					$active_state[] = $module;
2889
					Jetpack::state( $state, implode( ',', $active_state ) );
2890
				}
2891
				continue;
2892
			}
2893
2894
			$file = Jetpack::get_module_path( $module );
2895
			if ( ! file_exists( $file ) ) {
2896
				continue;
2897
			}
2898
2899
			// we'll override this later if the plugin can be included without fatal error
2900
			if ( $redirect ) {
2901
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2902
			}
2903
2904
			if ( $send_state_messages ) {
2905
				Jetpack::state( 'error', 'module_activation_failed' );
2906
				Jetpack::state( 'module', $module );
2907
			}
2908
2909
			ob_start();
2910
			require_once $file;
2911
2912
			$active[] = $module;
2913
2914 View Code Duplication
			if ( $send_state_messages ) {
2915
2916
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2917
				if ( $active_state = Jetpack::state( $state ) ) {
2918
					$active_state = explode( ',', $active_state );
2919
				} else {
2920
					$active_state = array();
2921
				}
2922
				$active_state[] = $module;
2923
				Jetpack::state( $state, implode( ',', $active_state ) );
2924
			}
2925
2926
			Jetpack::update_active_modules( $active );
2927
2928
			ob_end_clean();
2929
		}
2930
2931
		if ( $send_state_messages ) {
2932
			Jetpack::state( 'error', false );
2933
			Jetpack::state( 'module', false );
2934
		}
2935
2936
		Jetpack::catch_errors( false );
2937
		/**
2938
		 * Fires when default modules are activated.
2939
		 *
2940
		 * @since 1.9.0
2941
		 *
2942
		 * @param string $min_version Minimum version number required to use modules.
2943
		 * @param string $max_version Maximum version number required to use modules.
2944
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2945
		 */
2946
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2947
	}
2948
2949
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2950
		/**
2951
		 * Fires before a module is activated.
2952
		 *
2953
		 * @since 2.6.0
2954
		 *
2955
		 * @param string $module Module slug.
2956
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2957
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2958
		 */
2959
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2960
2961
		$jetpack = Jetpack::init();
2962
2963
		if ( ! strlen( $module ) )
2964
			return false;
2965
2966
		if ( ! Jetpack::is_module( $module ) )
2967
			return false;
2968
2969
		// If it's already active, then don't do it again
2970
		$active = Jetpack::get_active_modules();
2971
		foreach ( $active as $act ) {
2972
			if ( $act == $module )
2973
				return true;
2974
		}
2975
2976
		$module_data = Jetpack::get_module( $module );
2977
2978
		if ( ! Jetpack::is_active() ) {
2979
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2980
				return false;
2981
2982
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2983
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2984
				return false;
2985
		}
2986
2987
		// Check and see if the old plugin is active
2988
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2989
			// Deactivate the old plugin
2990
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2991
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2992
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2993
				Jetpack::state( 'deactivated_plugins', $module );
2994
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2995
				exit;
2996
			}
2997
		}
2998
2999
		// Protect won't work with mis-configured IPs
3000
		if ( 'protect' === $module ) {
3001
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3002
			if ( ! jetpack_protect_get_ip() ) {
3003
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3004
				return false;
3005
			}
3006
		}
3007
3008
		if ( ! Jetpack_Plan::supports( $module ) ) {
3009
			return false;
3010
		}
3011
3012
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3013
		Jetpack::state( 'module', $module );
3014
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3015
3016
		Jetpack::catch_errors( true );
3017
		ob_start();
3018
		require Jetpack::get_module_path( $module );
3019
		/** This action is documented in class.jetpack.php */
3020
		do_action( 'jetpack_activate_module', $module );
3021
		$active[] = $module;
3022
		Jetpack::update_active_modules( $active );
3023
3024
		Jetpack::state( 'error', false ); // the override
3025
		ob_end_clean();
3026
		Jetpack::catch_errors( false );
3027
3028
		if ( $redirect ) {
3029
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3030
		}
3031
		if ( $exit ) {
3032
			exit;
3033
		}
3034
		return true;
3035
	}
3036
3037
	function activate_module_actions( $module ) {
3038
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3039
	}
3040
3041
	public static function deactivate_module( $module ) {
3042
		/**
3043
		 * Fires when a module is deactivated.
3044
		 *
3045
		 * @since 1.9.0
3046
		 *
3047
		 * @param string $module Module slug.
3048
		 */
3049
		do_action( 'jetpack_pre_deactivate_module', $module );
3050
3051
		$jetpack = Jetpack::init();
3052
3053
		$active = Jetpack::get_active_modules();
3054
		$new    = array_filter( array_diff( $active, (array) $module ) );
3055
3056
		return self::update_active_modules( $new );
3057
	}
3058
3059
	public static function enable_module_configurable( $module ) {
3060
		$module = Jetpack::get_module_slug( $module );
3061
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3062
	}
3063
3064
	/**
3065
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3066
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3067
	 *
3068
	 * @param string $module Module slug
3069
	 * @return string $url module configuration URL
3070
	 */
3071
	public static function module_configuration_url( $module ) {
3072
		$module = Jetpack::get_module_slug( $module );
3073
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3074
		/**
3075
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3076
		 *
3077
		 * @since 6.9.0
3078
		 *
3079
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3080
		 */
3081
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3082
3083
		return $url;
3084
	}
3085
3086
/* Installation */
3087
	public static function bail_on_activation( $message, $deactivate = true ) {
3088
?>
3089
<!doctype html>
3090
<html>
3091
<head>
3092
<meta charset="<?php bloginfo( 'charset' ); ?>">
3093
<style>
3094
* {
3095
	text-align: center;
3096
	margin: 0;
3097
	padding: 0;
3098
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3099
}
3100
p {
3101
	margin-top: 1em;
3102
	font-size: 18px;
3103
}
3104
</style>
3105
<body>
3106
<p><?php echo esc_html( $message ); ?></p>
3107
</body>
3108
</html>
3109
<?php
3110
		if ( $deactivate ) {
3111
			$plugins = get_option( 'active_plugins' );
3112
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3113
			$update  = false;
3114
			foreach ( $plugins as $i => $plugin ) {
3115
				if ( $plugin === $jetpack ) {
3116
					$plugins[$i] = false;
3117
					$update = true;
3118
				}
3119
			}
3120
3121
			if ( $update ) {
3122
				update_option( 'active_plugins', array_filter( $plugins ) );
3123
			}
3124
		}
3125
		exit;
3126
	}
3127
3128
	/**
3129
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3130
	 * @static
3131
	 */
3132
	public static function plugin_activation( $network_wide ) {
3133
		Jetpack_Options::update_option( 'activated', 1 );
3134
3135
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3136
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3137
		}
3138
3139
		if ( $network_wide )
3140
			Jetpack::state( 'network_nag', true );
3141
3142
		// For firing one-off events (notices) immediately after activation
3143
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3144
3145
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3146
3147
		Jetpack::plugin_initialize();
3148
	}
3149
3150
	public static function get_activation_source( $referer_url ) {
3151
3152
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3153
			return array( 'wp-cli', null );
3154
		}
3155
3156
		$referer = parse_url( $referer_url );
3157
3158
		$source_type = 'unknown';
3159
		$source_query = null;
3160
3161
		if ( ! is_array( $referer ) ) {
3162
			return array( $source_type, $source_query );
3163
		}
3164
3165
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3166
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3167
3168
		if ( isset( $referer['query'] ) ) {
3169
			parse_str( $referer['query'], $query_parts );
3170
		} else {
3171
			$query_parts = array();
3172
		}
3173
3174
		if ( $plugins_path === $referer['path'] ) {
3175
			$source_type = 'list';
3176
		} elseif ( $plugins_install_path === $referer['path'] ) {
3177
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3178
			switch( $tab ) {
3179
				case 'popular':
3180
					$source_type = 'popular';
3181
					break;
3182
				case 'recommended':
3183
					$source_type = 'recommended';
3184
					break;
3185
				case 'favorites':
3186
					$source_type = 'favorites';
3187
					break;
3188
				case 'search':
3189
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3190
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3191
					break;
3192
				default:
3193
					$source_type = 'featured';
3194
			}
3195
		}
3196
3197
		return array( $source_type, $source_query );
3198
	}
3199
3200
	/**
3201
	 * Runs before bumping version numbers up to a new version
3202
	 * @param  string $version    Version:timestamp
3203
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3204
	 * @return null              [description]
3205
	 */
3206
	public static function do_version_bump( $version, $old_version ) {
3207
		if ( ! $old_version ) { // For new sites
3208
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3209
		}
3210
	}
3211
3212
	/**
3213
	 * Sets the internal version number and activation state.
3214
	 * @static
3215
	 */
3216
	public static function plugin_initialize() {
3217
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3218
			Jetpack_Options::update_option( 'activated', 2 );
3219
		}
3220
3221 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3222
			$version = $old_version = JETPACK__VERSION . ':' . time();
3223
			/** This action is documented in class.jetpack.php */
3224
			do_action( 'updating_jetpack_version', $version, false );
3225
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3226
		}
3227
3228
		Jetpack::load_modules();
3229
3230
		Jetpack_Options::delete_option( 'do_activate' );
3231
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3232
	}
3233
3234
	/**
3235
	 * Removes all connection options
3236
	 * @static
3237
	 */
3238
	public static function plugin_deactivation( ) {
3239
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3240
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3241
			Jetpack_Network::init()->deactivate();
3242
		} else {
3243
			Jetpack::disconnect( false );
3244
			//Jetpack_Heartbeat::init()->deactivate();
3245
		}
3246
	}
3247
3248
	/**
3249
	 * Disconnects from the Jetpack servers.
3250
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3251
	 * @static
3252
	 */
3253
	public static function disconnect( $update_activated_state = true ) {
3254
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3255
		Jetpack::clean_nonces( true );
3256
3257
		// If the site is in an IDC because sync is not allowed,
3258
		// let's make sure to not disconnect the production site.
3259
		if ( ! self::validate_sync_error_idc_option() ) {
3260
			$tracking = new Tracking();
3261
			$tracking->record_user_event( 'disconnect_site', array() );
3262
			Jetpack::load_xml_rpc_client();
3263
			$xml = new Jetpack_IXR_Client();
3264
			$xml->query( 'jetpack.deregister' );
3265
		}
3266
3267
		Jetpack_Options::delete_option(
3268
			array(
3269
				'blog_token',
3270
				'user_token',
3271
				'user_tokens',
3272
				'master_user',
3273
				'time_diff',
3274
				'fallback_no_verify_ssl_certs',
3275
			)
3276
		);
3277
3278
		Jetpack_IDC::clear_all_idc_options();
3279
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3280
3281
		if ( $update_activated_state ) {
3282
			Jetpack_Options::update_option( 'activated', 4 );
3283
		}
3284
3285
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3286
			// Check then record unique disconnection if site has never been disconnected previously
3287
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3288
				$jetpack_unique_connection['disconnected'] = 1;
3289
			} else {
3290
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3291
					//track unique disconnect
3292
					$jetpack = Jetpack::init();
3293
3294
					$jetpack->stat( 'connections', 'unique-disconnect' );
3295
					$jetpack->do_stats( 'server_side' );
3296
				}
3297
				// increment number of times disconnected
3298
				$jetpack_unique_connection['disconnected'] += 1;
3299
			}
3300
3301
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3302
		}
3303
3304
		// Delete cached connected user data
3305
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3306
		delete_transient( $transient_key );
3307
3308
		// Delete all the sync related data. Since it could be taking up space.
3309
		Sender::get_instance()->uninstall();
3310
3311
		// Disable the Heartbeat cron
3312
		Jetpack_Heartbeat::init()->deactivate();
3313
	}
3314
3315
	/**
3316
	 * Unlinks the current user from the linked WordPress.com user
3317
	 */
3318
	public static function unlink_user( $user_id = null ) {
3319
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3320
			return false;
3321
3322
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3323
3324
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3325
			return false;
3326
3327
		if ( ! isset( $tokens[ $user_id ] ) )
3328
			return false;
3329
3330
		Jetpack::load_xml_rpc_client();
3331
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3332
		$xml->query( 'jetpack.unlink_user', $user_id );
3333
3334
		unset( $tokens[ $user_id ] );
3335
3336
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3337
3338
		/**
3339
		 * Fires after the current user has been unlinked from WordPress.com.
3340
		 *
3341
		 * @since 4.1.0
3342
		 *
3343
		 * @param int $user_id The current user's ID.
3344
		 */
3345
		do_action( 'jetpack_unlinked_user', $user_id );
3346
3347
		return true;
3348
	}
3349
3350
	/**
3351
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3352
	 */
3353
	public static function try_registration() {
3354
		// The user has agreed to the TOS at some point by now.
3355
		Jetpack_Options::update_option( 'tos_agreed', true );
3356
3357
		// Let's get some testing in beta versions and such.
3358
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3359
			// Before attempting to connect, let's make sure that the domains are viable.
3360
			$domains_to_check = array_unique( array(
3361
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3362
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3363
			) );
3364
			foreach ( $domains_to_check as $domain ) {
3365
				$result = self::connection()->is_usable_domain( $domain );
3366
				if ( is_wp_error( $result ) ) {
3367
					return $result;
3368
				}
3369
			}
3370
		}
3371
3372
		$result = Jetpack::register();
3373
3374
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3375
		if ( ! $result || is_wp_error( $result ) ) {
3376
			return $result;
3377
		} else {
3378
			return true;
3379
		}
3380
	}
3381
3382
	/**
3383
	 * Tracking an internal event log. Try not to put too much chaff in here.
3384
	 *
3385
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3386
	 */
3387
	public static function log( $code, $data = null ) {
3388
		// only grab the latest 200 entries
3389
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3390
3391
		// Append our event to the log
3392
		$log_entry = array(
3393
			'time'    => time(),
3394
			'user_id' => get_current_user_id(),
3395
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3396
			'code'    => $code,
3397
		);
3398
		// Don't bother storing it unless we've got some.
3399
		if ( ! is_null( $data ) ) {
3400
			$log_entry['data'] = $data;
3401
		}
3402
		$log[] = $log_entry;
3403
3404
		// Try add_option first, to make sure it's not autoloaded.
3405
		// @todo: Add an add_option method to Jetpack_Options
3406
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3407
			Jetpack_Options::update_option( 'log', $log );
3408
		}
3409
3410
		/**
3411
		 * Fires when Jetpack logs an internal event.
3412
		 *
3413
		 * @since 3.0.0
3414
		 *
3415
		 * @param array $log_entry {
3416
		 *	Array of details about the log entry.
3417
		 *
3418
		 *	@param string time Time of the event.
3419
		 *	@param int user_id ID of the user who trigerred the event.
3420
		 *	@param int blog_id Jetpack Blog ID.
3421
		 *	@param string code Unique name for the event.
3422
		 *	@param string data Data about the event.
3423
		 * }
3424
		 */
3425
		do_action( 'jetpack_log_entry', $log_entry );
3426
	}
3427
3428
	/**
3429
	 * Get the internal event log.
3430
	 *
3431
	 * @param $event (string) - only return the specific log events
3432
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3433
	 *
3434
	 * @return array of log events || WP_Error for invalid params
3435
	 */
3436
	public static function get_log( $event = false, $num = false ) {
3437
		if ( $event && ! is_string( $event ) ) {
3438
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3439
		}
3440
3441
		if ( $num && ! is_numeric( $num ) ) {
3442
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3443
		}
3444
3445
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3446
3447
		// If nothing set - act as it did before, otherwise let's start customizing the output
3448
		if ( ! $num && ! $event ) {
3449
			return $entire_log;
3450
		} else {
3451
			$entire_log = array_reverse( $entire_log );
3452
		}
3453
3454
		$custom_log_output = array();
3455
3456
		if ( $event ) {
3457
			foreach ( $entire_log as $log_event ) {
3458
				if ( $event == $log_event[ 'code' ] ) {
3459
					$custom_log_output[] = $log_event;
3460
				}
3461
			}
3462
		} else {
3463
			$custom_log_output = $entire_log;
3464
		}
3465
3466
		if ( $num ) {
3467
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3468
		}
3469
3470
		return $custom_log_output;
3471
	}
3472
3473
	/**
3474
	 * Log modification of important settings.
3475
	 */
3476
	public static function log_settings_change( $option, $old_value, $value ) {
3477
		switch( $option ) {
3478
			case 'jetpack_sync_non_public_post_stati':
3479
				self::log( $option, $value );
3480
				break;
3481
		}
3482
	}
3483
3484
	/**
3485
	 * Return stat data for WPCOM sync
3486
	 */
3487
	public static function get_stat_data( $encode = true, $extended = true ) {
3488
		$data = Jetpack_Heartbeat::generate_stats_array();
3489
3490
		if ( $extended ) {
3491
			$additional_data = self::get_additional_stat_data();
3492
			$data = array_merge( $data, $additional_data );
3493
		}
3494
3495
		if ( $encode ) {
3496
			return json_encode( $data );
3497
		}
3498
3499
		return $data;
3500
	}
3501
3502
	/**
3503
	 * Get additional stat data to sync to WPCOM
3504
	 */
3505
	public static function get_additional_stat_data( $prefix = '' ) {
3506
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3507
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3508
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3509
		$return["{$prefix}site-count"]     = 0;
3510
3511
		if ( function_exists( 'get_blog_count' ) ) {
3512
			$return["{$prefix}site-count"] = get_blog_count();
3513
		}
3514
		return $return;
3515
	}
3516
3517
	private static function get_site_user_count() {
3518
		global $wpdb;
3519
3520
		if ( function_exists( 'wp_is_large_network' ) ) {
3521
			if ( wp_is_large_network( 'users' ) ) {
3522
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3523
			}
3524
		}
3525
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3526
			// It wasn't there, so regenerate the data and save the transient
3527
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3528
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3529
		}
3530
		return $user_count;
3531
	}
3532
3533
	/* Admin Pages */
3534
3535
	function admin_init() {
3536
		// If the plugin is not connected, display a connect message.
3537
		if (
3538
			// the plugin was auto-activated and needs its candy
3539
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3540
		||
3541
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3542
			! Jetpack_Options::get_option( 'activated' )
3543
		) {
3544
			Jetpack::plugin_initialize();
3545
		}
3546
3547
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3548
			Jetpack_Connection_Banner::init();
3549
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3550
			// Upgrade: 1.1 -> 1.1.1
3551
			// Check and see if host can verify the Jetpack servers' SSL certificate
3552
			$args = array();
3553
			Client::_wp_remote_request(
3554
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3555
				$args,
3556
				true
3557
			);
3558
		}
3559
3560
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3561
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3562
		}
3563
3564
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3565
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3566
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3567
3568
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3569
			// Artificially throw errors in certain whitelisted cases during plugin activation
3570
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3571
		}
3572
3573
		// Add custom column in wp-admin/users.php to show whether user is linked.
3574
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3575
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3576
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3577
	}
3578
3579
	function admin_body_class( $admin_body_class = '' ) {
3580
		$classes = explode( ' ', trim( $admin_body_class ) );
3581
3582
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3583
3584
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3585
		return " $admin_body_class ";
3586
	}
3587
3588
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3589
		return $admin_body_class . ' jetpack-pagestyles ';
3590
	}
3591
3592
	/**
3593
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3594
	 * This function artificially throws errors for such cases (whitelisted).
3595
	 *
3596
	 * @param string $plugin The activated plugin.
3597
	 */
3598
	function throw_error_on_activate_plugin( $plugin ) {
3599
		$active_modules = Jetpack::get_active_modules();
3600
3601
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3602
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3603
			$throw = false;
3604
3605
			// Try and make sure it really was the stats plugin
3606
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3607
				if ( 'stats.php' == basename( $plugin ) ) {
3608
					$throw = true;
3609
				}
3610
			} else {
3611
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3612
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3613
					$throw = true;
3614
				}
3615
			}
3616
3617
			if ( $throw ) {
3618
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3619
			}
3620
		}
3621
	}
3622
3623
	function intercept_plugin_error_scrape_init() {
3624
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3625
	}
3626
3627
	function intercept_plugin_error_scrape( $action, $result ) {
3628
		if ( ! $result ) {
3629
			return;
3630
		}
3631
3632
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3633
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3634
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3635
			}
3636
		}
3637
	}
3638
3639
	function add_remote_request_handlers() {
3640
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3641
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3642
	}
3643
3644
	function remote_request_handlers() {
3645
		$action = current_filter();
3646
3647
		switch ( current_filter() ) {
3648
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3649
			$response = $this->upload_handler();
3650
			break;
3651
3652
		case 'wp_ajax_nopriv_jetpack_update_file' :
3653
			$response = $this->upload_handler( true );
3654
			break;
3655
		default :
3656
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3657
			break;
3658
		}
3659
3660
		if ( ! $response ) {
3661
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3662
		}
3663
3664
		if ( is_wp_error( $response ) ) {
3665
			$status_code       = $response->get_error_data();
3666
			$error             = $response->get_error_code();
3667
			$error_description = $response->get_error_message();
3668
3669
			if ( ! is_int( $status_code ) ) {
3670
				$status_code = 400;
3671
			}
3672
3673
			status_header( $status_code );
3674
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3675
		}
3676
3677
		status_header( 200 );
3678
		if ( true === $response ) {
3679
			exit;
3680
		}
3681
3682
		die( json_encode( (object) $response ) );
3683
	}
3684
3685
	/**
3686
	 * Uploads a file gotten from the global $_FILES.
3687
	 * If `$update_media_item` is true and `post_id` is defined
3688
	 * the attachment file of the media item (gotten through of the post_id)
3689
	 * will be updated instead of add a new one.
3690
	 *
3691
	 * @param  boolean $update_media_item - update media attachment
3692
	 * @return array - An array describing the uploadind files process
3693
	 */
3694
	function upload_handler( $update_media_item = false ) {
3695
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3696
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3697
		}
3698
3699
		$user = wp_authenticate( '', '' );
3700
		if ( ! $user || is_wp_error( $user ) ) {
3701
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3702
		}
3703
3704
		wp_set_current_user( $user->ID );
3705
3706
		if ( ! current_user_can( 'upload_files' ) ) {
3707
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3708
		}
3709
3710
		if ( empty( $_FILES ) ) {
3711
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3712
		}
3713
3714
		foreach ( array_keys( $_FILES ) as $files_key ) {
3715
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3716
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3717
			}
3718
		}
3719
3720
		$media_keys = array_keys( $_FILES['media'] );
3721
3722
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3723
		if ( ! $token || is_wp_error( $token ) ) {
3724
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3725
		}
3726
3727
		$uploaded_files = array();
3728
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3729
		unset( $GLOBALS['post'] );
3730
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3731
			$file = array();
3732
			foreach ( $media_keys as $media_key ) {
3733
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3734
			}
3735
3736
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3737
3738
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3739
			if ( $hmac_provided !== $hmac_file ) {
3740
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3741
				continue;
3742
			}
3743
3744
			$_FILES['.jetpack.upload.'] = $file;
3745
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3746
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3747
				$post_id = 0;
3748
			}
3749
3750
			if ( $update_media_item ) {
3751
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3752
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3753
				}
3754
3755
				$media_array = $_FILES['media'];
3756
3757
				$file_array['name'] = $media_array['name'][0];
3758
				$file_array['type'] = $media_array['type'][0];
3759
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3760
				$file_array['error'] = $media_array['error'][0];
3761
				$file_array['size'] = $media_array['size'][0];
3762
3763
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3764
3765
				if ( is_wp_error( $edited_media_item ) ) {
3766
					return $edited_media_item;
3767
				}
3768
3769
				$response = (object) array(
3770
					'id'   => (string) $post_id,
3771
					'file' => (string) $edited_media_item->post_title,
3772
					'url'  => (string) wp_get_attachment_url( $post_id ),
3773
					'type' => (string) $edited_media_item->post_mime_type,
3774
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3775
				);
3776
3777
				return (array) array( $response );
3778
			}
3779
3780
			$attachment_id = media_handle_upload(
3781
				'.jetpack.upload.',
3782
				$post_id,
3783
				array(),
3784
				array(
3785
					'action' => 'jetpack_upload_file',
3786
				)
3787
			);
3788
3789
			if ( ! $attachment_id ) {
3790
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3791
			} elseif ( is_wp_error( $attachment_id ) ) {
3792
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3793
			} else {
3794
				$attachment = get_post( $attachment_id );
3795
				$uploaded_files[$index] = (object) array(
3796
					'id'   => (string) $attachment_id,
3797
					'file' => $attachment->post_title,
3798
					'url'  => wp_get_attachment_url( $attachment_id ),
3799
					'type' => $attachment->post_mime_type,
3800
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3801
				);
3802
				// Zip files uploads are not supported unless they are done for installation purposed
3803
				// lets delete them in case something goes wrong in this whole process
3804
				if ( 'application/zip' === $attachment->post_mime_type ) {
3805
					// Schedule a cleanup for 2 hours from now in case of failed install.
3806
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3807
				}
3808
			}
3809
		}
3810
		if ( ! is_null( $global_post ) ) {
3811
			$GLOBALS['post'] = $global_post;
3812
		}
3813
3814
		return $uploaded_files;
3815
	}
3816
3817
	/**
3818
	 * Add help to the Jetpack page
3819
	 *
3820
	 * @since Jetpack (1.2.3)
3821
	 * @return false if not the Jetpack page
3822
	 */
3823
	function admin_help() {
3824
		$current_screen = get_current_screen();
3825
3826
		// Overview
3827
		$current_screen->add_help_tab(
3828
			array(
3829
				'id'		=> 'home',
3830
				'title'		=> __( 'Home', 'jetpack' ),
3831
				'content'	=>
3832
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3833
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3834
					'<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>',
3835
			)
3836
		);
3837
3838
		// Screen Content
3839
		if ( current_user_can( 'manage_options' ) ) {
3840
			$current_screen->add_help_tab(
3841
				array(
3842
					'id'		=> 'settings',
3843
					'title'		=> __( 'Settings', 'jetpack' ),
3844
					'content'	=>
3845
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3846
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3847
						'<ol>' .
3848
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3849
							'<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>' .
3850
						'</ol>' .
3851
						'<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>'
3852
				)
3853
			);
3854
		}
3855
3856
		// Help Sidebar
3857
		$current_screen->set_help_sidebar(
3858
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3859
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3860
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3861
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3862
		);
3863
	}
3864
3865
	function admin_menu_css() {
3866
		wp_enqueue_style( 'jetpack-icons' );
3867
	}
3868
3869
	function admin_menu_order() {
3870
		return true;
3871
	}
3872
3873 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3874
		$jp_menu_order = array();
3875
3876
		foreach ( $menu_order as $index => $item ) {
3877
			if ( $item != 'jetpack' ) {
3878
				$jp_menu_order[] = $item;
3879
			}
3880
3881
			if ( $index == 0 ) {
3882
				$jp_menu_order[] = 'jetpack';
3883
			}
3884
		}
3885
3886
		return $jp_menu_order;
3887
	}
3888
3889
	function admin_banner_styles() {
3890
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3891
3892
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3893
			wp_register_style(
3894
				'jetpack-dops-style',
3895
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3896
				array(),
3897
				JETPACK__VERSION
3898
			);
3899
		}
3900
3901
		wp_enqueue_style(
3902
			'jetpack',
3903
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3904
			array( 'jetpack-dops-style' ),
3905
			 JETPACK__VERSION . '-20121016'
3906
		);
3907
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3908
		wp_style_add_data( 'jetpack', 'suffix', $min );
3909
	}
3910
3911
	function plugin_action_links( $actions ) {
3912
3913
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3914
3915
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3916
			return array_merge(
3917
				$jetpack_home,
3918
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3919
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3920
				$actions
3921
				);
3922
			}
3923
3924
		return array_merge( $jetpack_home, $actions );
3925
	}
3926
3927
	/*
3928
	 * Registration flow:
3929
	 * 1 - ::admin_page_load() action=register
3930
	 * 2 - ::try_registration()
3931
	 * 3 - ::register()
3932
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3933
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3934
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3935
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3936
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3937
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3938
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3939
	 *       jetpack_id, jetpack_secret, jetpack_public
3940
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3941
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3942
	 * 5 - user logs in with WP.com account
3943
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3944
	 *		- Jetpack_Client_Server::authorize()
3945
	 *		- Jetpack_Client_Server::get_token()
3946
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3947
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3948
	 *			- which responds with access_token, token_type, scope
3949
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3950
	 *		- Jetpack::activate_default_modules()
3951
	 *     		- Deactivates deprecated plugins
3952
	 *     		- Activates all default modules
3953
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3954
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3955
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3956
	 *     Done!
3957
	 */
3958
3959
	/**
3960
	 * Handles the page load events for the Jetpack admin page
3961
	 */
3962
	function admin_page_load() {
3963
		$error = false;
3964
3965
		// Make sure we have the right body class to hook stylings for subpages off of.
3966
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3967
3968
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3969
			// Should only be used in intermediate redirects to preserve state across redirects
3970
			Jetpack::restate();
3971
		}
3972
3973
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3974
			// @todo: Add validation against a known whitelist
3975
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3976
			// User clicked in the iframe to link their accounts
3977
			if ( ! Jetpack::is_user_connected() ) {
3978
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3979
3980
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3981
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3982
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3983
3984
				if ( isset( $_GET['notes_iframe'] ) )
3985
					$connect_url .= '&notes_iframe';
3986
				wp_redirect( $connect_url );
3987
				exit;
3988
			} else {
3989
				if ( ! isset( $_GET['calypso_env'] ) ) {
3990
					Jetpack::state( 'message', 'already_authorized' );
3991
					wp_safe_redirect( Jetpack::admin_url() );
3992
					exit;
3993
				} else {
3994
					$connect_url = $this->build_connect_url( true, false, $from );
3995
					$connect_url .= '&already_authorized=true';
3996
					wp_redirect( $connect_url );
3997
					exit;
3998
				}
3999
			}
4000
		}
4001
4002
4003
		if ( isset( $_GET['action'] ) ) {
4004
			switch ( $_GET['action'] ) {
4005
			case 'authorize':
4006
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4007
					Jetpack::state( 'message', 'already_authorized' );
4008
					wp_safe_redirect( Jetpack::admin_url() );
4009
					exit;
4010
				}
4011
				Jetpack::log( 'authorize' );
4012
				$client_server = new Jetpack_Client_Server;
4013
				$client_server->client_authorize();
4014
				exit;
4015
			case 'register' :
4016
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4017
					$error = 'cheatin';
4018
					break;
4019
				}
4020
				check_admin_referer( 'jetpack-register' );
4021
				Jetpack::log( 'register' );
4022
				Jetpack::maybe_set_version_option();
4023
				$registered = Jetpack::try_registration();
4024
				if ( is_wp_error( $registered ) ) {
4025
					$error = $registered->get_error_code();
4026
					Jetpack::state( 'error', $error );
4027
					Jetpack::state( 'error', $registered->get_error_message() );
4028
4029
					/**
4030
					 * Jetpack registration Error.
4031
					 *
4032
					 * @since 7.5.0
4033
					 *
4034
					 * @param string|int $error The error code.
4035
					 * @param \WP_Error $registered The error object.
4036
					 */
4037
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4038
					break;
4039
				}
4040
4041
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4042
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4043
4044
				/**
4045
				 * Jetpack registration Success.
4046
				 *
4047
				 * @since 7.5.0
4048
				 *
4049
				 * @param string $from 'from' GET parameter;
4050
				 */
4051
				do_action( 'jetpack_connection_register_success', $from );
4052
4053
				$url = $this->build_connect_url( true, $redirect, $from );
4054
4055
				if ( ! empty( $_GET['onboarding'] ) ) {
4056
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4057
				}
4058
4059
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4060
					$url = add_query_arg( 'auth_approved', 'true', $url );
4061
				}
4062
4063
				wp_redirect( $url );
4064
				exit;
4065
			case 'activate' :
4066
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4067
					$error = 'cheatin';
4068
					break;
4069
				}
4070
4071
				$module = stripslashes( $_GET['module'] );
4072
				check_admin_referer( "jetpack_activate-$module" );
4073
				Jetpack::log( 'activate', $module );
4074
				if ( ! Jetpack::activate_module( $module ) ) {
4075
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4076
				}
4077
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4078
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4079
				exit;
4080
			case 'activate_default_modules' :
4081
				check_admin_referer( 'activate_default_modules' );
4082
				Jetpack::log( 'activate_default_modules' );
4083
				Jetpack::restate();
4084
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4085
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4086
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4087
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4088
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4089
				exit;
4090
			case 'disconnect' :
4091
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4092
					$error = 'cheatin';
4093
					break;
4094
				}
4095
4096
				check_admin_referer( 'jetpack-disconnect' );
4097
				Jetpack::log( 'disconnect' );
4098
				Jetpack::disconnect();
4099
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4100
				exit;
4101
			case 'reconnect' :
4102
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4103
					$error = 'cheatin';
4104
					break;
4105
				}
4106
4107
				check_admin_referer( 'jetpack-reconnect' );
4108
				Jetpack::log( 'reconnect' );
4109
				$this->disconnect();
4110
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4111
				exit;
4112 View Code Duplication
			case 'deactivate' :
4113
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4114
					$error = 'cheatin';
4115
					break;
4116
				}
4117
4118
				$modules = stripslashes( $_GET['module'] );
4119
				check_admin_referer( "jetpack_deactivate-$modules" );
4120
				foreach ( explode( ',', $modules ) as $module ) {
4121
					Jetpack::log( 'deactivate', $module );
4122
					Jetpack::deactivate_module( $module );
4123
					Jetpack::state( 'message', 'module_deactivated' );
4124
				}
4125
				Jetpack::state( 'module', $modules );
4126
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4127
				exit;
4128
			case 'unlink' :
4129
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4130
				check_admin_referer( 'jetpack-unlink' );
4131
				Jetpack::log( 'unlink' );
4132
				$this->unlink_user();
4133
				Jetpack::state( 'message', 'unlinked' );
4134
				if ( 'sub-unlink' == $redirect ) {
4135
					wp_safe_redirect( admin_url() );
4136
				} else {
4137
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4138
				}
4139
				exit;
4140
			case 'onboard' :
4141
				if ( ! current_user_can( 'manage_options' ) ) {
4142
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4143
				} else {
4144
					Jetpack::create_onboarding_token();
4145
					$url = $this->build_connect_url( true );
4146
4147
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4148
						$url = add_query_arg( 'onboarding', $token, $url );
4149
					}
4150
4151
					$calypso_env = $this->get_calypso_env();
4152
					if ( ! empty( $calypso_env ) ) {
4153
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4154
					}
4155
4156
					wp_redirect( $url );
4157
					exit;
4158
				}
4159
				exit;
4160
			default:
4161
				/**
4162
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4163
				 *
4164
				 * @since 2.6.0
4165
				 *
4166
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4167
				 */
4168
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4169
			}
4170
		}
4171
4172
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4173
			self::activate_new_modules( true );
4174
		}
4175
4176
		$message_code = Jetpack::state( 'message' );
4177
		if ( Jetpack::state( 'optin-manage' ) ) {
4178
			$activated_manage = $message_code;
4179
			$message_code = 'jetpack-manage';
4180
		}
4181
4182
		switch ( $message_code ) {
4183
		case 'jetpack-manage':
4184
			$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>';
4185
			if ( $activated_manage ) {
4186
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4187
			}
4188
			break;
4189
4190
		}
4191
4192
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4193
4194
		if ( ! empty( $deactivated_plugins ) ) {
4195
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4196
			$deactivated_titles  = array();
4197
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4198
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4199
					continue;
4200
				}
4201
4202
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4203
			}
4204
4205
			if ( $deactivated_titles ) {
4206
				if ( $this->message ) {
4207
					$this->message .= "<br /><br />\n";
4208
				}
4209
4210
				$this->message .= wp_sprintf(
4211
					_n(
4212
						'Jetpack contains the most recent version of the old %l plugin.',
4213
						'Jetpack contains the most recent versions of the old %l plugins.',
4214
						count( $deactivated_titles ),
4215
						'jetpack'
4216
					),
4217
					$deactivated_titles
4218
				);
4219
4220
				$this->message .= "<br />\n";
4221
4222
				$this->message .= _n(
4223
					'The old version has been deactivated and can be removed from your site.',
4224
					'The old versions have been deactivated and can be removed from your site.',
4225
					count( $deactivated_titles ),
4226
					'jetpack'
4227
				);
4228
			}
4229
		}
4230
4231
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4232
4233
		if ( $this->message || $this->error || $this->privacy_checks ) {
4234
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4235
		}
4236
4237
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4238
	}
4239
4240
	function admin_notices() {
4241
4242
		if ( $this->error ) {
4243
?>
4244
<div id="message" class="jetpack-message jetpack-err">
4245
	<div class="squeezer">
4246
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4247
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4248
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4249
<?php	endif; ?>
4250
	</div>
4251
</div>
4252
<?php
4253
		}
4254
4255
		if ( $this->message ) {
4256
?>
4257
<div id="message" class="jetpack-message">
4258
	<div class="squeezer">
4259
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4260
	</div>
4261
</div>
4262
<?php
4263
		}
4264
4265
		if ( $this->privacy_checks ) :
4266
			$module_names = $module_slugs = array();
4267
4268
			$privacy_checks = explode( ',', $this->privacy_checks );
4269
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4270
			foreach ( $privacy_checks as $module_slug ) {
4271
				$module = Jetpack::get_module( $module_slug );
4272
				if ( ! $module ) {
4273
					continue;
4274
				}
4275
4276
				$module_slugs[] = $module_slug;
4277
				$module_names[] = "<strong>{$module['name']}</strong>";
4278
			}
4279
4280
			$module_slugs = join( ',', $module_slugs );
4281
?>
4282
<div id="message" class="jetpack-message jetpack-err">
4283
	<div class="squeezer">
4284
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4285
		<p><?php
4286
			echo wp_kses(
4287
				wptexturize(
4288
					wp_sprintf(
4289
						_nx(
4290
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4291
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4292
							count( $privacy_checks ),
4293
							'%l = list of Jetpack module/feature names',
4294
							'jetpack'
4295
						),
4296
						$module_names
4297
					)
4298
				),
4299
				array( 'strong' => true )
4300
			);
4301
4302
			echo "\n<br />\n";
4303
4304
			echo wp_kses(
4305
				sprintf(
4306
					_nx(
4307
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4308
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4309
						count( $privacy_checks ),
4310
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4311
						'jetpack'
4312
					),
4313
					wp_nonce_url(
4314
						Jetpack::admin_url(
4315
							array(
4316
								'page'   => 'jetpack',
4317
								'action' => 'deactivate',
4318
								'module' => urlencode( $module_slugs ),
4319
							)
4320
						),
4321
						"jetpack_deactivate-$module_slugs"
4322
					),
4323
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4324
				),
4325
				array( 'a' => array( 'href' => true, 'title' => true ) )
4326
			);
4327
		?></p>
4328
	</div>
4329
</div>
4330
<?php endif;
4331
	}
4332
4333
	/**
4334
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4335
	 */
4336
	function stat( $group, $detail ) {
4337
		if ( ! isset( $this->stats[ $group ] ) )
4338
			$this->stats[ $group ] = array();
4339
		$this->stats[ $group ][] = $detail;
4340
	}
4341
4342
	/**
4343
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4344
	 */
4345
	function do_stats( $method = '' ) {
4346
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4347
			foreach ( $this->stats as $group => $stats ) {
4348
				if ( is_array( $stats ) && count( $stats ) ) {
4349
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4350
					if ( 'server_side' === $method ) {
4351
						self::do_server_side_stat( $args );
4352
					} else {
4353
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4354
					}
4355
				}
4356
				unset( $this->stats[ $group ] );
4357
			}
4358
		}
4359
	}
4360
4361
	/**
4362
	 * Runs stats code for a one-off, server-side.
4363
	 *
4364
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4365
	 *
4366
	 * @return bool If it worked.
4367
	 */
4368
	static function do_server_side_stat( $args ) {
4369
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4370
		if ( is_wp_error( $response ) )
4371
			return false;
4372
4373
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4374
			return false;
4375
4376
		return true;
4377
	}
4378
4379
	/**
4380
	 * Builds the stats url.
4381
	 *
4382
	 * @param $args array|string The arguments to append to the URL.
4383
	 *
4384
	 * @return string The URL to be pinged.
4385
	 */
4386
	static function build_stats_url( $args ) {
4387
		$defaults = array(
4388
			'v'    => 'wpcom2',
4389
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4390
		);
4391
		$args     = wp_parse_args( $args, $defaults );
4392
		/**
4393
		 * Filter the URL used as the Stats tracking pixel.
4394
		 *
4395
		 * @since 2.3.2
4396
		 *
4397
		 * @param string $url Base URL used as the Stats tracking pixel.
4398
		 */
4399
		$base_url = apply_filters(
4400
			'jetpack_stats_base_url',
4401
			'https://pixel.wp.com/g.gif'
4402
		);
4403
		$url      = add_query_arg( $args, $base_url );
4404
		return $url;
4405
	}
4406
4407
	/**
4408
	 * Get the role of the current user.
4409
	 *
4410
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4411
	 *
4412
	 * @access public
4413
	 * @static
4414
	 *
4415
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4416
	 */
4417
	public static function translate_current_user_to_role() {
4418
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4419
4420
		$roles = new Roles();
4421
		return $roles->translate_current_user_to_role();
4422
	}
4423
4424
	/**
4425
	 * Get the role of a particular user.
4426
	 *
4427
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4428
	 *
4429
	 * @access public
4430
	 * @static
4431
	 *
4432
	 * @param \WP_User $user User object.
4433
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4434
	 */
4435
	public static function translate_user_to_role( $user ) {
4436
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4437
4438
		$roles = new Roles();
4439
		return $roles->translate_user_to_role( $user );
4440
	}
4441
4442
	/**
4443
	 * Get the minimum capability for a role.
4444
	 *
4445
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4446
	 *
4447
	 * @access public
4448
	 * @static
4449
	 *
4450
	 * @param string $role Role name.
4451
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4452
	 */
4453
	public static function translate_role_to_cap( $role ) {
4454
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4455
4456
		$roles = new Roles();
4457
		return $roles->translate_role_to_cap( $role );
4458
	}
4459
4460
	static function sign_role( $role, $user_id = null ) {
4461
		if ( empty( $user_id ) ) {
4462
			$user_id = (int) get_current_user_id();
4463
		}
4464
4465
		if ( ! $user_id  ) {
4466
			return false;
4467
		}
4468
4469
		$token = Jetpack_Data::get_access_token();
4470
		if ( ! $token || is_wp_error( $token ) ) {
4471
			return false;
4472
		}
4473
4474
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4475
	}
4476
4477
4478
	/**
4479
	 * Builds a URL to the Jetpack connection auth page
4480
	 *
4481
	 * @since 3.9.5
4482
	 *
4483
	 * @param bool $raw If true, URL will not be escaped.
4484
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4485
	 *                              If string, will be a custom redirect.
4486
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4487
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4488
	 *
4489
	 * @return string Connect URL
4490
	 */
4491
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4492
		$site_id = Jetpack_Options::get_option( 'id' );
4493
		$blog_token = Jetpack_Data::get_access_token();
4494
4495
		if ( $register || ! $blog_token || ! $site_id ) {
4496
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4497
4498
			if ( ! empty( $redirect ) ) {
4499
				$url = add_query_arg(
4500
					'redirect',
4501
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4502
					$url
4503
				);
4504
			}
4505
4506
			if( is_network_admin() ) {
4507
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4508
			}
4509
		} else {
4510
4511
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4512
			// because otherwise this logic can get us in to a loop.
4513
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4514
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4515
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4516
4517
				$response = Client::wpcom_json_api_request_as_blog(
4518
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4519
					'1.1'
4520
				);
4521
4522
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4523
4524
					// Generating a register URL instead to refresh the existing token
4525
					return $this->build_connect_url( $raw, $redirect, $from, true );
4526
				}
4527
			}
4528
4529
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4530
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4531
			}
4532
4533
			$roles       = new Roles();
4534
			$role        = $roles->translate_current_user_to_role();
4535
			$signed_role = self::sign_role( $role );
4536
4537
			$user = wp_get_current_user();
4538
4539
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4540
			$redirect = $redirect
4541
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4542
				: $jetpack_admin_page;
4543
4544
			if( isset( $_REQUEST['is_multisite'] ) ) {
4545
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4546
			}
4547
4548
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4549
4550
			/**
4551
			 * Filter the type of authorization.
4552
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4553
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4554
			 *
4555
			 * @since 4.3.3
4556
			 *
4557
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4558
			 */
4559
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4560
4561
4562
			$tracks = new Tracking();
4563
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4564
4565
			$args = urlencode_deep(
4566
				array(
4567
					'response_type' => 'code',
4568
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4569
					'redirect_uri'  => add_query_arg(
4570
						array(
4571
							'action'   => 'authorize',
4572
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4573
							'redirect' => urlencode( $redirect ),
4574
						),
4575
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4576
					),
4577
					'state'         => $user->ID,
4578
					'scope'         => $signed_role,
4579
					'user_email'    => $user->user_email,
4580
					'user_login'    => $user->user_login,
4581
					'is_active'     => Jetpack::is_active(),
4582
					'jp_version'    => JETPACK__VERSION,
4583
					'auth_type'     => $auth_type,
4584
					'secret'        => $secrets['secret_1'],
4585
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4586
					'blogname'      => get_option( 'blogname' ),
4587
					'site_url'      => site_url(),
4588
					'home_url'      => home_url(),
4589
					'site_icon'     => get_site_icon_url(),
4590
					'site_lang'     => get_locale(),
4591
					'_ui'           => $tracks_identity['_ui'],
4592
					'_ut'           => $tracks_identity['_ut'],
4593
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4594
				)
4595
			);
4596
4597
			self::apply_activation_source_to_args( $args );
4598
4599
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4600
		}
4601
4602
		if ( $from ) {
4603
			$url = add_query_arg( 'from', $from, $url );
4604
		}
4605
4606
		// Ensure that class to get the affiliate code is loaded
4607
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4608
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4609
		}
4610
		// Get affiliate code and add it to the URL
4611
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4612
4613
		$calypso_env = $this->get_calypso_env();
4614
4615
		if ( ! empty( $calypso_env ) ) {
4616
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4617
		}
4618
4619
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4620
	}
4621
4622
	/**
4623
	 * Get our assumed site creation date.
4624
	 * Calculated based on the earlier date of either:
4625
	 * - Earliest admin user registration date.
4626
	 * - Earliest date of post of any post type.
4627
	 *
4628
	 * @since 7.2.0
4629
	 *
4630
	 * @return string Assumed site creation date and time.
4631
	 */
4632
	public static function get_assumed_site_creation_date() {
4633
		$earliest_registered_users = get_users( array(
4634
			'role'    => 'administrator',
4635
			'orderby' => 'user_registered',
4636
			'order'   => 'ASC',
4637
			'fields'  => array( 'user_registered' ),
4638
			'number'  => 1,
4639
		) );
4640
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4641
4642
		$earliest_posts = get_posts( array(
4643
			'posts_per_page' => 1,
4644
			'post_type'      => 'any',
4645
			'post_status'    => 'any',
4646
			'orderby'        => 'date',
4647
			'order'          => 'ASC',
4648
		) );
4649
4650
		// If there are no posts at all, we'll count only on user registration date.
4651
		if ( $earliest_posts ) {
4652
			$earliest_post_date = $earliest_posts[0]->post_date;
4653
		} else {
4654
			$earliest_post_date = PHP_INT_MAX;
4655
		}
4656
4657
		return min( $earliest_registration_date, $earliest_post_date );
4658
	}
4659
4660
	public static function apply_activation_source_to_args( &$args ) {
4661
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4662
4663
		if ( $activation_source_name ) {
4664
			$args['_as'] = urlencode( $activation_source_name );
4665
		}
4666
4667
		if ( $activation_source_keyword ) {
4668
			$args['_ak'] = urlencode( $activation_source_keyword );
4669
		}
4670
	}
4671
4672
	function build_reconnect_url( $raw = false ) {
4673
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4674
		return $raw ? $url : esc_url( $url );
4675
	}
4676
4677
	public static function admin_url( $args = null ) {
4678
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4679
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4680
		return $url;
4681
	}
4682
4683
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4684
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4685
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4686
	}
4687
4688
	function dismiss_jetpack_notice() {
4689
4690
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4691
			return;
4692
		}
4693
4694
		switch( $_GET['jetpack-notice'] ) {
4695
			case 'dismiss':
4696
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4697
4698
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4699
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4700
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4701
				}
4702
				break;
4703
			case 'jetpack-protect-multisite-opt-out':
4704
4705
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4706
					// Don't show the banner again
4707
4708
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4709
					// redirect back to the page that had the notice
4710
					if ( wp_get_referer() ) {
4711
						wp_safe_redirect( wp_get_referer() );
4712
					} else {
4713
						// Take me to Jetpack
4714
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4715
					}
4716
				}
4717
				break;
4718
		}
4719
	}
4720
4721
	public static function sort_modules( $a, $b ) {
4722
		if ( $a['sort'] == $b['sort'] )
4723
			return 0;
4724
4725
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4726
	}
4727
4728
	function ajax_recheck_ssl() {
4729
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4730
		$result = Jetpack::permit_ssl( true );
4731
		wp_send_json( array(
4732
			'enabled' => $result,
4733
			'message' => get_transient( 'jetpack_https_test_message' )
4734
		) );
4735
	}
4736
4737
/* Client API */
4738
4739
	/**
4740
	 * Returns the requested Jetpack API URL
4741
	 *
4742
	 * @return string
4743
	 */
4744
	public static function api_url( $relative_url ) {
4745
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4746
	}
4747
4748
	/**
4749
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4750
	 */
4751
	public static function fix_url_for_bad_hosts( $url ) {
4752
		if ( 0 !== strpos( $url, 'https://' ) ) {
4753
			return $url;
4754
		}
4755
4756
		switch ( JETPACK_CLIENT__HTTPS ) {
4757
			case 'ALWAYS' :
4758
				return $url;
4759
			case 'NEVER' :
4760
				return set_url_scheme( $url, 'http' );
4761
			// default : case 'AUTO' :
4762
		}
4763
4764
		// we now return the unmodified SSL URL by default, as a security precaution
4765
		return $url;
4766
	}
4767
4768
	/**
4769
	 * Create a random secret for validating onboarding payload
4770
	 *
4771
	 * @return string Secret token
4772
	 */
4773
	public static function create_onboarding_token() {
4774
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4775
			$token = wp_generate_password( 32, false );
4776
			Jetpack_Options::update_option( 'onboarding', $token );
4777
		}
4778
4779
		return $token;
4780
	}
4781
4782
	/**
4783
	 * Remove the onboarding token
4784
	 *
4785
	 * @return bool True on success, false on failure
4786
	 */
4787
	public static function invalidate_onboarding_token() {
4788
		return Jetpack_Options::delete_option( 'onboarding' );
4789
	}
4790
4791
	/**
4792
	 * Validate an onboarding token for a specific action
4793
	 *
4794
	 * @return boolean True if token/action pair is accepted, false if not
4795
	 */
4796
	public static function validate_onboarding_token_action( $token, $action ) {
4797
		// Compare tokens, bail if tokens do not match
4798
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4799
			return false;
4800
		}
4801
4802
		// List of valid actions we can take
4803
		$valid_actions = array(
4804
			'/jetpack/v4/settings',
4805
		);
4806
4807
		// Whitelist the action
4808
		if ( ! in_array( $action, $valid_actions ) ) {
4809
			return false;
4810
		}
4811
4812
		return true;
4813
	}
4814
4815
	/**
4816
	 * Checks to see if the URL is using SSL to connect with Jetpack
4817
	 *
4818
	 * @since 2.3.3
4819
	 * @return boolean
4820
	 */
4821
	public static function permit_ssl( $force_recheck = false ) {
4822
		// Do some fancy tests to see if ssl is being supported
4823
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4824
			$message = '';
4825
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4826
				$ssl = 0;
4827
			} else {
4828
				switch ( JETPACK_CLIENT__HTTPS ) {
4829
					case 'NEVER':
4830
						$ssl = 0;
4831
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4832
						break;
4833
					case 'ALWAYS':
4834
					case 'AUTO':
4835
					default:
4836
						$ssl = 1;
4837
						break;
4838
				}
4839
4840
				// If it's not 'NEVER', test to see
4841
				if ( $ssl ) {
4842
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4843
						$ssl = 0;
4844
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4845
					} else {
4846
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4847
						if ( is_wp_error( $response ) ) {
4848
							$ssl = 0;
4849
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4850
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4851
							$ssl = 0;
4852
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4853
						}
4854
					}
4855
				}
4856
			}
4857
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4858
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4859
		}
4860
4861
		return (bool) $ssl;
4862
	}
4863
4864
	/*
4865
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4866
	 */
4867
	public function alert_auto_ssl_fail() {
4868
		if ( ! current_user_can( 'manage_options' ) )
4869
			return;
4870
4871
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4872
		?>
4873
4874
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4875
			<div class="jp-banner__content">
4876
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4877
				<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>
4878
				<p>
4879
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4880
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4881
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4882
				</p>
4883
				<p>
4884
					<?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' ),
4885
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4886
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4887
				</p>
4888
			</div>
4889
		</div>
4890
		<style>
4891
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4892
		</style>
4893
		<script type="text/javascript">
4894
			jQuery( document ).ready( function( $ ) {
4895
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4896
					var $this = $( this );
4897
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4898
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4899
					e.preventDefault();
4900
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4901
					$.post( ajaxurl, data )
4902
					  .done( function( response ) {
4903
					  	if ( response.enabled ) {
4904
					  		$( '#jetpack-ssl-warning' ).hide();
4905
					  	} else {
4906
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4907
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4908
					  	}
4909
					  }.bind( $this ) );
4910
				} );
4911
			} );
4912
		</script>
4913
4914
		<?php
4915
	}
4916
4917
	/**
4918
	 * Returns the Jetpack XML-RPC API
4919
	 *
4920
	 * @return string
4921
	 */
4922
	public static function xmlrpc_api_url() {
4923
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4924
		return untrailingslashit( $base ) . '/xmlrpc.php';
4925
	}
4926
4927
	public static function connection() {
4928
		return self::init()->connection_manager;
4929
	}
4930
4931
	/**
4932
	 * Creates two secret tokens and the end of life timestamp for them.
4933
	 *
4934
	 * Note these tokens are unique per call, NOT static per site for connecting.
4935
	 *
4936
	 * @since 2.6
4937
	 * @return array
4938
	 */
4939
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4940
		if ( false === $user_id ) {
4941
			$user_id = get_current_user_id();
4942
		}
4943
4944
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4945
	}
4946
4947
	public static function get_secrets( $action, $user_id ) {
4948
		$secrets = self::connection()->get_secrets( $action, $user_id );
4949
4950
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4951
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4952
		}
4953
4954
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4955
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4956
		}
4957
4958
		return $secrets;
4959
	}
4960
4961
	/**
4962
	 * @deprecated 7.5 Use Connection_Manager instead.
4963
	 *
4964
	 * @param $action
4965
	 * @param $user_id
4966
	 */
4967
	public static function delete_secrets( $action, $user_id ) {
4968
		return self::connection()->delete_secrets( $action, $user_id );
4969
	}
4970
4971
	/**
4972
	 * Builds the timeout limit for queries talking with the wpcom servers.
4973
	 *
4974
	 * Based on local php max_execution_time in php.ini
4975
	 *
4976
	 * @since 2.6
4977
	 * @return int
4978
	 * @deprecated
4979
	 **/
4980
	public function get_remote_query_timeout_limit() {
4981
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4982
		return Jetpack::get_max_execution_time();
4983
	}
4984
4985
	/**
4986
	 * Builds the timeout limit for queries talking with the wpcom servers.
4987
	 *
4988
	 * Based on local php max_execution_time in php.ini
4989
	 *
4990
	 * @since 5.4
4991
	 * @return int
4992
	 **/
4993
	public static function get_max_execution_time() {
4994
		$timeout = (int) ini_get( 'max_execution_time' );
4995
4996
		// Ensure exec time set in php.ini
4997
		if ( ! $timeout ) {
4998
			$timeout = 30;
4999
		}
5000
		return $timeout;
5001
	}
5002
5003
	/**
5004
	 * Sets a minimum request timeout, and returns the current timeout
5005
	 *
5006
	 * @since 5.4
5007
	 **/
5008
	public static function set_min_time_limit( $min_timeout ) {
5009
		$timeout = self::get_max_execution_time();
5010
		if ( $timeout < $min_timeout ) {
5011
			$timeout = $min_timeout;
5012
			set_time_limit( $timeout );
5013
		}
5014
		return $timeout;
5015
	}
5016
5017
5018
	/**
5019
	 * Takes the response from the Jetpack register new site endpoint and
5020
	 * verifies it worked properly.
5021
	 *
5022
	 * @since 2.6
5023
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5024
	 **/
5025
	public function validate_remote_register_response( $response ) {
5026
	  if ( is_wp_error( $response ) ) {
5027
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

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

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

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

Loading history...
5028
		}
5029
5030
		$code   = wp_remote_retrieve_response_code( $response );
5031
		$entity = wp_remote_retrieve_body( $response );
5032
		if ( $entity )
5033
			$registration_response = json_decode( $entity );
5034
		else
5035
			$registration_response = false;
5036
5037
		$code_type = intval( $code / 100 );
5038
		if ( 5 == $code_type ) {
5039
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

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

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

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

Loading history...
5040
		} elseif ( 408 == $code ) {
5041
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_408'.

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

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

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

Loading history...
5042
		} elseif ( ! empty( $registration_response->error ) ) {
5043
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5044
				$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' );
5045
			} else {
5046
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5047
			}
5048
5049
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->error.

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

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

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

Loading history...
5050
		} elseif ( 200 != $code ) {
5051
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

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

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

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

Loading history...
5052
		}
5053
5054
		// Jetpack ID error block
5055
		if ( empty( $registration_response->jetpack_id ) ) {
5056
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5057
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5058
			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 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5059
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5060
			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 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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

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

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

Loading history...
5061
		}
5062
5063
	    return $registration_response;
5064
	}
5065
	/**
5066
	 * @return bool|WP_Error
5067
	 */
5068
	public static function register() {
5069
		$tracking = new Tracking();
5070
		$tracking->record_user_event( 'jpc_register_begin' );
5071
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5072
		$secrets = Jetpack::generate_secrets( 'register' );
5073
5074 View Code Duplication
		if (
5075
			empty( $secrets['secret_1'] ) ||
5076
			empty( $secrets['secret_2'] ) ||
5077
			empty( $secrets['exp'] )
5078
		) {
5079
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

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

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

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

Loading history...
5080
		}
5081
5082
		// better to try (and fail) to set a higher timeout than this system
5083
		// supports than to have register fail for more users than it should
5084
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5085
5086
		$gmt_offset = get_option( 'gmt_offset' );
5087
		if ( ! $gmt_offset ) {
5088
			$gmt_offset = 0;
5089
		}
5090
5091
		$stats_options = get_option( 'stats_options' );
5092
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5093
5094
		$tracks = new Tracking();
5095
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5096
5097
		$args = array(
5098
			'method'  => 'POST',
5099
			'body'    => array(
5100
				'siteurl'         => site_url(),
5101
				'home'            => home_url(),
5102
				'gmt_offset'      => $gmt_offset,
5103
				'timezone_string' => (string) get_option( 'timezone_string' ),
5104
				'site_name'       => (string) get_option( 'blogname' ),
5105
				'secret_1'        => $secrets['secret_1'],
5106
				'secret_2'        => $secrets['secret_2'],
5107
				'site_lang'       => get_locale(),
5108
				'timeout'         => $timeout,
5109
				'stats_id'        => $stats_id,
5110
				'state'           => get_current_user_id(),
5111
				'_ui'             => $tracks_identity['_ui'],
5112
				'_ut'             => $tracks_identity['_ut'],
5113
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5114
				'jetpack_version' => JETPACK__VERSION,
5115
				'ABSPATH'         => defined( 'ABSPATH' ) ? ABSPATH : '',
5116
			),
5117
			'headers' => array(
5118
				'Accept' => 'application/json',
5119
			),
5120
			'timeout' => $timeout,
5121
		);
5122
5123
		self::apply_activation_source_to_args( $args['body'] );
5124
5125
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5126
5127
		// Make sure the response is valid and does not contain any Jetpack errors
5128
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5129
		if ( is_wp_error( $registration_details ) ) {
5130
			return $registration_details;
5131
		} elseif ( ! $registration_details ) {
5132
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
5133
		}
5134
5135 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5136
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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

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

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

Loading history...
5137
		}
5138
5139
		if ( isset( $registration_details->jetpack_public ) ) {
5140
			$jetpack_public = (int) $registration_details->jetpack_public;
5141
		} else {
5142
			$jetpack_public = false;
5143
		}
5144
5145
		Jetpack_Options::update_options(
5146
			array(
5147
				'id'         => (int)    $registration_details->jetpack_id,
5148
				'blog_token' => (string) $registration_details->jetpack_secret,
5149
				'public'     => $jetpack_public,
5150
			)
5151
		);
5152
5153
		/**
5154
		 * Fires when a site is registered on WordPress.com.
5155
		 *
5156
		 * @since 3.7.0
5157
		 *
5158
		 * @param int $json->jetpack_id Jetpack Blog ID.
5159
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5160
		 * @param int|bool $jetpack_public Is the site public.
5161
		 */
5162
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5163
5164
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
5165
5166
		return true;
5167
	}
5168
5169
	/**
5170
	 * If the db version is showing something other that what we've got now, bump it to current.
5171
	 *
5172
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5173
	 */
5174
	public static function maybe_set_version_option() {
5175
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5176
		if ( JETPACK__VERSION != $version ) {
5177
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5178
5179
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5180
				/** This action is documented in class.jetpack.php */
5181
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5182
			}
5183
5184
			return true;
5185
		}
5186
		return false;
5187
	}
5188
5189
/* Client Server API */
5190
5191
	/**
5192
	 * Loads the Jetpack XML-RPC client
5193
	 */
5194
	public static function load_xml_rpc_client() {
5195
		require_once ABSPATH . WPINC . '/class-IXR.php';
5196
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5197
	}
5198
5199
	/**
5200
	 * Resets the saved authentication state in between testing requests.
5201
	 */
5202
	public function reset_saved_auth_state() {
5203
		$this->xmlrpc_verification = null;
5204
		$this->rest_authentication_status = null;
5205
	}
5206
5207
	/**
5208
	 * Verifies the signature of the current request.
5209
	 *
5210
	 * @return false|array
5211
	 */
5212
	function verify_xml_rpc_signature() {
5213
		if ( is_null( $this->xmlrpc_verification ) ) {
5214
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5215
5216
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5217
				/**
5218
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5219
				 *
5220
				 * Error codes:
5221
				 * - malformed_token
5222
				 * - malformed_user_id
5223
				 * - unknown_token
5224
				 * - could_not_sign
5225
				 * - invalid_nonce
5226
				 * - signature_mismatch
5227
				 *
5228
				 * @since 7.5.0
5229
				 *
5230
				 * @param WP_Error $signature_verification_error The verification error
5231
				 */
5232
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5233
			}
5234
		}
5235
5236
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5237
	}
5238
5239
	/**
5240
	 * Verifies the signature of the current request.
5241
	 *
5242
	 * This function has side effects and should not be used. Instead,
5243
	 * use the memoized version `->verify_xml_rpc_signature()`.
5244
	 *
5245
	 * @internal
5246
	 */
5247
	private function internal_verify_xml_rpc_signature() {
5248
		// It's not for us
5249
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5250
			return false;
5251
		}
5252
5253
		$signature_details = array(
5254
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5255
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5256
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5257
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5258
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5259
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5260
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5261
		);
5262
5263
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
5264
		if (
5265
			empty( $token_key )
5266
		||
5267
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5268
		) {
5269
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
5270
		}
5271
5272
		if ( '0' === $user_id ) {
5273
			$token_type = 'blog';
5274
			$user_id = 0;
5275
		} else {
5276
			$token_type = 'user';
5277
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5278
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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

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

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

Loading history...
5279
			}
5280
			$user_id = (int) $user_id;
5281
5282
			$user = new WP_User( $user_id );
5283
			if ( ! $user || ! $user->exists() ) {
5284
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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

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

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

Loading history...
5285
			}
5286
		}
5287
5288
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
0 ignored issues
show
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5289
		if ( is_wp_error( $token ) ) {
5290
			$token->add_data( compact( 'signature_details' ) );
5291
			return $token;
5292
		} elseif ( ! $token ) {
5293
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
5294
		}
5295
5296
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5297
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5298
			$post_data   = $_POST;
5299
			$file_hashes = array();
5300
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5301
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5302
					continue;
5303
				}
5304
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5305
				$file_hashes[$post_data_key] = $post_data_value;
5306
			}
5307
5308
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5309
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5310
				$post_data[$post_data_key] = $post_data_value;
5311
			}
5312
5313
			ksort( $post_data );
5314
5315
			$body = http_build_query( stripslashes_deep( $post_data ) );
5316
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5317
			$body = file_get_contents( 'php://input' );
5318
		} else {
5319
			$body = null;
5320
		}
5321
5322
		$signature = $jetpack_signature->sign_current_request(
5323
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5324
		);
5325
5326
		$signature_details['url'] = $jetpack_signature->current_request_url;
5327
5328
		if ( ! $signature ) {
5329
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
5330
		} else if ( is_wp_error( $signature ) ) {
5331
			return $signature;
5332
		}
5333
5334
		$timestamp = (int) $_GET['timestamp'];
5335
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5336
5337
		// Use up the nonce regardless of whether the signature matches.
5338
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5339
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
5340
		}
5341
5342
		// Be careful about what you do with this debugging data.
5343
		// If a malicious requester has access to the expected signature,
5344
		// bad things might be possible.
5345
		$signature_details['expected'] = $signature;
5346
5347
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5348
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

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