Completed
Push — add/signature-error-reporting ( d88fea...6482e9 )
by
unknown
32:31 queued 22:55
created

class.jetpack.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

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

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

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

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