Completed
Push — add/user-authentication ( 34ed8f...93b97f )
by
unknown
288:07 queued 279:09
created

class.jetpack.php (9 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
5248
			}
5249
		}
5250
5251
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
0 ignored issues
show
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

Loading history...
5257
		}
5258
5259
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5260
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5261
			$post_data   = $_POST;
5262
			$file_hashes = array();
5263
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5264
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5265
					continue;
5266
				}
5267
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5268
				$file_hashes[$post_data_key] = $post_data_value;
5269
			}
5270
5271
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5272
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5273
				$post_data[$post_data_key] = $post_data_value;
5274
			}
5275
5276
			ksort( $post_data );
5277
5278
			$body = http_build_query( stripslashes_deep( $post_data ) );
5279
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5280
			$body = file_get_contents( 'php://input' );
5281
		} else {
5282
			$body = null;
5283
		}
5284
5285
		$signature = $jetpack_signature->sign_current_request(
5286
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5287
		);
5288
5289
		$signature_details['url'] = $jetpack_signature->current_request_url;
5290
5291
		if ( ! $signature ) {
5292
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
5293
		} else if ( is_wp_error( $signature ) ) {
5294
			return $signature;
5295
		}
5296
5297
		$timestamp = (int) $_GET['timestamp'];
5298
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5299
5300
		// Use up the nonce regardless of whether the signature matches.
5301
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5302
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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

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

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

Loading history...
5303
		}
5304
5305
		// Be careful about what you do with this debugging data.
5306
		// If a malicious requester has access to the expected signature,
5307
		// bad things might be possible.
5308
		$signature_details['expected'] = $signature;
5309
5310
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5311
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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

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

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

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