Completed
Push — add/is-active-to-connection-pa... ( 30e22c )
by
unknown
18:06 queued 10:36
created

class.jetpack.php (2 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
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
use \Automattic\Jetpack\Connection\Manager as Connection_Manager;
26
27
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
28
29
class Jetpack {
30
	public $xmlrpc_server = null;
31
32
	private $xmlrpc_verification = null;
33
	private $rest_authentication_status = null;
34
35
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
36
37
	/**
38
	 * @var array The handles of styles that are concatenated into jetpack.css.
39
	 *
40
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
41
	 */
42
	public $concatenated_style_handles = array(
43
		'jetpack-carousel',
44
		'grunion.css',
45
		'the-neverending-homepage',
46
		'jetpack_likes',
47
		'jetpack_related-posts',
48
		'sharedaddy',
49
		'jetpack-slideshow',
50
		'presentations',
51
		'quiz',
52
		'jetpack-subscriptions',
53
		'jetpack-responsive-videos-style',
54
		'jetpack-social-menu',
55
		'tiled-gallery',
56
		'jetpack_display_posts_widget',
57
		'gravatar-profile-widget',
58
		'goodreads-widget',
59
		'jetpack_social_media_icons_widget',
60
		'jetpack-top-posts-widget',
61
		'jetpack_image_widget',
62
		'jetpack-my-community-widget',
63
		'jetpack-authors-widget',
64
		'wordads',
65
		'eu-cookie-law-style',
66
		'flickr-widget-style',
67
		'jetpack-search-widget',
68
		'jetpack-simple-payments-widget-style',
69
		'jetpack-widget-social-icons-styles',
70
	);
71
72
	/**
73
	 * Contains all assets that have had their URL rewritten to minified versions.
74
	 *
75
	 * @var array
76
	 */
77
	static $min_assets = array();
78
79
	public $plugins_to_deactivate = array(
80
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
81
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
82
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
83
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
84
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
85
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
86
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
87
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
88
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
89
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
90
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
91
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
92
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
93
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
94
	);
95
96
	static $capability_translations = array(
97
		'administrator' => 'manage_options',
98
		'editor'        => 'edit_others_posts',
99
		'author'        => 'publish_posts',
100
		'contributor'   => 'edit_posts',
101
		'subscriber'    => 'read',
102
	);
103
104
	/**
105
	 * Map of modules that have conflicts with plugins and should not be auto-activated
106
	 * if the plugins are active.  Used by filter_default_modules
107
	 *
108
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
109
	 * change `module-slug` and add this to your plugin:
110
	 *
111
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
112
	 * function my_jetpack_get_default_modules( $modules ) {
113
	 *     return array_diff( $modules, array( 'module-slug' ) );
114
	 * }
115
	 *
116
	 * @var array
117
	 */
118
	private $conflicting_plugins = array(
119
		'comments'          => array(
120
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
121
			'Disqus'                               => 'disqus-comment-system/disqus.php',
122
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
123
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
124
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
125
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
126
		),
127
		'comment-likes' => array(
128
			'Epoch'                                => 'epoch/plugincore.php',
129
		),
130
		'contact-form'      => array(
131
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
132
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
133
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
134
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
135
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
136
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
137
		),
138
		'minileven'         => array(
139
			'WPtouch'                              => 'wptouch/wptouch.php',
140
		),
141
		'latex'             => array(
142
			'LaTeX for WordPress'                  => 'latex/latex.php',
143
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
144
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
145
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
146
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
147
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
148
		),
149
		'protect'           => array(
150
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
151
			'Captcha'                              => 'captcha/captcha.php',
152
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
153
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
154
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
155
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
156
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
157
			'Security-protection'                  => 'security-protection/security-protection.php',
158
			'Login Security'                       => 'login-security/login-security.php',
159
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
160
			'Wordfence Security'                   => 'wordfence/wordfence.php',
161
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
162
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
163
		),
164
		'random-redirect'   => array(
165
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
166
		),
167
		'related-posts'     => array(
168
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
169
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
170
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
171
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
172
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
173
			'outbrain'                             => 'outbrain/outbrain.php',
174
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
175
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
176
		),
177
		'sharedaddy'        => array(
178
			'AddThis'                              => 'addthis/addthis_social_widget.php',
179
			'Add To Any'                           => 'add-to-any/add-to-any.php',
180
			'ShareThis'                            => 'share-this/sharethis.php',
181
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
182
		),
183
		'seo-tools' => array(
184
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
185
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
186
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
187
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
188
			'The SEO Framework'                    => 'autodescription/autodescription.php',
189
		),
190
		'verification-tools' => array(
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'The SEO Framework'                    => 'autodescription/autodescription.php',
196
		),
197
		'widget-visibility' => array(
198
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
199
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
200
		),
201
		'sitemaps' => array(
202
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
203
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
204
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
205
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
206
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
207
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'                    => 'autodescription/autodescription.php',
212
			'Sitemap'                              => 'sitemap/sitemap.php',
213
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
214
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
215
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
216
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
217
		),
218
		'lazy-images' => array(
219
			'Lazy Load'              => 'lazy-load/lazy-load.php',
220
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
221
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
222
		),
223
	);
224
225
	/**
226
	 * Plugins for which we turn off our Facebook OG Tags implementation.
227
	 *
228
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
229
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
230
	 *
231
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
232
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
233
	 */
234
	private $open_graph_conflicting_plugins = array(
235
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
236
		                                                         // 2 Click Social Media Buttons
237
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
238
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
239
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
240
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
241
		                                                         // Open Graph Meta Tags by Heateor
242
		'facebook/facebook.php',                                 // Facebook (official plugin)
243
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
244
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
245
		                                                         // Facebook Featured Image & OG Meta Tags
246
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
247
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
248
		                                                         // Facebook Open Graph Meta Tags for WordPress
249
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
250
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
251
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
252
		                                                         // Fedmich's Facebook Open Graph Meta
253
		'network-publisher/networkpub.php',                      // Network Publisher
254
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
255
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
256
		                                                         // NextScripts SNAP
257
		'og-tags/og-tags.php',                                   // OG Tags
258
		'opengraph/opengraph.php',                               // Open Graph
259
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
260
		                                                         // Open Graph Protocol Framework
261
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
262
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
263
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
264
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
265
		'sharepress/sharepress.php',                             // SharePress
266
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
267
		'social-discussions/social-discussions.php',             // Social Discussions
268
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
269
		'socialize/socialize.php',                               // Socialize
270
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
271
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
272
		                                                         // Tweet, Like, Google +1 and Share
273
		'wordbooker/wordbooker.php',                             // Wordbooker
274
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
275
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
276
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
277
		                                                         // WP Facebook Like Send & Open Graph Meta
278
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
279
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
280
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
281
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
282
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
283
	);
284
285
	/**
286
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
287
	 */
288
	private $twitter_cards_conflicting_plugins = array(
289
	//	'twitter/twitter.php',                       // The official one handles this on its own.
290
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
291
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
292
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
293
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
294
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
295
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
296
		'twitter-cards/twitter-cards.php',           // Twitter Cards
297
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
298
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
299
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
300
	);
301
302
	/**
303
	 * Message to display in admin_notice
304
	 * @var string
305
	 */
306
	public $message = '';
307
308
	/**
309
	 * Error to display in admin_notice
310
	 * @var string
311
	 */
312
	public $error = '';
313
314
	/**
315
	 * Modules that need more privacy description.
316
	 * @var string
317
	 */
318
	public $privacy_checks = '';
319
320
	/**
321
	 * Stats to record once the page loads
322
	 *
323
	 * @var array
324
	 */
325
	public $stats = array();
326
327
	/**
328
	 * Jetpack_Sync object
329
	 */
330
	public $sync;
331
332
	/**
333
	 * Verified data for JSON authorization request
334
	 */
335
	public $json_api_authorization_request = array();
336
337
	/**
338
	 * @var \Automattic\Jetpack\Connection\Manager
339
	 */
340
	protected $connection_manager;
341
342
	/**
343
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
344
	 */
345
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
346
347
	/**
348
	 * Holds the singleton instance of this class
349
	 * @since 2.3.3
350
	 * @var Jetpack
351
	 */
352
	static $instance = false;
353
354
	/**
355
	 * Singleton
356
	 * @static
357
	 */
358
	public static function init() {
359
		if ( ! self::$instance ) {
360
			self::$instance = new Jetpack;
361
362
			self::$instance->plugin_upgrade();
363
		}
364
365
		return self::$instance;
366
	}
367
368
	/**
369
	 * Must never be called statically
370
	 */
371
	function plugin_upgrade() {
372
		if ( Jetpack::is_active() ) {
373
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
374
			if ( JETPACK__VERSION != $version ) {
375
				// Prevent multiple upgrades at once - only a single process should trigger
376
				// an upgrade to avoid stampedes
377
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
378
					return;
379
				}
380
381
				// Set a short lock to prevent multiple instances of the upgrade
382
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
383
384
				// check which active modules actually exist and remove others from active_modules list
385
				$unfiltered_modules = Jetpack::get_active_modules();
386
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
387
				if ( array_diff( $unfiltered_modules, $modules ) ) {
388
					Jetpack::update_active_modules( $modules );
389
				}
390
391
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
392
393
				// Upgrade to 4.3.0
394
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
395
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
396
				}
397
398
				// Make sure Markdown for posts gets turned back on
399
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
400
					update_option( 'wpcom_publish_posts_with_markdown', true );
401
				}
402
403
				if ( did_action( 'wp_loaded' ) ) {
404
					self::upgrade_on_load();
405
				} else {
406
					add_action(
407
						'wp_loaded',
408
						array( __CLASS__, 'upgrade_on_load' )
409
					);
410
				}
411
			}
412
		}
413
	}
414
415
	/**
416
	 * Runs upgrade routines that need to have modules loaded.
417
	 */
418
	static function upgrade_on_load() {
419
420
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
421
		// This can happen in case Jetpack has been just upgraded and is
422
		// being initialized late during the page load. In this case we wait
423
		// until the next proper admin page load with Jetpack active.
424
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
425
			delete_transient( self::$plugin_upgrade_lock_key );
426
427
			return;
428
		}
429
430
		Jetpack::maybe_set_version_option();
431
432
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
433
			Jetpack_Widget_Conditions::migrate_post_type_rules();
434
		}
435
436
		if (
437
			class_exists( 'Jetpack_Sitemap_Manager' )
438
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
439
		) {
440
			do_action( 'jetpack_sitemaps_purge_data' );
441
		}
442
443
		delete_transient( self::$plugin_upgrade_lock_key );
444
	}
445
446
	/**
447
	 * Saves all the currently active modules to options.
448
	 * Also fires Action hooks for each newly activated and deactived module.
449
	 *
450
	 * @param $modules Array Array of active modules to be saved in options.
451
	 *
452
	 * @return $success bool true for success, false for failure.
453
	 */
454
	static function update_active_modules( $modules ) {
455
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
456
		$active_modules       = Jetpack::get_active_modules();
457
		$new_active_modules   = array_diff( $modules, $current_modules );
458
		$new_inactive_modules = array_diff( $active_modules, $modules );
459
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
460
		$reindexed_modules    = array_values( $new_current_modules );
461
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
462
463
		foreach ( $new_active_modules as $module ) {
464
			/**
465
			 * Fires when a specific module is activated.
466
			 *
467
			 * @since 1.9.0
468
			 *
469
			 * @param string $module Module slug.
470
			 * @param boolean $success whether the module was activated. @since 4.2
471
			 */
472
			do_action( 'jetpack_activate_module', $module, $success );
473
			/**
474
			 * Fires when a module is activated.
475
			 * The dynamic part of the filter, $module, is the module slug.
476
			 *
477
			 * @since 1.9.0
478
			 *
479
			 * @param string $module Module slug.
480
			 */
481
			do_action( "jetpack_activate_module_$module", $module );
482
		}
483
484
		foreach ( $new_inactive_modules as $module ) {
485
			/**
486
			 * Fired after a module has been deactivated.
487
			 *
488
			 * @since 4.2.0
489
			 *
490
			 * @param string $module Module slug.
491
			 * @param boolean $success whether the module was deactivated.
492
			 */
493
			do_action( 'jetpack_deactivate_module', $module, $success );
494
			/**
495
			 * Fires when a module is deactivated.
496
			 * The dynamic part of the filter, $module, is the module slug.
497
			 *
498
			 * @since 1.9.0
499
			 *
500
			 * @param string $module Module slug.
501
			 */
502
			do_action( "jetpack_deactivate_module_$module", $module );
503
		}
504
505
		return $success;
506
	}
507
508
	static function delete_active_modules() {
509
		self::update_active_modules( array() );
510
	}
511
512
	/**
513
	 * Constructor.  Initializes WordPress hooks
514
	 */
515
	private function __construct() {
516
		/*
517
		 * Check for and alert any deprecated hooks
518
		 */
519
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
520
521
		/*
522
		 * Enable enhanced handling of previewing sites in Calypso
523
		 */
524
		if ( Jetpack::is_active() ) {
525
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
526
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
527
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
528
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
529
		}
530
531
		/*
532
		 * Load things that should only be in Network Admin.
533
		 *
534
		 * For now blow away everything else until a more full
535
		 * understanding of what is needed at the network level is
536
		 * available
537
		 */
538
		if ( is_multisite() ) {
539
			Jetpack_Network::init();
540
		}
541
542
		add_filter( 'jetpack_connection_option_manager', function() {
543
			return new Jetpack_Options_Manager();
544
		} );
545
546
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
547
			return function() {
548
				return wp_generate_password( 32, false );
549
			};
550
		} );
551
552
		$this->connection_manager = new Connection_Manager( );
553
554
		/**
555
		 * Prepare Gutenberg Editor functionality
556
		 */
557
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
558
		Jetpack_Gutenberg::init();
559
		Jetpack_Gutenberg::load_independent_blocks();
560
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
561
562
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
563
564
		// Unlink user before deleting the user from .com
565
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
566
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
567
568
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
569
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
570
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
571
				define( 'XMLRPC_REQUEST', true );
572
			}
573
574
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
575
576
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
577
		}
578
579
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
580
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
581
582
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
583
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
584
585
			$this->require_jetpack_authentication();
586
587
			if ( Jetpack::is_active() ) {
588
				// Hack to preserve $HTTP_RAW_POST_DATA
589
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
590
591
				$signed = $this->verify_xml_rpc_signature();
592 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
593
					// The actual API methods.
594
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
595
				} else {
596
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
597
					// active Jetpack connection, so that additional users can link their account.
598
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
599
				}
600 View Code Duplication
			} else {
601
				// The bootstrap API methods.
602
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
603
				$signed = $this->verify_xml_rpc_signature();
604
				if ( $signed && ! is_wp_error( $signed ) ) {
605
					// the jetpack Provision method is available for blog-token-signed requests
606
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
607
				}
608
			}
609
610
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
611
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
612
		} elseif (
613
			is_admin() &&
614
			isset( $_POST['action'] ) && (
615
				'jetpack_upload_file' == $_POST['action'] ||
616
				'jetpack_update_file' == $_POST['action']
617
			)
618
		) {
619
			$this->require_jetpack_authentication();
620
			$this->add_remote_request_handlers();
621
		} else {
622
			if ( Jetpack::is_active() ) {
623
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
624
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
625
			}
626
		}
627
628
		if ( Jetpack::is_active() ) {
629
			Jetpack_Heartbeat::init();
630
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
631
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
632
				Jetpack_Search_Performance_Logger::init();
633
			}
634
		}
635
636
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
637
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
638
639
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
640
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
641
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
642
		}
643
644
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
645
646
		add_action( 'admin_init', array( $this, 'admin_init' ) );
647
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
648
649
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
650
651
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
652
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
653
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
654
655
		// returns HTTPS support status
656
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
657
658
		// JITM AJAX callback function
659
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
660
661
		// Universal ajax callback for all tracking events triggered via js
662
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
663
664
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
665
666
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
667
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
668
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
669
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
670
671
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
672
673
		/**
674
		 * These actions run checks to load additional files.
675
		 * They check for external files or plugins, so they need to run as late as possible.
676
		 */
677
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
678
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
679
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
680
681
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
682
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
683
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
684
685
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
686
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
687
688
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
689
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
690
691
		// A filter to control all just in time messages
692
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
693
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
694
695
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
696
		// We should make sure to only do this for front end links.
697
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
698
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
699
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
700
701
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
702
			//so they point moderation links on emails to Calypso
703
			jetpack_require_lib( 'functions.wp-notify' );
704
		}
705
706
		// Update the Jetpack plan from API on heartbeats
707
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
708
709
		/**
710
		 * This is the hack to concatenate all css files into one.
711
		 * For description and reasoning see the implode_frontend_css method
712
		 *
713
		 * Super late priority so we catch all the registered styles
714
		 */
715
		if( !is_admin() ) {
716
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
717
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
718
		}
719
720
		/**
721
		 * These are sync actions that we need to keep track of for jitms
722
		 */
723
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
724
725
		// Actually push the stats on shutdown.
726
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
727
			add_action( 'shutdown', array( $this, 'push_stats' ) );
728
		}
729
	}
730
731
	/**
732
	 * This is ported over from the manage module, which has been deprecated and baked in here.
733
	 *
734
	 * @param $domains
735
	 */
736
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
737
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
738
	}
739
740
	/**
741
	 * Return $domains, with 'wordpress.com' appended.
742
	 * This is ported over from the manage module, which has been deprecated and baked in here.
743
	 *
744
	 * @param $domains
745
	 * @return array
746
	 */
747
	function allow_wpcom_domain( $domains ) {
748
		if ( empty( $domains ) ) {
749
			$domains = array();
750
		}
751
		$domains[] = 'wordpress.com';
752
		return array_unique( $domains );
753
	}
754
755
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
756
		$post = get_post( $post_id );
757
758
		if ( empty( $post ) ) {
759
			return $default_url;
760
		}
761
762
		$post_type = $post->post_type;
763
764
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
765
		// https://en.support.wordpress.com/custom-post-types/
766
		$allowed_post_types = array(
767
			'post' => 'post',
768
			'page' => 'page',
769
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
770
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
771
		);
772
773
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
774
			return $default_url;
775
		}
776
777
		$path_prefix = $allowed_post_types[ $post_type ];
778
779
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
780
781
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
782
	}
783
784
	function point_edit_comment_links_to_calypso( $url ) {
785
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
786
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
787
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
788
			Jetpack::build_raw_urls( get_home_url() ),
789
			$query_args['amp;c']
790
		) );
791
	}
792
793
	function jetpack_track_last_sync_callback( $params ) {
794
		/**
795
		 * Filter to turn off jitm caching
796
		 *
797
		 * @since 5.4.0
798
		 *
799
		 * @param bool false Whether to cache just in time messages
800
		 */
801
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
802
			return $params;
803
		}
804
805
		if ( is_array( $params ) && isset( $params[0] ) ) {
806
			$option = $params[0];
807
			if ( 'active_plugins' === $option ) {
808
				// use the cache if we can, but not terribly important if it gets evicted
809
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
810
			}
811
		}
812
813
		return $params;
814
	}
815
816
	function jetpack_connection_banner_callback() {
817
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
818
819
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
820
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
821
			wp_send_json_success();
822
		}
823
824
		wp_die();
825
	}
826
827
	/**
828
	 * Removes all XML-RPC methods that are not `jetpack.*`.
829
	 * Only used in our alternate XML-RPC endpoint, where we want to
830
	 * ensure that Core and other plugins' methods are not exposed.
831
	 *
832
	 * @param array $methods
833
	 * @return array filtered $methods
834
	 */
835
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
836
		$jetpack_methods = array();
837
838
		foreach ( $methods as $method => $callback ) {
839
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
840
				$jetpack_methods[ $method ] = $callback;
841
			}
842
		}
843
844
		return $jetpack_methods;
845
	}
846
847
	/**
848
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
849
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
850
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
851
	 * which is accessible via a different URI. Most of the below is copied directly
852
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
853
	 */
854
	function alternate_xmlrpc() {
855
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
856
		global $HTTP_RAW_POST_DATA;
857
858
		// Some browser-embedded clients send cookies. We don't want them.
859
		$_COOKIE = array();
860
861
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
862
		// but we can do it ourself.
863
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
864
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
865
		}
866
867
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
868
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
869
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
870
		}
871
872
		// phpcs:enable
873
874
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
875
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
876
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
877
878
		/**
879
		 * Filters the class used for handling XML-RPC requests.
880
		 *
881
		 * @since 3.1.0
882
		 *
883
		 * @param string $class The name of the XML-RPC server class.
884
		 */
885
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
886
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
887
888
		// Fire off the request
889
		nocache_headers();
890
		$wp_xmlrpc_server->serve_request();
891
892
		exit;
893
	}
894
895
	function jetpack_admin_ajax_tracks_callback() {
896
		// Check for nonce
897
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
898
			wp_die( 'Permissions check failed.' );
899
		}
900
901
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
902
			wp_die( 'No valid event name or type.' );
903
		}
904
905
		$tracks_data = array();
906
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
907
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
908
				$tracks_data = $_REQUEST['tracksEventProp'];
909
			} else {
910
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
911
			}
912
		}
913
914
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
915
		wp_send_json_success();
916
		wp_die();
917
	}
918
919
	/**
920
	 * The callback for the JITM ajax requests.
921
	 */
922
	function jetpack_jitm_ajax_callback() {
923
		// Check for nonce
924
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
925
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
926
		}
927
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
928
			$module_slug = $_REQUEST['jitmModule'];
929
			Jetpack::log( 'activate', $module_slug );
930
			Jetpack::activate_module( $module_slug, false, false );
931
			Jetpack::state( 'message', 'no_message' );
932
933
			//A Jetpack module is being activated through a JITM, track it
934
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
935
			$this->do_stats( 'server_side' );
936
937
			wp_send_json_success();
938
		}
939
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
940
			// get the hide_jitm options array
941
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
942
			$module_slug = $_REQUEST['jitmModule'];
943
944
			if( ! $jetpack_hide_jitm ) {
945
				$jetpack_hide_jitm = array(
946
					$module_slug => 'hide'
947
				);
948
			} else {
949
				$jetpack_hide_jitm[$module_slug] = 'hide';
950
			}
951
952
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
953
954
			//jitm is being dismissed forever, track it
955
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
956
			$this->do_stats( 'server_side' );
957
958
			wp_send_json_success();
959
		}
960 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
961
			$module_slug = $_REQUEST['jitmModule'];
962
963
			// User went to WordPress.com, track this
964
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
965
			$this->do_stats( 'server_side' );
966
967
			wp_send_json_success();
968
		}
969 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
970
			$track = $_REQUEST['jitmModule'];
971
972
			// User is viewing JITM, track it.
973
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
974
			$this->do_stats( 'server_side' );
975
976
			wp_send_json_success();
977
		}
978
	}
979
980
	/**
981
	 * If there are any stats that need to be pushed, but haven't been, push them now.
982
	 */
983
	function push_stats() {
984
		if ( ! empty( $this->stats ) ) {
985
			$this->do_stats( 'server_side' );
986
		}
987
	}
988
989
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
990
		switch( $cap ) {
991
			case 'jetpack_connect' :
992
			case 'jetpack_reconnect' :
993
				if ( Jetpack::is_development_mode() ) {
994
					$caps = array( 'do_not_allow' );
995
					break;
996
				}
997
				/**
998
				 * Pass through. If it's not development mode, these should match disconnect.
999
				 * Let users disconnect if it's development mode, just in case things glitch.
1000
				 */
1001
			case 'jetpack_disconnect' :
1002
				/**
1003
				 * In multisite, can individual site admins manage their own connection?
1004
				 *
1005
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1006
				 */
1007
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1008
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1009
						/**
1010
						 * We need to update the option name -- it's terribly unclear which
1011
						 * direction the override goes.
1012
						 *
1013
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1014
						 */
1015
						$caps = array( 'do_not_allow' );
1016
						break;
1017
					}
1018
				}
1019
1020
				$caps = array( 'manage_options' );
1021
				break;
1022
			case 'jetpack_manage_modules' :
1023
			case 'jetpack_activate_modules' :
1024
			case 'jetpack_deactivate_modules' :
1025
				$caps = array( 'manage_options' );
1026
				break;
1027
			case 'jetpack_configure_modules' :
1028
				$caps = array( 'manage_options' );
1029
				break;
1030
			case 'jetpack_manage_autoupdates' :
1031
				$caps = array(
1032
					'manage_options',
1033
					'update_plugins',
1034
				);
1035
				break;
1036
			case 'jetpack_network_admin_page':
1037
			case 'jetpack_network_settings_page':
1038
				$caps = array( 'manage_network_plugins' );
1039
				break;
1040
			case 'jetpack_network_sites_page':
1041
				$caps = array( 'manage_sites' );
1042
				break;
1043
			case 'jetpack_admin_page' :
1044
				if ( Jetpack::is_development_mode() ) {
1045
					$caps = array( 'manage_options' );
1046
					break;
1047
				} else {
1048
					$caps = array( 'read' );
1049
				}
1050
				break;
1051
			case 'jetpack_connect_user' :
1052
				if ( Jetpack::is_development_mode() ) {
1053
					$caps = array( 'do_not_allow' );
1054
					break;
1055
				}
1056
				$caps = array( 'read' );
1057
				break;
1058
		}
1059
		return $caps;
1060
	}
1061
1062
	function require_jetpack_authentication() {
1063
		// Don't let anyone authenticate
1064
		$_COOKIE = array();
1065
		remove_all_filters( 'authenticate' );
1066
		remove_all_actions( 'wp_login_failed' );
1067
1068
		if ( Jetpack::is_active() ) {
1069
			// Allow Jetpack authentication
1070
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1071
		}
1072
	}
1073
1074
	/**
1075
	 * Load language files
1076
	 * @action plugins_loaded
1077
	 */
1078
	public static function plugin_textdomain() {
1079
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1080
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1081
	}
1082
1083
	/**
1084
	 * Register assets for use in various modules and the Jetpack admin page.
1085
	 *
1086
	 * @uses wp_script_is, wp_register_script, plugins_url
1087
	 * @action wp_loaded
1088
	 * @return null
1089
	 */
1090
	public function register_assets() {
1091
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1092
			wp_register_script(
1093
				'spin',
1094
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1095
				false,
1096
				'1.3'
1097
			);
1098
		}
1099
1100
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1101
			wp_register_script(
1102
				'jquery.spin',
1103
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1104
				array( 'jquery', 'spin' ),
1105
				'1.3'
1106
			);
1107
		}
1108
1109 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1110
			wp_register_script(
1111
				'jetpack-gallery-settings',
1112
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1113
				array( 'media-views' ),
1114
				'20121225'
1115
			);
1116
		}
1117
1118
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1119
			wp_register_script(
1120
				'jetpack-twitter-timeline',
1121
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1122
				array( 'jquery' ),
1123
				'4.0.0',
1124
				true
1125
			);
1126
		}
1127
1128
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1129
			wp_register_script(
1130
				'jetpack-facebook-embed',
1131
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1132
				array( 'jquery' ),
1133
				null,
1134
				true
1135
			);
1136
1137
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1138
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1139
			if ( ! is_numeric( $fb_app_id ) ) {
1140
				$fb_app_id = '';
1141
			}
1142
			wp_localize_script(
1143
				'jetpack-facebook-embed',
1144
				'jpfbembed',
1145
				array(
1146
					'appid' => $fb_app_id,
1147
					'locale' => $this->get_locale(),
1148
				)
1149
			);
1150
		}
1151
1152
		/**
1153
		 * As jetpack_register_genericons is by default fired off a hook,
1154
		 * the hook may have already fired by this point.
1155
		 * So, let's just trigger it manually.
1156
		 */
1157
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1158
		jetpack_register_genericons();
1159
1160
		/**
1161
		 * Register the social logos
1162
		 */
1163
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1164
		jetpack_register_social_logos();
1165
1166 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1167
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1168
	}
1169
1170
	/**
1171
	 * Guess locale from language code.
1172
	 *
1173
	 * @param string $lang Language code.
1174
	 * @return string|bool
1175
	 */
1176 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1177
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1178
			return 'en_US';
1179
		}
1180
1181
		if ( ! class_exists( 'GP_Locales' ) ) {
1182
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1183
				return false;
1184
			}
1185
1186
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1187
		}
1188
1189
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1190
			// WP.com: get_locale() returns 'it'
1191
			$locale = GP_Locales::by_slug( $lang );
1192
		} else {
1193
			// Jetpack: get_locale() returns 'it_IT';
1194
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1195
		}
1196
1197
		if ( ! $locale ) {
1198
			return false;
1199
		}
1200
1201
		if ( empty( $locale->facebook_locale ) ) {
1202
			if ( empty( $locale->wp_locale ) ) {
1203
				return false;
1204
			} else {
1205
				// Facebook SDK is smart enough to fall back to en_US if a
1206
				// locale isn't supported. Since supported Facebook locales
1207
				// can fall out of sync, we'll attempt to use the known
1208
				// wp_locale value and rely on said fallback.
1209
				return $locale->wp_locale;
1210
			}
1211
		}
1212
1213
		return $locale->facebook_locale;
1214
	}
1215
1216
	/**
1217
	 * Get the locale.
1218
	 *
1219
	 * @return string|bool
1220
	 */
1221
	function get_locale() {
1222
		$locale = $this->guess_locale_from_lang( get_locale() );
1223
1224
		if ( ! $locale ) {
1225
			$locale = 'en_US';
1226
		}
1227
1228
		return $locale;
1229
	}
1230
1231
	/**
1232
	 * Device Pixels support
1233
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1234
	 */
1235
	function devicepx() {
1236
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1237
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1238
		}
1239
	}
1240
1241
	/**
1242
	 * Return the network_site_url so that .com knows what network this site is a part of.
1243
	 * @param  bool $option
1244
	 * @return string
1245
	 */
1246
	public function jetpack_main_network_site_option( $option ) {
1247
		return network_site_url();
1248
	}
1249
	/**
1250
	 * Network Name.
1251
	 */
1252
	static function network_name( $option = null ) {
1253
		global $current_site;
1254
		return $current_site->site_name;
1255
	}
1256
	/**
1257
	 * Does the network allow new user and site registrations.
1258
	 * @return string
1259
	 */
1260
	static function network_allow_new_registrations( $option = null ) {
1261
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1262
	}
1263
	/**
1264
	 * Does the network allow admins to add new users.
1265
	 * @return boolian
1266
	 */
1267
	static function network_add_new_users( $option = null ) {
1268
		return (bool) get_site_option( 'add_new_users' );
1269
	}
1270
	/**
1271
	 * File upload psace left per site in MB.
1272
	 *  -1 means NO LIMIT.
1273
	 * @return number
1274
	 */
1275
	static function network_site_upload_space( $option = null ) {
1276
		// value in MB
1277
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1278
	}
1279
1280
	/**
1281
	 * Network allowed file types.
1282
	 * @return string
1283
	 */
1284
	static function network_upload_file_types( $option = null ) {
1285
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1286
	}
1287
1288
	/**
1289
	 * Maximum file upload size set by the network.
1290
	 * @return number
1291
	 */
1292
	static function network_max_upload_file_size( $option = null ) {
1293
		// value in KB
1294
		return get_site_option( 'fileupload_maxk', 300 );
1295
	}
1296
1297
	/**
1298
	 * Lets us know if a site allows admins to manage the network.
1299
	 * @return array
1300
	 */
1301
	static function network_enable_administration_menus( $option = null ) {
1302
		return get_site_option( 'menu_items' );
1303
	}
1304
1305
	/**
1306
	 * If a user has been promoted to or demoted from admin, we need to clear the
1307
	 * jetpack_other_linked_admins transient.
1308
	 *
1309
	 * @since 4.3.2
1310
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1311
	 *
1312
	 * @param int    $user_id   The user ID whose role changed.
1313
	 * @param string $role      The new role.
1314
	 * @param array  $old_roles An array of the user's previous roles.
1315
	 */
1316
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1317
		if ( 'administrator' == $role
1318
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1319
			|| is_null( $old_roles )
1320
		) {
1321
			delete_transient( 'jetpack_other_linked_admins' );
1322
		}
1323
	}
1324
1325
	/**
1326
	 * Checks to see if there are any other users available to become primary
1327
	 * Users must both:
1328
	 * - Be linked to wpcom
1329
	 * - Be an admin
1330
	 *
1331
	 * @return mixed False if no other users are linked, Int if there are.
1332
	 */
1333
	static function get_other_linked_admins() {
1334
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1335
1336
		if ( false === $other_linked_users ) {
1337
			$admins = get_users( array( 'role' => 'administrator' ) );
1338
			if ( count( $admins ) > 1 ) {
1339
				$available = array();
1340
				foreach ( $admins as $admin ) {
1341
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1342
						$available[] = $admin->ID;
1343
					}
1344
				}
1345
1346
				$count_connected_admins = count( $available );
1347
				if ( count( $available ) > 1 ) {
1348
					$other_linked_users = $count_connected_admins;
1349
				} else {
1350
					$other_linked_users = 0;
1351
				}
1352
			} else {
1353
				$other_linked_users = 0;
1354
			}
1355
1356
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1357
		}
1358
1359
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1360
	}
1361
1362
	/**
1363
	 * Return whether we are dealing with a multi network setup or not.
1364
	 * The reason we are type casting this is because we want to avoid the situation where
1365
	 * the result is false since when is_main_network_option return false it cases
1366
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1367
	 * database which could be set to anything as opposed to what this function returns.
1368
	 * @param  bool  $option
1369
	 *
1370
	 * @return boolean
1371
	 */
1372
	public function is_main_network_option( $option ) {
1373
		// return '1' or ''
1374
		return (string) (bool) Jetpack::is_multi_network();
1375
	}
1376
1377
	/**
1378
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1379
	 *
1380
	 * @param  string  $option
1381
	 * @return boolean
1382
	 */
1383
	public function is_multisite( $option ) {
1384
		return (string) (bool) is_multisite();
1385
	}
1386
1387
	/**
1388
	 * Implemented since there is no core is multi network function
1389
	 * Right now there is no way to tell if we which network is the dominant network on the system
1390
	 *
1391
	 * @since  3.3
1392
	 * @return boolean
1393
	 */
1394
	public static function is_multi_network() {
1395
		global  $wpdb;
1396
1397
		// if we don't have a multi site setup no need to do any more
1398
		if ( ! is_multisite() ) {
1399
			return false;
1400
		}
1401
1402
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1403
		if ( $num_sites > 1 ) {
1404
			return true;
1405
		} else {
1406
			return false;
1407
		}
1408
	}
1409
1410
	/**
1411
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1412
	 * @return null
1413
	 */
1414
	function update_jetpack_main_network_site_option() {
1415
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1416
	}
1417
	/**
1418
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1419
	 *
1420
	 */
1421
	function update_jetpack_network_settings() {
1422
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1423
		// Only sync this info for the main network site.
1424
	}
1425
1426
	/**
1427
	 * Get back if the current site is single user site.
1428
	 *
1429
	 * @return bool
1430
	 */
1431
	public static function is_single_user_site() {
1432
		global $wpdb;
1433
1434 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1435
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1436
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1437
		}
1438
		return 1 === (int) $some_users;
1439
	}
1440
1441
	/**
1442
	 * Returns true if the site has file write access false otherwise.
1443
	 * @return string ( '1' | '0' )
1444
	 **/
1445
	public static function file_system_write_access() {
1446
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1447
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1448
		}
1449
1450
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1451
1452
		$filesystem_method = get_filesystem_method();
1453
		if ( $filesystem_method === 'direct' ) {
1454
			return 1;
1455
		}
1456
1457
		ob_start();
1458
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1459
		ob_end_clean();
1460
		if ( $filesystem_credentials_are_stored ) {
1461
			return 1;
1462
		}
1463
		return 0;
1464
	}
1465
1466
	/**
1467
	 * Finds out if a site is using a version control system.
1468
	 * @return string ( '1' | '0' )
1469
	 **/
1470
	public static function is_version_controlled() {
1471
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1472
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1473
	}
1474
1475
	/**
1476
	 * Determines whether the current theme supports featured images or not.
1477
	 * @return string ( '1' | '0' )
1478
	 */
1479
	public static function featured_images_enabled() {
1480
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1481
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1482
	}
1483
1484
	/**
1485
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1486
	 *
1487
	 * @deprecated 4.7 use get_avatar_url instead.
1488
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1489
	 * @param int $size Size of the avatar image
1490
	 * @param string $default URL to a default image to use if no avatar is available
1491
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1492
	 *
1493
	 * @return array
1494
	 */
1495
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1496
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1497
		return get_avatar_url( $id_or_email, array(
1498
			'size' => $size,
1499
			'default' => $default,
1500
			'force_default' => $force_display,
1501
		) );
1502
	}
1503
1504
	/**
1505
	 * jetpack_updates is saved in the following schema:
1506
	 *
1507
	 * array (
1508
	 *      'plugins'                       => (int) Number of plugin updates available.
1509
	 *      'themes'                        => (int) Number of theme updates available.
1510
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1511
	 *      'translations'                  => (int) Number of translation updates available.
1512
	 *      'total'                         => (int) Total of all available updates.
1513
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1514
	 * )
1515
	 * @return array
1516
	 */
1517
	public static function get_updates() {
1518
		$update_data = wp_get_update_data();
1519
1520
		// Stores the individual update counts as well as the total count.
1521
		if ( isset( $update_data['counts'] ) ) {
1522
			$updates = $update_data['counts'];
1523
		}
1524
1525
		// If we need to update WordPress core, let's find the latest version number.
1526 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1527
			$cur = get_preferred_from_update_core();
1528
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1529
				$updates['wp_update_version'] = $cur->current;
1530
			}
1531
		}
1532
		return isset( $updates ) ? $updates : array();
1533
	}
1534
1535
	public static function get_update_details() {
1536
		$update_details = array(
1537
			'update_core' => get_site_transient( 'update_core' ),
1538
			'update_plugins' => get_site_transient( 'update_plugins' ),
1539
			'update_themes' => get_site_transient( 'update_themes' ),
1540
		);
1541
		return $update_details;
1542
	}
1543
1544
	public static function refresh_update_data() {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1546
1547
	}
1548
1549
	public static function refresh_theme_data() {
1550
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1551
	}
1552
1553
	/**
1554
	 * Is Jetpack active?
1555
	 */
1556
	public static function is_active() {
1557
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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...
1558
	}
1559
1560
	/**
1561
	 * Make an API call to WordPress.com for plan status
1562
	 *
1563
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1564
	 *
1565
	 * @return bool True if plan is updated, false if no update
1566
	 */
1567
	public static function refresh_active_plan_from_wpcom() {
1568
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1569
		return Jetpack_Plan::refresh_from_wpcom();
1570
	}
1571
1572
	/**
1573
	 * Get the plan that this Jetpack site is currently using
1574
	 *
1575
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1576
	 * @return array Active Jetpack plan details.
1577
	 */
1578
	public static function get_active_plan() {
1579
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1580
		return Jetpack_Plan::get();
1581
	}
1582
1583
	/**
1584
	 * Determine whether the active plan supports a particular feature
1585
	 *
1586
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1587
	 * @return bool True if plan supports feature, false if not.
1588
	 */
1589
	public static function active_plan_supports( $feature ) {
1590
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1591
		return Jetpack_Plan::supports( $feature );
1592
	}
1593
1594
	/**
1595
	 * Is Jetpack in development (offline) mode?
1596
	 */
1597
	public static function is_development_mode() {
1598
		$development_mode = false;
1599
1600
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1601
			$development_mode = JETPACK_DEV_DEBUG;
1602
		} elseif ( $site_url = site_url() ) {
1603
			$development_mode = false === strpos( $site_url, '.' );
1604
		}
1605
1606
		/**
1607
		 * Filters Jetpack's development mode.
1608
		 *
1609
		 * @see https://jetpack.com/support/development-mode/
1610
		 *
1611
		 * @since 2.2.1
1612
		 *
1613
		 * @param bool $development_mode Is Jetpack's development mode active.
1614
		 */
1615
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1616
		return $development_mode;
1617
	}
1618
1619
	/**
1620
	 * Whether the site is currently onboarding or not.
1621
	 * A site is considered as being onboarded if it currently has an onboarding token.
1622
	 *
1623
	 * @since 5.8
1624
	 *
1625
	 * @access public
1626
	 * @static
1627
	 *
1628
	 * @return bool True if the site is currently onboarding, false otherwise
1629
	 */
1630
	public static function is_onboarding() {
1631
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1632
	}
1633
1634
	/**
1635
	 * Determines reason for Jetpack development mode.
1636
	 */
1637
	public static function development_mode_trigger_text() {
1638
		if ( ! Jetpack::is_development_mode() ) {
1639
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1640
		}
1641
1642
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1643
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1644
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1645
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1646
		} else {
1647
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1648
		}
1649
1650
		return $notice;
1651
1652
	}
1653
	/**
1654
	* Get Jetpack development mode notice text and notice class.
1655
	*
1656
	* Mirrors the checks made in Jetpack::is_development_mode
1657
	*
1658
	*/
1659
	public static function show_development_mode_notice() {
1660 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1661
			$notice = sprintf(
1662
			/* translators: %s is a URL */
1663
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1664
				'https://jetpack.com/support/development-mode/'
1665
			);
1666
1667
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1668
1669
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1670
		}
1671
1672
		// Throw up a notice if using a development version and as for feedback.
1673
		if ( Jetpack::is_development_version() ) {
1674
			/* translators: %s is a URL */
1675
			$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/' );
1676
1677
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1678
		}
1679
		// Throw up a notice if using staging mode
1680
		if ( Jetpack::is_staging_site() ) {
1681
			/* translators: %s is a URL */
1682
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1683
1684
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1685
		}
1686
	}
1687
1688
	/**
1689
	 * Whether Jetpack's version maps to a public release, or a development version.
1690
	 */
1691
	public static function is_development_version() {
1692
		/**
1693
		 * Allows filtering whether this is a development version of Jetpack.
1694
		 *
1695
		 * This filter is especially useful for tests.
1696
		 *
1697
		 * @since 4.3.0
1698
		 *
1699
		 * @param bool $development_version Is this a develoment version of Jetpack?
1700
		 */
1701
		return (bool) apply_filters(
1702
			'jetpack_development_version',
1703
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1704
		);
1705
	}
1706
1707
	/**
1708
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1709
	 */
1710
	public static function is_user_connected( $user_id = false ) {
1711
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1712
		if ( ! $user_id ) {
1713
			return false;
1714
		}
1715
1716
		return (bool) Jetpack_Data::get_access_token( $user_id );
1717
	}
1718
1719
	/**
1720
	 * Get the wpcom user data of the current|specified connected user.
1721
	 */
1722
	public static function get_connected_user_data( $user_id = null ) {
1723
		if ( ! $user_id ) {
1724
			$user_id = get_current_user_id();
1725
		}
1726
1727
		$transient_key = "jetpack_connected_user_data_$user_id";
1728
1729
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1730
			return $cached_user_data;
1731
		}
1732
1733
		Jetpack::load_xml_rpc_client();
1734
		$xml = new Jetpack_IXR_Client( array(
1735
			'user_id' => $user_id,
1736
		) );
1737
		$xml->query( 'wpcom.getUser' );
1738
		if ( ! $xml->isError() ) {
1739
			$user_data = $xml->getResponse();
1740
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1741
			return $user_data;
1742
		}
1743
1744
		return false;
1745
	}
1746
1747
	/**
1748
	 * Get the wpcom email of the current|specified connected user.
1749
	 */
1750 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1751
		if ( ! $user_id ) {
1752
			$user_id = get_current_user_id();
1753
		}
1754
		Jetpack::load_xml_rpc_client();
1755
		$xml = new Jetpack_IXR_Client( array(
1756
			'user_id' => $user_id,
1757
		) );
1758
		$xml->query( 'wpcom.getUserEmail' );
1759
		if ( ! $xml->isError() ) {
1760
			return $xml->getResponse();
1761
		}
1762
		return false;
1763
	}
1764
1765
	/**
1766
	 * Get the wpcom email of the master user.
1767
	 */
1768
	public static function get_master_user_email() {
1769
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1770
		if ( $master_user_id ) {
1771
			return self::get_connected_user_email( $master_user_id );
1772
		}
1773
		return '';
1774
	}
1775
1776
	function current_user_is_connection_owner() {
1777
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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...
1778
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1779
	}
1780
1781
	/**
1782
	 * Gets current user IP address.
1783
	 *
1784
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1785
	 *
1786
	 * @return string                  Current user IP address.
1787
	 */
1788
	public static function current_user_ip( $check_all_headers = false ) {
1789
		if ( $check_all_headers ) {
1790
			foreach ( array(
1791
				'HTTP_CF_CONNECTING_IP',
1792
				'HTTP_CLIENT_IP',
1793
				'HTTP_X_FORWARDED_FOR',
1794
				'HTTP_X_FORWARDED',
1795
				'HTTP_X_CLUSTER_CLIENT_IP',
1796
				'HTTP_FORWARDED_FOR',
1797
				'HTTP_FORWARDED',
1798
				'HTTP_VIA',
1799
			) as $key ) {
1800
				if ( ! empty( $_SERVER[ $key ] ) ) {
1801
					return $_SERVER[ $key ];
1802
				}
1803
			}
1804
		}
1805
1806
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1807
	}
1808
1809
	/**
1810
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1811
	 */
1812
	function extra_oembed_providers() {
1813
		// Cloudup: https://dev.cloudup.com/#oembed
1814
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1815
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1816
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1817
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1818
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1819
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1820
	}
1821
1822
	/**
1823
	 * Synchronize connected user role changes
1824
	 */
1825
	function user_role_change( $user_id ) {
1826
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1827
		Jetpack_Sync_Users::user_role_change( $user_id );
1828
	}
1829
1830
	/**
1831
	 * Loads the private module if it has been activated.
1832
	 * Else, updates the admin dashboard with the site's private status.
1833
	 */
1834
	public static function load_private() {
1835
		if ( self::is_module_active( 'private' ) ) {
1836
			self::load_modules( array( 'private' ) );
1837
		} else {
1838
			add_action( 'update_right_now_text', array( __CLASS__, 'add_public_dashboard_glance_items' ) );
1839
			add_action( 'admin_enqueue_scripts', array( __CLASS__, 'wp_admin_glance_dashboard_style' ) );
1840
			add_filter( 'privacy_on_link_text', array( __CLASS__, 'private_site_privacy_on_link_text' ) );
1841
		}
1842
	}
1843
1844
	/**
1845
	 * Adds a line break for the 'Search Engines Discouraged' message
1846
	 * displayed in the 'At a Glance' dashboard widget.
1847
	 *
1848
	 * @param string $content Content of 'At A Glance' wp-admin dashboard widget.
1849
	 * @return string The modified content of the 'At a Glance' dashboard widget.
1850
	 */
1851
1852
	public static function private_site_privacy_on_link_text( $content ) {
1853
		return '<br>' . $content;
1854
	}
1855
1856
	/**
1857
	 * Basic styling for the wp-admin 'At a Glance' dashboard widget.
1858
	 * This is applied when the private module is inactive.
1859
	 *
1860
	 * @param string $hook Page Hook Suffix for the current page.
1861
	 */
1862
	public static function wp_admin_glance_dashboard_style( $hook ) {
1863
		if ( 'index.php' !== $hook ) {
1864
			return;
1865
		}
1866
1867
		$custom_css = '
1868
			.jp-at-a-glance__site-public {
1869
				color: #46B450;
1870
			}
1871
		';
1872
		wp_add_inline_style( 'dashboard', $custom_css );
1873
	}
1874
1875
	/**
1876
	 * Adds a message to the 'At a Glance' dashboard widget.
1877
	 *
1878
	 * @param string $content Content of 'At A Glance' wp-admin dashboard widget.
1879
	 * @return string The modified content of the 'At a Glance' dashboard widget.
1880
	 */
1881 View Code Duplication
	public static function add_public_dashboard_glance_items( $content ) {
1882
		return
1883
			$content .
1884
			'<br><br>' .
1885
			wp_kses(
1886
				sprintf(
1887
					/* translators: URL for Jetpack dashboard. */
1888
					__( '<span class="%1$1s">This site is set to public.</span> <a href="%2$2s">Make private</a>.', 'jetpack' ),
1889
					esc_attr( 'jp-at-a-glance__site-public' ),
1890
					esc_url( admin_url( 'admin.php?page=jetpack#/security?term=private' ) )
1891
				),
1892
				array(
1893
					'a' => array( 'href' => true ),
1894
					'span' => array( 'class' => true ),
1895
				)
1896
			);
1897
	}
1898
1899
	/**
1900
	 * Loads modules from given array, otherwise all the currently active modules.
1901
	 *
1902
	 * @param array $modules Specific modules to be loaded.
1903
	 */
1904
	public static function load_modules( $modules = array() ) {
1905
		if (
1906
			! self::is_active()
1907
			&& ! self::is_development_mode()
1908
			&& ! self::is_onboarding()
1909
			&& (
1910
				! is_multisite()
1911
				|| ! get_site_option( 'jetpack_protect_active' )
1912
			)
1913
		) {
1914
			return;
1915
		}
1916
1917
		$version = Jetpack_Options::get_option( 'version' );
1918 View Code Duplication
		if ( ! $version ) {
1919
			$version = $old_version = JETPACK__VERSION . ':' . time();
1920
			/** This action is documented in class.jetpack.php */
1921
			do_action( 'updating_jetpack_version', $version, false );
1922
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1923
		}
1924
		list( $version )            = explode( ':', $version );
1925
		$fetched_all_active_modules = false;
1926
1927
		if ( empty( $modules ) ) {
1928
			$modules                    = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1929
			$fetched_all_active_modules = true;
1930
		}
1931
1932
		$modules_data = array();
1933
1934
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1935
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1936
			$updated_modules = array();
1937
			foreach ( $modules as $module ) {
1938
				$modules_data[ $module ] = Jetpack::get_module( $module );
1939
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1940
					continue;
1941
				}
1942
1943
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1944
					continue;
1945
				}
1946
1947
				$updated_modules[] = $module;
1948
			}
1949
1950
			$modules = array_diff( $modules, $updated_modules );
1951
		}
1952
1953
		$is_development_mode = Jetpack::is_development_mode();
1954
1955
		foreach ( $modules as $index => $module ) {
1956
			// If we're in dev mode, disable modules requiring a connection
1957
			if ( $is_development_mode ) {
1958
				// Prime the pump if we need to
1959
				if ( empty( $modules_data[ $module ] ) ) {
1960
					$modules_data[ $module ] = Jetpack::get_module( $module );
1961
				}
1962
				// If the module requires a connection, but we're in local mode, don't include it.
1963
				if ( $modules_data[ $module ]['requires_connection'] ) {
1964
					continue;
1965
				}
1966
			}
1967
1968
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1969
				continue;
1970
			}
1971
1972
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1973
				unset( $modules[ $index ] );
1974
				self::update_active_modules( array_values( $modules ) );
1975
				continue;
1976
			}
1977
1978
			/**
1979
			 * Fires when a specific module is loaded.
1980
			 * The dynamic part of the hook, $module, is the module slug.
1981
			 *
1982
			 * @since 1.1.0
1983
			 */
1984
			do_action( 'jetpack_module_loaded_' . $module );
1985
		}
1986
1987
		if ( $fetched_all_active_modules ) {
1988
			/**
1989
			* Fires when all the modules are loaded.
1990
			*
1991
			* @since 1.1.0
1992
			*/
1993
			do_action( 'jetpack_modules_loaded' );
1994
		}
1995
1996
		// 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.
1997
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1998
	}
1999
2000
	/**
2001
	 * Check if Jetpack's REST API compat file should be included
2002
	 * @action plugins_loaded
2003
	 * @return null
2004
	 */
2005
	public function check_rest_api_compat() {
2006
		/**
2007
		 * Filters the list of REST API compat files to be included.
2008
		 *
2009
		 * @since 2.2.5
2010
		 *
2011
		 * @param array $args Array of REST API compat files to include.
2012
		 */
2013
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2014
2015
		if ( function_exists( 'bbpress' ) )
2016
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
2017
2018
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
2019
			require_once $_jetpack_rest_api_compat_include;
2020
	}
2021
2022
	/**
2023
	 * Gets all plugins currently active in values, regardless of whether they're
2024
	 * traditionally activated or network activated.
2025
	 *
2026
	 * @todo Store the result in core's object cache maybe?
2027
	 */
2028
	public static function get_active_plugins() {
2029
		$active_plugins = (array) get_option( 'active_plugins', array() );
2030
2031
		if ( is_multisite() ) {
2032
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2033
			// whereas active_plugins stores them in the values.
2034
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2035
			if ( $network_plugins ) {
2036
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2037
			}
2038
		}
2039
2040
		sort( $active_plugins );
2041
2042
		return array_unique( $active_plugins );
2043
	}
2044
2045
	/**
2046
	 * Gets and parses additional plugin data to send with the heartbeat data
2047
	 *
2048
	 * @since 3.8.1
2049
	 *
2050
	 * @return array Array of plugin data
2051
	 */
2052
	public static function get_parsed_plugin_data() {
2053
		if ( ! function_exists( 'get_plugins' ) ) {
2054
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
2055
		}
2056
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2057
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2058
		$active_plugins = Jetpack::get_active_plugins();
2059
2060
		$plugins = array();
2061
		foreach ( $all_plugins as $path => $plugin_data ) {
2062
			$plugins[ $path ] = array(
2063
					'is_active' => in_array( $path, $active_plugins ),
2064
					'file'      => $path,
2065
					'name'      => $plugin_data['Name'],
2066
					'version'   => $plugin_data['Version'],
2067
					'author'    => $plugin_data['Author'],
2068
			);
2069
		}
2070
2071
		return $plugins;
2072
	}
2073
2074
	/**
2075
	 * Gets and parses theme data to send with the heartbeat data
2076
	 *
2077
	 * @since 3.8.1
2078
	 *
2079
	 * @return array Array of theme data
2080
	 */
2081
	public static function get_parsed_theme_data() {
2082
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2083
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2084
2085
		$themes = array();
2086
		foreach ( $all_themes as $slug => $theme_data ) {
2087
			$theme_headers = array();
2088
			foreach ( $header_keys as $header_key ) {
2089
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2090
			}
2091
2092
			$themes[ $slug ] = array(
2093
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2094
					'slug' => $slug,
2095
					'theme_root' => $theme_data->get_theme_root_uri(),
2096
					'parent' => $theme_data->parent(),
2097
					'headers' => $theme_headers
2098
			);
2099
		}
2100
2101
		return $themes;
2102
	}
2103
2104
	/**
2105
	 * Checks whether a specific plugin is active.
2106
	 *
2107
	 * We don't want to store these in a static variable, in case
2108
	 * there are switch_to_blog() calls involved.
2109
	 */
2110
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2111
		return in_array( $plugin, self::get_active_plugins() );
2112
	}
2113
2114
	/**
2115
	 * Check if Jetpack's Open Graph tags should be used.
2116
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2117
	 *
2118
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2119
	 * @action plugins_loaded
2120
	 * @return null
2121
	 */
2122
	public function check_open_graph() {
2123
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2124
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2125
		}
2126
2127
		$active_plugins = self::get_active_plugins();
2128
2129
		if ( ! empty( $active_plugins ) ) {
2130
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2131
				if ( in_array( $plugin, $active_plugins ) ) {
2132
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2133
					break;
2134
				}
2135
			}
2136
		}
2137
2138
		/**
2139
		 * Allow the addition of Open Graph Meta Tags to all pages.
2140
		 *
2141
		 * @since 2.0.3
2142
		 *
2143
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2144
		 */
2145
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2146
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2147
		}
2148
	}
2149
2150
	/**
2151
	 * Check if Jetpack's Twitter tags should be used.
2152
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2153
	 *
2154
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2155
	 * @action plugins_loaded
2156
	 * @return null
2157
	 */
2158
	public function check_twitter_tags() {
2159
2160
		$active_plugins = self::get_active_plugins();
2161
2162
		if ( ! empty( $active_plugins ) ) {
2163
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2164
				if ( in_array( $plugin, $active_plugins ) ) {
2165
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2166
					break;
2167
				}
2168
			}
2169
		}
2170
2171
		/**
2172
		 * Allow Twitter Card Meta tags to be disabled.
2173
		 *
2174
		 * @since 2.6.0
2175
		 *
2176
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2177
		 */
2178
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2179
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2180
		}
2181
	}
2182
2183
	/**
2184
	 * Allows plugins to submit security reports.
2185
 	 *
2186
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2187
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2188
	 * @param array   $args         See definitions above
2189
	 */
2190
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2191
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2192
	}
2193
2194
/* Jetpack Options API */
2195
2196
	public static function get_option_names( $type = 'compact' ) {
2197
		return Jetpack_Options::get_option_names( $type );
2198
	}
2199
2200
	/**
2201
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2202
 	 *
2203
	 * @param string $name    Option name
2204
	 * @param mixed  $default (optional)
2205
	 */
2206
	public static function get_option( $name, $default = false ) {
2207
		return Jetpack_Options::get_option( $name, $default );
2208
	}
2209
2210
	/**
2211
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2212
 	 *
2213
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2214
	 * @param string $name  Option name
2215
	 * @param mixed  $value Option value
2216
	 */
2217
	public static function update_option( $name, $value ) {
2218
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2219
		return Jetpack_Options::update_option( $name, $value );
2220
	}
2221
2222
	/**
2223
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2224
 	 *
2225
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2226
	 * @param array $array array( option name => option value, ... )
2227
	 */
2228
	public static function update_options( $array ) {
2229
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2230
		return Jetpack_Options::update_options( $array );
2231
	}
2232
2233
	/**
2234
	 * Deletes the given option.  May be passed multiple option names as an array.
2235
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2236
	 *
2237
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2238
	 * @param string|array $names
2239
	 */
2240
	public static function delete_option( $names ) {
2241
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2242
		return Jetpack_Options::delete_option( $names );
2243
	}
2244
2245
	/**
2246
	 * Enters a user token into the user_tokens option
2247
	 *
2248
	 * @param int $user_id
2249
	 * @param string $token
2250
	 * return bool
2251
	 */
2252
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2253
		// not designed for concurrent updates
2254
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2255
		if ( ! is_array( $user_tokens ) )
2256
			$user_tokens = array();
2257
		$user_tokens[$user_id] = $token;
2258
		if ( $is_master_user ) {
2259
			$master_user = $user_id;
2260
			$options     = compact( 'user_tokens', 'master_user' );
2261
		} else {
2262
			$options = compact( 'user_tokens' );
2263
		}
2264
		return Jetpack_Options::update_options( $options );
2265
	}
2266
2267
	/**
2268
	 * Returns an array of all PHP files in the specified absolute path.
2269
	 * Equivalent to glob( "$absolute_path/*.php" ).
2270
	 *
2271
	 * @param string $absolute_path The absolute path of the directory to search.
2272
	 * @return array Array of absolute paths to the PHP files.
2273
	 */
2274
	public static function glob_php( $absolute_path ) {
2275
		if ( function_exists( 'glob' ) ) {
2276
			return glob( "$absolute_path/*.php" );
2277
		}
2278
2279
		$absolute_path = untrailingslashit( $absolute_path );
2280
		$files = array();
2281
		if ( ! $dir = @opendir( $absolute_path ) ) {
2282
			return $files;
2283
		}
2284
2285
		while ( false !== $file = readdir( $dir ) ) {
2286
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2287
				continue;
2288
			}
2289
2290
			$file = "$absolute_path/$file";
2291
2292
			if ( ! is_file( $file ) ) {
2293
				continue;
2294
			}
2295
2296
			$files[] = $file;
2297
		}
2298
2299
		closedir( $dir );
2300
2301
		return $files;
2302
	}
2303
2304
	public static function activate_new_modules( $redirect = false ) {
2305
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2306
			return;
2307
		}
2308
2309
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2310 View Code Duplication
		if ( ! $jetpack_old_version ) {
2311
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2312
			/** This action is documented in class.jetpack.php */
2313
			do_action( 'updating_jetpack_version', $version, false );
2314
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2315
		}
2316
2317
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2318
2319
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2320
			return;
2321
		}
2322
2323
		$active_modules     = Jetpack::get_active_modules();
2324
		$reactivate_modules = array();
2325
		foreach ( $active_modules as $active_module ) {
2326
			$module = Jetpack::get_module( $active_module );
2327
			if ( ! isset( $module['changed'] ) ) {
2328
				continue;
2329
			}
2330
2331
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2332
				continue;
2333
			}
2334
2335
			$reactivate_modules[] = $active_module;
2336
			Jetpack::deactivate_module( $active_module );
2337
		}
2338
2339
		$new_version = JETPACK__VERSION . ':' . time();
2340
		/** This action is documented in class.jetpack.php */
2341
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2342
		Jetpack_Options::update_options(
2343
			array(
2344
				'version'     => $new_version,
2345
				'old_version' => $jetpack_old_version,
2346
			)
2347
		);
2348
2349
		Jetpack::state( 'message', 'modules_activated' );
2350
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2351
2352
		if ( $redirect ) {
2353
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2354
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2355
				$page = $_GET['page'];
2356
			}
2357
2358
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2359
			exit;
2360
		}
2361
	}
2362
2363
	/**
2364
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2365
	 * Make sure to tuck away module "library" files in a sub-directory.
2366
	 */
2367
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2368
		static $modules = null;
2369
2370
		if ( ! isset( $modules ) ) {
2371
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2372
			// Use the cache if we're on the front-end and it's available...
2373
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2374
				$modules = $available_modules_option[ JETPACK__VERSION ];
2375
			} else {
2376
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2377
2378
				$modules = array();
2379
2380
				foreach ( $files as $file ) {
2381
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2382
						continue;
2383
					}
2384
2385
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2386
				}
2387
2388
				Jetpack_Options::update_option( 'available_modules', array(
2389
					JETPACK__VERSION => $modules,
2390
				) );
2391
			}
2392
		}
2393
2394
		/**
2395
		 * Filters the array of modules available to be activated.
2396
		 *
2397
		 * @since 2.4.0
2398
		 *
2399
		 * @param array $modules Array of available modules.
2400
		 * @param string $min_version Minimum version number required to use modules.
2401
		 * @param string $max_version Maximum version number required to use modules.
2402
		 */
2403
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2404
2405
		if ( ! $min_version && ! $max_version ) {
2406
			return array_keys( $mods );
2407
		}
2408
2409
		$r = array();
2410
		foreach ( $mods as $slug => $introduced ) {
2411
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2412
				continue;
2413
			}
2414
2415
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2416
				continue;
2417
			}
2418
2419
			$r[] = $slug;
2420
		}
2421
2422
		return $r;
2423
	}
2424
2425
	/**
2426
	 * Default modules loaded on activation.
2427
	 */
2428
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2429
		$return = array();
2430
2431
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2432
			$module_data = Jetpack::get_module( $module );
2433
2434
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2435
				case 'yes' :
2436
					$return[] = $module;
2437
					break;
2438
				case 'public' :
2439
					if ( Jetpack_Options::get_option( 'public' ) ) {
2440
						$return[] = $module;
2441
					}
2442
					break;
2443
				case 'no' :
2444
				default :
2445
					break;
2446
			}
2447
		}
2448
		/**
2449
		 * Filters the array of default modules.
2450
		 *
2451
		 * @since 2.5.0
2452
		 *
2453
		 * @param array $return Array of default modules.
2454
		 * @param string $min_version Minimum version number required to use modules.
2455
		 * @param string $max_version Maximum version number required to use modules.
2456
		 */
2457
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2458
	}
2459
2460
	/**
2461
	 * Checks activated modules during auto-activation to determine
2462
	 * if any of those modules are being deprecated.  If so, close
2463
	 * them out, and add any replacement modules.
2464
	 *
2465
	 * Runs at priority 99 by default.
2466
	 *
2467
	 * This is run late, so that it can still activate a module if
2468
	 * the new module is a replacement for another that the user
2469
	 * currently has active, even if something at the normal priority
2470
	 * would kibosh everything.
2471
	 *
2472
	 * @since 2.6
2473
	 * @uses jetpack_get_default_modules filter
2474
	 * @param array $modules
2475
	 * @return array
2476
	 */
2477
	function handle_deprecated_modules( $modules ) {
2478
		$deprecated_modules = array(
2479
			'debug'            => null,  // Closed out and moved to the debugger library.
2480
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2481
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2482
		);
2483
2484
		// Don't activate SSO if they never completed activating WPCC.
2485
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2486
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2487
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2488
				$deprecated_modules['wpcc'] = null;
2489
			}
2490
		}
2491
2492
		foreach ( $deprecated_modules as $module => $replacement ) {
2493
			if ( Jetpack::is_module_active( $module ) ) {
2494
				self::deactivate_module( $module );
2495
				if ( $replacement ) {
2496
					$modules[] = $replacement;
2497
				}
2498
			}
2499
		}
2500
2501
		return array_unique( $modules );
2502
	}
2503
2504
	/**
2505
	 * Checks activated plugins during auto-activation to determine
2506
	 * if any of those plugins are in the list with a corresponding module
2507
	 * that is not compatible with the plugin. The module will not be allowed
2508
	 * to auto-activate.
2509
	 *
2510
	 * @since 2.6
2511
	 * @uses jetpack_get_default_modules filter
2512
	 * @param array $modules
2513
	 * @return array
2514
	 */
2515
	function filter_default_modules( $modules ) {
2516
2517
		$active_plugins = self::get_active_plugins();
2518
2519
		if ( ! empty( $active_plugins ) ) {
2520
2521
			// For each module we'd like to auto-activate...
2522
			foreach ( $modules as $key => $module ) {
2523
				// If there are potential conflicts for it...
2524
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2525
					// For each potential conflict...
2526
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2527
						// If that conflicting plugin is active...
2528
						if ( in_array( $plugin, $active_plugins ) ) {
2529
							// Remove that item from being auto-activated.
2530
							unset( $modules[ $key ] );
2531
						}
2532
					}
2533
				}
2534
			}
2535
		}
2536
2537
		return $modules;
2538
	}
2539
2540
	/**
2541
	 * Extract a module's slug from its full path.
2542
	 */
2543
	public static function get_module_slug( $file ) {
2544
		return str_replace( '.php', '', basename( $file ) );
2545
	}
2546
2547
	/**
2548
	 * Generate a module's path from its slug.
2549
	 */
2550
	public static function get_module_path( $slug ) {
2551
		/**
2552
		 * Filters the path of a modules.
2553
		 *
2554
		 * @since 7.4.0
2555
		 *
2556
		 * @param array $return The absolute path to a module's root php file
2557
		 * @param string $slug The module slug
2558
		 */
2559
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2560
	}
2561
2562
	/**
2563
	 * Load module data from module file. Headers differ from WordPress
2564
	 * plugin headers to avoid them being identified as standalone
2565
	 * plugins on the WordPress plugins page.
2566
	 */
2567
	public static function get_module( $module ) {
2568
		$headers = array(
2569
			'name'                      => 'Module Name',
2570
			'description'               => 'Module Description',
2571
			'jumpstart_desc'            => 'Jumpstart Description',
2572
			'sort'                      => 'Sort Order',
2573
			'recommendation_order'      => 'Recommendation Order',
2574
			'introduced'                => 'First Introduced',
2575
			'changed'                   => 'Major Changes In',
2576
			'deactivate'                => 'Deactivate',
2577
			'free'                      => 'Free',
2578
			'requires_connection'       => 'Requires Connection',
2579
			'auto_activate'             => 'Auto Activate',
2580
			'module_tags'               => 'Module Tags',
2581
			'feature'                   => 'Feature',
2582
			'additional_search_queries' => 'Additional Search Queries',
2583
			'plan_classes'              => 'Plans',
2584
		);
2585
2586
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2587
2588
		$mod = Jetpack::get_file_data( $file, $headers );
2589
		if ( empty( $mod['name'] ) ) {
2590
			return false;
2591
		}
2592
2593
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2594
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2595
		$mod['deactivate']              = empty( $mod['deactivate'] );
2596
		$mod['free']                    = empty( $mod['free'] );
2597
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2598
2599
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2600
			$mod['auto_activate'] = 'No';
2601
		} else {
2602
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2603
		}
2604
2605
		if ( $mod['module_tags'] ) {
2606
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2607
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2608
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2609
		} else {
2610
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2611
		}
2612
2613 View Code Duplication
		if ( $mod['plan_classes'] ) {
2614
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2615
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2616
		} else {
2617
			$mod['plan_classes'] = array( 'free' );
2618
		}
2619
2620 View Code Duplication
		if ( $mod['feature'] ) {
2621
			$mod['feature'] = explode( ',', $mod['feature'] );
2622
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2623
		} else {
2624
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2625
		}
2626
2627
		/**
2628
		 * Filters the feature array on a module.
2629
		 *
2630
		 * This filter allows you to control where each module is filtered: Recommended,
2631
		 * Jumpstart, and the default "Other" listing.
2632
		 *
2633
		 * @since 3.5.0
2634
		 *
2635
		 * @param array   $mod['feature'] The areas to feature this module:
2636
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2637
		 *     'Recommended' shows on the main Jetpack admin screen.
2638
		 *     'Other' should be the default if no other value is in the array.
2639
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2640
		 * @param array   $mod All the currently assembled module data.
2641
		 */
2642
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2643
2644
		/**
2645
		 * Filter the returned data about a module.
2646
		 *
2647
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2648
		 * so please be careful.
2649
		 *
2650
		 * @since 3.6.0
2651
		 *
2652
		 * @param array   $mod    The details of the requested module.
2653
		 * @param string  $module The slug of the module, e.g. sharedaddy
2654
		 * @param string  $file   The path to the module source file.
2655
		 */
2656
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2657
	}
2658
2659
	/**
2660
	 * Like core's get_file_data implementation, but caches the result.
2661
	 */
2662
	public static function get_file_data( $file, $headers ) {
2663
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2664
		$file_name = basename( $file );
2665
2666
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2667
2668
		$file_data_option = get_transient( $cache_key );
2669
2670
		if ( false === $file_data_option ) {
2671
			$file_data_option = array();
2672
		}
2673
2674
		$key           = md5( $file_name . serialize( $headers ) );
2675
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2676
2677
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2678
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2679
			return $file_data_option[ $key ];
2680
		}
2681
2682
		$data = get_file_data( $file, $headers );
2683
2684
		$file_data_option[ $key ] = $data;
2685
2686
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2687
2688
		return $data;
2689
	}
2690
2691
2692
	/**
2693
	 * Return translated module tag.
2694
	 *
2695
	 * @param string $tag Tag as it appears in each module heading.
2696
	 *
2697
	 * @return mixed
2698
	 */
2699
	public static function translate_module_tag( $tag ) {
2700
		return jetpack_get_module_i18n_tag( $tag );
2701
	}
2702
2703
	/**
2704
	 * Get i18n strings as a JSON-encoded string
2705
	 *
2706
	 * @return string The locale as JSON
2707
	 */
2708
	public static function get_i18n_data_json() {
2709
2710
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2711
		// JSON files with the file they should be included for. This is an md5
2712
		// of '_inc/build/admin.js'.
2713
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2714
2715
		$i18n_json =
2716
				   JETPACK__PLUGIN_DIR
2717
				   . 'languages/json/jetpack-'
2718
				   . get_user_locale()
2719
				   . '-'
2720
				   . $path_md5
2721
				   . '.json';
2722
2723
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2724
			$locale_data = @file_get_contents( $i18n_json );
2725
			if ( $locale_data ) {
2726
				return $locale_data;
2727
			}
2728
		}
2729
2730
		// Return valid empty Jed locale
2731
		return '{ "locale_data": { "messages": { "": {} } } }';
2732
	}
2733
2734
	/**
2735
	 * Add locale data setup to wp-i18n
2736
	 *
2737
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2738
	 *
2739
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2740
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2741
	 *
2742
	 * This method provides a safe way to request the setup multiple times but add the script at
2743
	 * most once.
2744
	 *
2745
	 * @since 6.7.0
2746
	 *
2747
	 * @return void
2748
	 */
2749
	public static function setup_wp_i18n_locale_data() {
2750
		static $script_added = false;
2751
		if ( ! $script_added ) {
2752
			$script_added = true;
2753
			wp_add_inline_script(
2754
				'wp-i18n',
2755
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2756
			);
2757
		}
2758
	}
2759
2760
	/**
2761
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2762
	 *
2763
	 * @since 3.9.2
2764
	 *
2765
	 * @param array $modules
2766
	 *
2767
	 * @return string|void
2768
	 */
2769
	public static function get_translated_modules( $modules ) {
2770
		foreach ( $modules as $index => $module ) {
2771
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2772
			if ( isset( $module['name'] ) ) {
2773
				$modules[ $index ]['name'] = $i18n_module['name'];
2774
			}
2775
			if ( isset( $module['description'] ) ) {
2776
				$modules[ $index ]['description'] = $i18n_module['description'];
2777
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2778
			}
2779
		}
2780
		return $modules;
2781
	}
2782
2783
	/**
2784
	 * Get a list of activated modules as an array of module slugs.
2785
	 */
2786
	public static function get_active_modules() {
2787
		$active = Jetpack_Options::get_option( 'active_modules' );
2788
2789
		if ( ! is_array( $active ) ) {
2790
			$active = array();
2791
		}
2792
2793
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2794
			$active[] = 'vaultpress';
2795
		} else {
2796
			$active = array_diff( $active, array( 'vaultpress' ) );
2797
		}
2798
2799
		//If protect is active on the main site of a multisite, it should be active on all sites.
2800
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2801
			$active[] = 'protect';
2802
		}
2803
2804
		/**
2805
		 * Allow filtering of the active modules.
2806
		 *
2807
		 * Gives theme and plugin developers the power to alter the modules that
2808
		 * are activated on the fly.
2809
		 *
2810
		 * @since 5.8.0
2811
		 *
2812
		 * @param array $active Array of active module slugs.
2813
		 */
2814
		$active = apply_filters( 'jetpack_active_modules', $active );
2815
2816
		return array_unique( $active );
2817
	}
2818
2819
	/**
2820
	 * Check whether or not a Jetpack module is active.
2821
	 *
2822
	 * @param string $module The slug of a Jetpack module.
2823
	 * @return bool
2824
	 *
2825
	 * @static
2826
	 */
2827
	public static function is_module_active( $module ) {
2828
		return in_array( $module, self::get_active_modules() );
2829
	}
2830
2831
	public static function is_module( $module ) {
2832
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2833
	}
2834
2835
	/**
2836
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2837
	 *
2838
	 * @param bool $catch True to start catching, False to stop.
2839
	 *
2840
	 * @static
2841
	 */
2842
	public static function catch_errors( $catch ) {
2843
		static $display_errors, $error_reporting;
2844
2845
		if ( $catch ) {
2846
			$display_errors  = @ini_set( 'display_errors', 1 );
2847
			$error_reporting = @error_reporting( E_ALL );
2848
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2849
		} else {
2850
			@ini_set( 'display_errors', $display_errors );
2851
			@error_reporting( $error_reporting );
2852
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2853
		}
2854
	}
2855
2856
	/**
2857
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2858
	 */
2859
	public static function catch_errors_on_shutdown() {
2860
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2861
	}
2862
2863
	/**
2864
	 * Rewrite any string to make paths easier to read.
2865
	 *
2866
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2867
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2868
	 *
2869
	 * @param $string
2870
	 * @return mixed
2871
	 */
2872
	public static function alias_directories( $string ) {
2873
		// ABSPATH has a trailing slash.
2874
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2875
		// WP_CONTENT_DIR does not have a trailing slash.
2876
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2877
2878
		return $string;
2879
	}
2880
2881
	public static function activate_default_modules(
2882
		$min_version = false,
2883
		$max_version = false,
2884
		$other_modules = array(),
2885
		$redirect = true,
2886
		$send_state_messages = true
2887
	) {
2888
		$jetpack = Jetpack::init();
2889
2890
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2891
		$modules = array_merge( $other_modules, $modules );
2892
2893
		// Look for standalone plugins and disable if active.
2894
2895
		$to_deactivate = array();
2896
		foreach ( $modules as $module ) {
2897
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2898
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2899
			}
2900
		}
2901
2902
		$deactivated = array();
2903
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2904
			list( $probable_file, $probable_title ) = $deactivate_me;
2905
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2906
				$deactivated[] = $module;
2907
			}
2908
		}
2909
2910
		if ( $deactivated && $redirect ) {
2911
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2912
2913
			$url = add_query_arg(
2914
				array(
2915
					'action'   => 'activate_default_modules',
2916
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2917
				),
2918
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2919
			);
2920
			wp_safe_redirect( $url );
2921
			exit;
2922
		}
2923
2924
		/**
2925
		 * Fires before default modules are activated.
2926
		 *
2927
		 * @since 1.9.0
2928
		 *
2929
		 * @param string $min_version Minimum version number required to use modules.
2930
		 * @param string $max_version Maximum version number required to use modules.
2931
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2932
		 */
2933
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2934
2935
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2936
		if ( $send_state_messages ) {
2937
			Jetpack::restate();
2938
			Jetpack::catch_errors( true );
2939
		}
2940
2941
		$active = Jetpack::get_active_modules();
2942
2943
		foreach ( $modules as $module ) {
2944
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2945
				$active[] = $module;
2946
				self::update_active_modules( $active );
2947
				continue;
2948
			}
2949
2950
			if ( $send_state_messages && in_array( $module, $active ) ) {
2951
				$module_info = Jetpack::get_module( $module );
2952 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2953
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2954
					if ( $active_state = Jetpack::state( $state ) ) {
2955
						$active_state = explode( ',', $active_state );
2956
					} else {
2957
						$active_state = array();
2958
					}
2959
					$active_state[] = $module;
2960
					Jetpack::state( $state, implode( ',', $active_state ) );
2961
				}
2962
				continue;
2963
			}
2964
2965
			$file = Jetpack::get_module_path( $module );
2966
			if ( ! file_exists( $file ) ) {
2967
				continue;
2968
			}
2969
2970
			// we'll override this later if the plugin can be included without fatal error
2971
			if ( $redirect ) {
2972
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2973
			}
2974
2975
			if ( $send_state_messages ) {
2976
				Jetpack::state( 'error', 'module_activation_failed' );
2977
				Jetpack::state( 'module', $module );
2978
			}
2979
2980
			ob_start();
2981
			require_once $file;
2982
2983
			$active[] = $module;
2984
2985 View Code Duplication
			if ( $send_state_messages ) {
2986
2987
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2988
				if ( $active_state = Jetpack::state( $state ) ) {
2989
					$active_state = explode( ',', $active_state );
2990
				} else {
2991
					$active_state = array();
2992
				}
2993
				$active_state[] = $module;
2994
				Jetpack::state( $state, implode( ',', $active_state ) );
2995
			}
2996
2997
			Jetpack::update_active_modules( $active );
2998
2999
			ob_end_clean();
3000
		}
3001
3002
		if ( $send_state_messages ) {
3003
			Jetpack::state( 'error', false );
3004
			Jetpack::state( 'module', false );
3005
		}
3006
3007
		Jetpack::catch_errors( false );
3008
		/**
3009
		 * Fires when default modules are activated.
3010
		 *
3011
		 * @since 1.9.0
3012
		 *
3013
		 * @param string $min_version Minimum version number required to use modules.
3014
		 * @param string $max_version Maximum version number required to use modules.
3015
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3016
		 */
3017
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3018
	}
3019
3020
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3021
		/**
3022
		 * Fires before a module is activated.
3023
		 *
3024
		 * @since 2.6.0
3025
		 *
3026
		 * @param string $module Module slug.
3027
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3028
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3029
		 */
3030
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3031
3032
		$jetpack = Jetpack::init();
3033
3034
		if ( ! strlen( $module ) )
3035
			return false;
3036
3037
		if ( ! Jetpack::is_module( $module ) )
3038
			return false;
3039
3040
		// If it's already active, then don't do it again
3041
		$active = Jetpack::get_active_modules();
3042
		foreach ( $active as $act ) {
3043
			if ( $act == $module )
3044
				return true;
3045
		}
3046
3047
		$module_data = Jetpack::get_module( $module );
3048
3049
		if ( ! Jetpack::is_active() ) {
3050
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
3051
				return false;
3052
3053
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3054
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
3055
				return false;
3056
		}
3057
3058
		// Check and see if the old plugin is active
3059
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3060
			// Deactivate the old plugin
3061
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3062
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3063
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3064
				Jetpack::state( 'deactivated_plugins', $module );
3065
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3066
				exit;
3067
			}
3068
		}
3069
3070
		// Protect won't work with mis-configured IPs
3071
		if ( 'protect' === $module ) {
3072
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3073
			if ( ! jetpack_protect_get_ip() ) {
3074
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3075
				return false;
3076
			}
3077
		}
3078
3079
		if ( ! Jetpack_Plan::supports( $module ) ) {
3080
			return false;
3081
		}
3082
3083
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3084
		Jetpack::state( 'module', $module );
3085
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3086
3087
		Jetpack::catch_errors( true );
3088
		ob_start();
3089
		require Jetpack::get_module_path( $module );
3090
		/** This action is documented in class.jetpack.php */
3091
		do_action( 'jetpack_activate_module', $module );
3092
		$active[] = $module;
3093
		Jetpack::update_active_modules( $active );
3094
3095
		Jetpack::state( 'error', false ); // the override
3096
		ob_end_clean();
3097
		Jetpack::catch_errors( false );
3098
3099
		if ( $redirect ) {
3100
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3101
		}
3102
		if ( $exit ) {
3103
			exit;
3104
		}
3105
		return true;
3106
	}
3107
3108
	function activate_module_actions( $module ) {
3109
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3110
	}
3111
3112
	public static function deactivate_module( $module ) {
3113
		/**
3114
		 * Fires when a module is deactivated.
3115
		 *
3116
		 * @since 1.9.0
3117
		 *
3118
		 * @param string $module Module slug.
3119
		 */
3120
		do_action( 'jetpack_pre_deactivate_module', $module );
3121
3122
		$jetpack = Jetpack::init();
3123
3124
		$active = Jetpack::get_active_modules();
3125
		$new    = array_filter( array_diff( $active, (array) $module ) );
3126
3127
		return self::update_active_modules( $new );
3128
	}
3129
3130
	public static function enable_module_configurable( $module ) {
3131
		$module = Jetpack::get_module_slug( $module );
3132
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3133
	}
3134
3135
	/**
3136
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3137
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3138
	 *
3139
	 * @param string $module Module slug
3140
	 * @return string $url module configuration URL
3141
	 */
3142
	public static function module_configuration_url( $module ) {
3143
		$module = Jetpack::get_module_slug( $module );
3144
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3145
		/**
3146
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3147
		 *
3148
		 * @since 6.9.0
3149
		 *
3150
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3151
		 */
3152
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3153
3154
		return $url;
3155
	}
3156
3157
/* Installation */
3158
	public static function bail_on_activation( $message, $deactivate = true ) {
3159
?>
3160
<!doctype html>
3161
<html>
3162
<head>
3163
<meta charset="<?php bloginfo( 'charset' ); ?>">
3164
<style>
3165
* {
3166
	text-align: center;
3167
	margin: 0;
3168
	padding: 0;
3169
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3170
}
3171
p {
3172
	margin-top: 1em;
3173
	font-size: 18px;
3174
}
3175
</style>
3176
<body>
3177
<p><?php echo esc_html( $message ); ?></p>
3178
</body>
3179
</html>
3180
<?php
3181
		if ( $deactivate ) {
3182
			$plugins = get_option( 'active_plugins' );
3183
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3184
			$update  = false;
3185
			foreach ( $plugins as $i => $plugin ) {
3186
				if ( $plugin === $jetpack ) {
3187
					$plugins[$i] = false;
3188
					$update = true;
3189
				}
3190
			}
3191
3192
			if ( $update ) {
3193
				update_option( 'active_plugins', array_filter( $plugins ) );
3194
			}
3195
		}
3196
		exit;
3197
	}
3198
3199
	/**
3200
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3201
	 * @static
3202
	 */
3203
	public static function plugin_activation( $network_wide ) {
3204
		Jetpack_Options::update_option( 'activated', 1 );
3205
3206
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3207
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3208
		}
3209
3210
		if ( $network_wide )
3211
			Jetpack::state( 'network_nag', true );
3212
3213
		// For firing one-off events (notices) immediately after activation
3214
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3215
3216
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3217
3218
		Jetpack::plugin_initialize();
3219
	}
3220
3221
	public static function get_activation_source( $referer_url ) {
3222
3223
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3224
			return array( 'wp-cli', null );
3225
		}
3226
3227
		$referer = parse_url( $referer_url );
3228
3229
		$source_type = 'unknown';
3230
		$source_query = null;
3231
3232
		if ( ! is_array( $referer ) ) {
3233
			return array( $source_type, $source_query );
3234
		}
3235
3236
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3237
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3238
3239
		if ( isset( $referer['query'] ) ) {
3240
			parse_str( $referer['query'], $query_parts );
3241
		} else {
3242
			$query_parts = array();
3243
		}
3244
3245
		if ( $plugins_path === $referer['path'] ) {
3246
			$source_type = 'list';
3247
		} elseif ( $plugins_install_path === $referer['path'] ) {
3248
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3249
			switch( $tab ) {
3250
				case 'popular':
3251
					$source_type = 'popular';
3252
					break;
3253
				case 'recommended':
3254
					$source_type = 'recommended';
3255
					break;
3256
				case 'favorites':
3257
					$source_type = 'favorites';
3258
					break;
3259
				case 'search':
3260
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3261
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3262
					break;
3263
				default:
3264
					$source_type = 'featured';
3265
			}
3266
		}
3267
3268
		return array( $source_type, $source_query );
3269
	}
3270
3271
	/**
3272
	 * Runs before bumping version numbers up to a new version
3273
	 * @param  string $version    Version:timestamp
3274
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3275
	 * @return null              [description]
3276
	 */
3277
	public static function do_version_bump( $version, $old_version ) {
3278
		if ( ! $old_version ) { // For new sites
3279
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3280
		}
3281
	}
3282
3283
	/**
3284
	 * Sets the internal version number and activation state.
3285
	 * @static
3286
	 */
3287
	public static function plugin_initialize() {
3288
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3289
			Jetpack_Options::update_option( 'activated', 2 );
3290
		}
3291
3292 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3293
			$version = $old_version = JETPACK__VERSION . ':' . time();
3294
			/** This action is documented in class.jetpack.php */
3295
			do_action( 'updating_jetpack_version', $version, false );
3296
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3297
		}
3298
3299
		Jetpack::load_modules();
3300
3301
		Jetpack_Options::delete_option( 'do_activate' );
3302
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3303
	}
3304
3305
	/**
3306
	 * Removes all connection options
3307
	 * @static
3308
	 */
3309
	public static function plugin_deactivation( ) {
3310
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3311
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3312
			Jetpack_Network::init()->deactivate();
3313
		} else {
3314
			Jetpack::disconnect( false );
3315
			//Jetpack_Heartbeat::init()->deactivate();
3316
		}
3317
	}
3318
3319
	/**
3320
	 * Disconnects from the Jetpack servers.
3321
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3322
	 * @static
3323
	 */
3324
	public static function disconnect( $update_activated_state = true ) {
3325
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3326
		Jetpack::clean_nonces( true );
3327
3328
		// If the site is in an IDC because sync is not allowed,
3329
		// let's make sure to not disconnect the production site.
3330
		if ( ! self::validate_sync_error_idc_option() ) {
3331
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3332
			Jetpack::load_xml_rpc_client();
3333
			$xml = new Jetpack_IXR_Client();
3334
			$xml->query( 'jetpack.deregister' );
3335
		}
3336
3337
		Jetpack_Options::delete_option(
3338
			array(
3339
				'blog_token',
3340
				'user_token',
3341
				'user_tokens',
3342
				'master_user',
3343
				'time_diff',
3344
				'fallback_no_verify_ssl_certs',
3345
			)
3346
		);
3347
3348
		Jetpack_IDC::clear_all_idc_options();
3349
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3350
3351
		if ( $update_activated_state ) {
3352
			Jetpack_Options::update_option( 'activated', 4 );
3353
		}
3354
3355
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3356
			// Check then record unique disconnection if site has never been disconnected previously
3357
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3358
				$jetpack_unique_connection['disconnected'] = 1;
3359
			} else {
3360
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3361
					//track unique disconnect
3362
					$jetpack = Jetpack::init();
3363
3364
					$jetpack->stat( 'connections', 'unique-disconnect' );
3365
					$jetpack->do_stats( 'server_side' );
3366
				}
3367
				// increment number of times disconnected
3368
				$jetpack_unique_connection['disconnected'] += 1;
3369
			}
3370
3371
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3372
		}
3373
3374
		// Delete cached connected user data
3375
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3376
		delete_transient( $transient_key );
3377
3378
		// Delete all the sync related data. Since it could be taking up space.
3379
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3380
		Jetpack_Sync_Sender::get_instance()->uninstall();
3381
3382
		// Disable the Heartbeat cron
3383
		Jetpack_Heartbeat::init()->deactivate();
3384
	}
3385
3386
	/**
3387
	 * Unlinks the current user from the linked WordPress.com user
3388
	 */
3389
	public static function unlink_user( $user_id = null ) {
3390
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3391
			return false;
3392
3393
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3394
3395
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3396
			return false;
3397
3398
		if ( ! isset( $tokens[ $user_id ] ) )
3399
			return false;
3400
3401
		Jetpack::load_xml_rpc_client();
3402
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3403
		$xml->query( 'jetpack.unlink_user', $user_id );
3404
3405
		unset( $tokens[ $user_id ] );
3406
3407
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3408
3409
		/**
3410
		 * Fires after the current user has been unlinked from WordPress.com.
3411
		 *
3412
		 * @since 4.1.0
3413
		 *
3414
		 * @param int $user_id The current user's ID.
3415
		 */
3416
		do_action( 'jetpack_unlinked_user', $user_id );
3417
3418
		return true;
3419
	}
3420
3421
	/**
3422
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3423
	 */
3424
	public static function try_registration() {
3425
		// The user has agreed to the TOS at some point by now.
3426
		Jetpack_Options::update_option( 'tos_agreed', true );
3427
3428
		// Let's get some testing in beta versions and such.
3429
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3430
			// Before attempting to connect, let's make sure that the domains are viable.
3431
			$domains_to_check = array_unique( array(
3432
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3433
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3434
			) );
3435
			foreach ( $domains_to_check as $domain ) {
3436
				$result = Jetpack_Data::is_usable_domain( $domain );
3437
				if ( is_wp_error( $result ) ) {
3438
					return $result;
3439
				}
3440
			}
3441
		}
3442
3443
		$result = Jetpack::register();
3444
3445
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3446
		if ( ! $result || is_wp_error( $result ) ) {
3447
			return $result;
3448
		} else {
3449
			return true;
3450
		}
3451
	}
3452
3453
	/**
3454
	 * Tracking an internal event log. Try not to put too much chaff in here.
3455
	 *
3456
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3457
	 */
3458
	public static function log( $code, $data = null ) {
3459
		// only grab the latest 200 entries
3460
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3461
3462
		// Append our event to the log
3463
		$log_entry = array(
3464
			'time'    => time(),
3465
			'user_id' => get_current_user_id(),
3466
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3467
			'code'    => $code,
3468
		);
3469
		// Don't bother storing it unless we've got some.
3470
		if ( ! is_null( $data ) ) {
3471
			$log_entry['data'] = $data;
3472
		}
3473
		$log[] = $log_entry;
3474
3475
		// Try add_option first, to make sure it's not autoloaded.
3476
		// @todo: Add an add_option method to Jetpack_Options
3477
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3478
			Jetpack_Options::update_option( 'log', $log );
3479
		}
3480
3481
		/**
3482
		 * Fires when Jetpack logs an internal event.
3483
		 *
3484
		 * @since 3.0.0
3485
		 *
3486
		 * @param array $log_entry {
3487
		 *	Array of details about the log entry.
3488
		 *
3489
		 *	@param string time Time of the event.
3490
		 *	@param int user_id ID of the user who trigerred the event.
3491
		 *	@param int blog_id Jetpack Blog ID.
3492
		 *	@param string code Unique name for the event.
3493
		 *	@param string data Data about the event.
3494
		 * }
3495
		 */
3496
		do_action( 'jetpack_log_entry', $log_entry );
3497
	}
3498
3499
	/**
3500
	 * Get the internal event log.
3501
	 *
3502
	 * @param $event (string) - only return the specific log events
3503
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3504
	 *
3505
	 * @return array of log events || WP_Error for invalid params
3506
	 */
3507
	public static function get_log( $event = false, $num = false ) {
3508
		if ( $event && ! is_string( $event ) ) {
3509
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3510
		}
3511
3512
		if ( $num && ! is_numeric( $num ) ) {
3513
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3514
		}
3515
3516
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3517
3518
		// If nothing set - act as it did before, otherwise let's start customizing the output
3519
		if ( ! $num && ! $event ) {
3520
			return $entire_log;
3521
		} else {
3522
			$entire_log = array_reverse( $entire_log );
3523
		}
3524
3525
		$custom_log_output = array();
3526
3527
		if ( $event ) {
3528
			foreach ( $entire_log as $log_event ) {
3529
				if ( $event == $log_event[ 'code' ] ) {
3530
					$custom_log_output[] = $log_event;
3531
				}
3532
			}
3533
		} else {
3534
			$custom_log_output = $entire_log;
3535
		}
3536
3537
		if ( $num ) {
3538
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3539
		}
3540
3541
		return $custom_log_output;
3542
	}
3543
3544
	/**
3545
	 * Log modification of important settings.
3546
	 */
3547
	public static function log_settings_change( $option, $old_value, $value ) {
3548
		switch( $option ) {
3549
			case 'jetpack_sync_non_public_post_stati':
3550
				self::log( $option, $value );
3551
				break;
3552
		}
3553
	}
3554
3555
	/**
3556
	 * Return stat data for WPCOM sync
3557
	 */
3558
	public static function get_stat_data( $encode = true, $extended = true ) {
3559
		$data = Jetpack_Heartbeat::generate_stats_array();
3560
3561
		if ( $extended ) {
3562
			$additional_data = self::get_additional_stat_data();
3563
			$data = array_merge( $data, $additional_data );
3564
		}
3565
3566
		if ( $encode ) {
3567
			return json_encode( $data );
3568
		}
3569
3570
		return $data;
3571
	}
3572
3573
	/**
3574
	 * Get additional stat data to sync to WPCOM
3575
	 */
3576
	public static function get_additional_stat_data( $prefix = '' ) {
3577
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3578
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3579
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3580
		$return["{$prefix}site-count"]     = 0;
3581
3582
		if ( function_exists( 'get_blog_count' ) ) {
3583
			$return["{$prefix}site-count"] = get_blog_count();
3584
		}
3585
		return $return;
3586
	}
3587
3588
	private static function get_site_user_count() {
3589
		global $wpdb;
3590
3591
		if ( function_exists( 'wp_is_large_network' ) ) {
3592
			if ( wp_is_large_network( 'users' ) ) {
3593
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3594
			}
3595
		}
3596 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3597
			// It wasn't there, so regenerate the data and save the transient
3598
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3599
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3600
		}
3601
		return $user_count;
3602
	}
3603
3604
	/* Admin Pages */
3605
3606
	function admin_init() {
3607
		// If the plugin is not connected, display a connect message.
3608
		if (
3609
			// the plugin was auto-activated and needs its candy
3610
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3611
		||
3612
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3613
			! Jetpack_Options::get_option( 'activated' )
3614
		) {
3615
			Jetpack::plugin_initialize();
3616
		}
3617
3618
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3619
			Jetpack_Connection_Banner::init();
3620
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3621
			// Upgrade: 1.1 -> 1.1.1
3622
			// Check and see if host can verify the Jetpack servers' SSL certificate
3623
			$args = array();
3624
			Jetpack_Client::_wp_remote_request(
3625
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3626
				$args,
3627
				true
3628
			);
3629
		}
3630
3631
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3632
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3633
		}
3634
3635
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3636
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3637
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3638
3639
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3640
			// Artificially throw errors in certain whitelisted cases during plugin activation
3641
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3642
		}
3643
3644
		// Add custom column in wp-admin/users.php to show whether user is linked.
3645
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3646
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3647
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3648
	}
3649
3650
	function admin_body_class( $admin_body_class = '' ) {
3651
		$classes = explode( ' ', trim( $admin_body_class ) );
3652
3653
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3654
3655
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3656
		return " $admin_body_class ";
3657
	}
3658
3659
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3660
		return $admin_body_class . ' jetpack-pagestyles ';
3661
	}
3662
3663
	/**
3664
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3665
	 * This function artificially throws errors for such cases (whitelisted).
3666
	 *
3667
	 * @param string $plugin The activated plugin.
3668
	 */
3669
	function throw_error_on_activate_plugin( $plugin ) {
3670
		$active_modules = Jetpack::get_active_modules();
3671
3672
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3673
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3674
			$throw = false;
3675
3676
			// Try and make sure it really was the stats plugin
3677
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3678
				if ( 'stats.php' == basename( $plugin ) ) {
3679
					$throw = true;
3680
				}
3681
			} else {
3682
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3683
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3684
					$throw = true;
3685
				}
3686
			}
3687
3688
			if ( $throw ) {
3689
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3690
			}
3691
		}
3692
	}
3693
3694
	function intercept_plugin_error_scrape_init() {
3695
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3696
	}
3697
3698
	function intercept_plugin_error_scrape( $action, $result ) {
3699
		if ( ! $result ) {
3700
			return;
3701
		}
3702
3703
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3704
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3705
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3706
			}
3707
		}
3708
	}
3709
3710
	function add_remote_request_handlers() {
3711
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3712
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3713
	}
3714
3715
	function remote_request_handlers() {
3716
		$action = current_filter();
3717
3718
		switch ( current_filter() ) {
3719
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3720
			$response = $this->upload_handler();
3721
			break;
3722
3723
		case 'wp_ajax_nopriv_jetpack_update_file' :
3724
			$response = $this->upload_handler( true );
3725
			break;
3726
		default :
3727
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3728
			break;
3729
		}
3730
3731
		if ( ! $response ) {
3732
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3733
		}
3734
3735
		if ( is_wp_error( $response ) ) {
3736
			$status_code       = $response->get_error_data();
3737
			$error             = $response->get_error_code();
3738
			$error_description = $response->get_error_message();
3739
3740
			if ( ! is_int( $status_code ) ) {
3741
				$status_code = 400;
3742
			}
3743
3744
			status_header( $status_code );
3745
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3746
		}
3747
3748
		status_header( 200 );
3749
		if ( true === $response ) {
3750
			exit;
3751
		}
3752
3753
		die( json_encode( (object) $response ) );
3754
	}
3755
3756
	/**
3757
	 * Uploads a file gotten from the global $_FILES.
3758
	 * If `$update_media_item` is true and `post_id` is defined
3759
	 * the attachment file of the media item (gotten through of the post_id)
3760
	 * will be updated instead of add a new one.
3761
	 *
3762
	 * @param  boolean $update_media_item - update media attachment
3763
	 * @return array - An array describing the uploadind files process
3764
	 */
3765
	function upload_handler( $update_media_item = false ) {
3766
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3767
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3768
		}
3769
3770
		$user = wp_authenticate( '', '' );
3771
		if ( ! $user || is_wp_error( $user ) ) {
3772
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3773
		}
3774
3775
		wp_set_current_user( $user->ID );
3776
3777
		if ( ! current_user_can( 'upload_files' ) ) {
3778
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3779
		}
3780
3781
		if ( empty( $_FILES ) ) {
3782
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3783
		}
3784
3785
		foreach ( array_keys( $_FILES ) as $files_key ) {
3786
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3787
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3788
			}
3789
		}
3790
3791
		$media_keys = array_keys( $_FILES['media'] );
3792
3793
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3794
		if ( ! $token || is_wp_error( $token ) ) {
3795
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3796
		}
3797
3798
		$uploaded_files = array();
3799
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3800
		unset( $GLOBALS['post'] );
3801
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3802
			$file = array();
3803
			foreach ( $media_keys as $media_key ) {
3804
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3805
			}
3806
3807
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3808
3809
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3810
			if ( $hmac_provided !== $hmac_file ) {
3811
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3812
				continue;
3813
			}
3814
3815
			$_FILES['.jetpack.upload.'] = $file;
3816
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3817
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3818
				$post_id = 0;
3819
			}
3820
3821
			if ( $update_media_item ) {
3822
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3823
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3824
				}
3825
3826
				$media_array = $_FILES['media'];
3827
3828
				$file_array['name'] = $media_array['name'][0];
3829
				$file_array['type'] = $media_array['type'][0];
3830
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3831
				$file_array['error'] = $media_array['error'][0];
3832
				$file_array['size'] = $media_array['size'][0];
3833
3834
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3835
3836
				if ( is_wp_error( $edited_media_item ) ) {
3837
					return $edited_media_item;
3838
				}
3839
3840
				$response = (object) array(
3841
					'id'   => (string) $post_id,
3842
					'file' => (string) $edited_media_item->post_title,
3843
					'url'  => (string) wp_get_attachment_url( $post_id ),
3844
					'type' => (string) $edited_media_item->post_mime_type,
3845
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3846
				);
3847
3848
				return (array) array( $response );
3849
			}
3850
3851
			$attachment_id = media_handle_upload(
3852
				'.jetpack.upload.',
3853
				$post_id,
3854
				array(),
3855
				array(
3856
					'action' => 'jetpack_upload_file',
3857
				)
3858
			);
3859
3860
			if ( ! $attachment_id ) {
3861
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3862
			} elseif ( is_wp_error( $attachment_id ) ) {
3863
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3864
			} else {
3865
				$attachment = get_post( $attachment_id );
3866
				$uploaded_files[$index] = (object) array(
3867
					'id'   => (string) $attachment_id,
3868
					'file' => $attachment->post_title,
3869
					'url'  => wp_get_attachment_url( $attachment_id ),
3870
					'type' => $attachment->post_mime_type,
3871
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3872
				);
3873
				// Zip files uploads are not supported unless they are done for installation purposed
3874
				// lets delete them in case something goes wrong in this whole process
3875
				if ( 'application/zip' === $attachment->post_mime_type ) {
3876
					// Schedule a cleanup for 2 hours from now in case of failed install.
3877
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3878
				}
3879
			}
3880
		}
3881
		if ( ! is_null( $global_post ) ) {
3882
			$GLOBALS['post'] = $global_post;
3883
		}
3884
3885
		return $uploaded_files;
3886
	}
3887
3888
	/**
3889
	 * Add help to the Jetpack page
3890
	 *
3891
	 * @since Jetpack (1.2.3)
3892
	 * @return false if not the Jetpack page
3893
	 */
3894
	function admin_help() {
3895
		$current_screen = get_current_screen();
3896
3897
		// Overview
3898
		$current_screen->add_help_tab(
3899
			array(
3900
				'id'		=> 'home',
3901
				'title'		=> __( 'Home', 'jetpack' ),
3902
				'content'	=>
3903
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3904
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3905
					'<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>',
3906
			)
3907
		);
3908
3909
		// Screen Content
3910
		if ( current_user_can( 'manage_options' ) ) {
3911
			$current_screen->add_help_tab(
3912
				array(
3913
					'id'		=> 'settings',
3914
					'title'		=> __( 'Settings', 'jetpack' ),
3915
					'content'	=>
3916
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3917
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3918
						'<ol>' .
3919
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3920
							'<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>' .
3921
						'</ol>' .
3922
						'<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>'
3923
				)
3924
			);
3925
		}
3926
3927
		// Help Sidebar
3928
		$current_screen->set_help_sidebar(
3929
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3930
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3931
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3932
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3933
		);
3934
	}
3935
3936
	function admin_menu_css() {
3937
		wp_enqueue_style( 'jetpack-icons' );
3938
	}
3939
3940
	function admin_menu_order() {
3941
		return true;
3942
	}
3943
3944 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3945
		$jp_menu_order = array();
3946
3947
		foreach ( $menu_order as $index => $item ) {
3948
			if ( $item != 'jetpack' ) {
3949
				$jp_menu_order[] = $item;
3950
			}
3951
3952
			if ( $index == 0 ) {
3953
				$jp_menu_order[] = 'jetpack';
3954
			}
3955
		}
3956
3957
		return $jp_menu_order;
3958
	}
3959
3960
	function admin_banner_styles() {
3961
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3962
3963
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3964
			wp_register_style(
3965
				'jetpack-dops-style',
3966
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3967
				array(),
3968
				JETPACK__VERSION
3969
			);
3970
		}
3971
3972
		wp_enqueue_style(
3973
			'jetpack',
3974
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3975
			array( 'jetpack-dops-style' ),
3976
			 JETPACK__VERSION . '-20121016'
3977
		);
3978
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3979
		wp_style_add_data( 'jetpack', 'suffix', $min );
3980
	}
3981
3982
	function plugin_action_links( $actions ) {
3983
3984
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3985
3986
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3987
			return array_merge(
3988
				$jetpack_home,
3989
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3990
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3991
				$actions
3992
				);
3993
			}
3994
3995
		return array_merge( $jetpack_home, $actions );
3996
	}
3997
3998
	/*
3999
	 * Registration flow:
4000
	 * 1 - ::admin_page_load() action=register
4001
	 * 2 - ::try_registration()
4002
	 * 3 - ::register()
4003
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4004
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4005
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4006
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4007
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4008
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4009
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4010
	 *       jetpack_id, jetpack_secret, jetpack_public
4011
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4012
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4013
	 * 5 - user logs in with WP.com account
4014
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4015
	 *		- Jetpack_Client_Server::authorize()
4016
	 *		- Jetpack_Client_Server::get_token()
4017
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4018
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4019
	 *			- which responds with access_token, token_type, scope
4020
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
4021
	 *		- Jetpack::activate_default_modules()
4022
	 *     		- Deactivates deprecated plugins
4023
	 *     		- Activates all default modules
4024
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4025
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4026
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4027
	 *     Done!
4028
	 */
4029
4030
	/**
4031
	 * Handles the page load events for the Jetpack admin page
4032
	 */
4033
	function admin_page_load() {
4034
		$error = false;
4035
4036
		// Make sure we have the right body class to hook stylings for subpages off of.
4037
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4038
4039
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4040
			// Should only be used in intermediate redirects to preserve state across redirects
4041
			Jetpack::restate();
4042
		}
4043
4044
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4045
			// @todo: Add validation against a known whitelist
4046
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4047
			// User clicked in the iframe to link their accounts
4048
			if ( ! Jetpack::is_user_connected() ) {
4049
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4050
4051
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4052
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4053
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4054
4055
				if ( isset( $_GET['notes_iframe'] ) )
4056
					$connect_url .= '&notes_iframe';
4057
				wp_redirect( $connect_url );
4058
				exit;
4059
			} else {
4060
				if ( ! isset( $_GET['calypso_env'] ) ) {
4061
					Jetpack::state( 'message', 'already_authorized' );
4062
					wp_safe_redirect( Jetpack::admin_url() );
4063
					exit;
4064
				} else {
4065
					$connect_url = $this->build_connect_url( true, false, $from );
4066
					$connect_url .= '&already_authorized=true';
4067
					wp_redirect( $connect_url );
4068
					exit;
4069
				}
4070
			}
4071
		}
4072
4073
4074
		if ( isset( $_GET['action'] ) ) {
4075
			switch ( $_GET['action'] ) {
4076
			case 'authorize':
4077
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4078
					Jetpack::state( 'message', 'already_authorized' );
4079
					wp_safe_redirect( Jetpack::admin_url() );
4080
					exit;
4081
				}
4082
				Jetpack::log( 'authorize' );
4083
				$client_server = new Jetpack_Client_Server;
4084
				$client_server->client_authorize();
4085
				exit;
4086
			case 'register' :
4087
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4088
					$error = 'cheatin';
4089
					break;
4090
				}
4091
				check_admin_referer( 'jetpack-register' );
4092
				Jetpack::log( 'register' );
4093
				Jetpack::maybe_set_version_option();
4094
				$registered = Jetpack::try_registration();
4095
				if ( is_wp_error( $registered ) ) {
4096
					$error = $registered->get_error_code();
4097
					Jetpack::state( 'error', $error );
4098
					Jetpack::state( 'error', $registered->get_error_message() );
4099
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4100
						'error_code' => $error,
4101
						'error_message' => $registered->get_error_message()
4102
					) );
4103
					break;
4104
				}
4105
4106
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4107
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4108
4109
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4110
					'from' => $from
4111
				) );
4112
4113
				$url = $this->build_connect_url( true, $redirect, $from );
4114
4115
				if ( ! empty( $_GET['onboarding'] ) ) {
4116
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4117
				}
4118
4119
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4120
					$url = add_query_arg( 'auth_approved', 'true', $url );
4121
				}
4122
4123
				wp_redirect( $url );
4124
				exit;
4125
			case 'activate' :
4126
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4127
					$error = 'cheatin';
4128
					break;
4129
				}
4130
4131
				$module = stripslashes( $_GET['module'] );
4132
				check_admin_referer( "jetpack_activate-$module" );
4133
				Jetpack::log( 'activate', $module );
4134
				if ( ! Jetpack::activate_module( $module ) ) {
4135
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4136
				}
4137
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4138
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4139
				exit;
4140
			case 'activate_default_modules' :
4141
				check_admin_referer( 'activate_default_modules' );
4142
				Jetpack::log( 'activate_default_modules' );
4143
				Jetpack::restate();
4144
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4145
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4146
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4147
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4148
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4149
				exit;
4150
			case 'disconnect' :
4151
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4152
					$error = 'cheatin';
4153
					break;
4154
				}
4155
4156
				check_admin_referer( 'jetpack-disconnect' );
4157
				Jetpack::log( 'disconnect' );
4158
				Jetpack::disconnect();
4159
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4160
				exit;
4161
			case 'reconnect' :
4162
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4163
					$error = 'cheatin';
4164
					break;
4165
				}
4166
4167
				check_admin_referer( 'jetpack-reconnect' );
4168
				Jetpack::log( 'reconnect' );
4169
				$this->disconnect();
4170
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4171
				exit;
4172 View Code Duplication
			case 'deactivate' :
4173
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4174
					$error = 'cheatin';
4175
					break;
4176
				}
4177
4178
				$modules = stripslashes( $_GET['module'] );
4179
				check_admin_referer( "jetpack_deactivate-$modules" );
4180
				foreach ( explode( ',', $modules ) as $module ) {
4181
					Jetpack::log( 'deactivate', $module );
4182
					Jetpack::deactivate_module( $module );
4183
					Jetpack::state( 'message', 'module_deactivated' );
4184
				}
4185
				Jetpack::state( 'module', $modules );
4186
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4187
				exit;
4188
			case 'unlink' :
4189
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4190
				check_admin_referer( 'jetpack-unlink' );
4191
				Jetpack::log( 'unlink' );
4192
				$this->unlink_user();
4193
				Jetpack::state( 'message', 'unlinked' );
4194
				if ( 'sub-unlink' == $redirect ) {
4195
					wp_safe_redirect( admin_url() );
4196
				} else {
4197
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4198
				}
4199
				exit;
4200
			case 'onboard' :
4201
				if ( ! current_user_can( 'manage_options' ) ) {
4202
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4203
				} else {
4204
					Jetpack::create_onboarding_token();
4205
					$url = $this->build_connect_url( true );
4206
4207
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4208
						$url = add_query_arg( 'onboarding', $token, $url );
4209
					}
4210
4211
					$calypso_env = $this->get_calypso_env();
4212
					if ( ! empty( $calypso_env ) ) {
4213
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4214
					}
4215
4216
					wp_redirect( $url );
4217
					exit;
4218
				}
4219
				exit;
4220
			default:
4221
				/**
4222
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4223
				 *
4224
				 * @since 2.6.0
4225
				 *
4226
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4227
				 */
4228
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4229
			}
4230
		}
4231
4232
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4233
			self::activate_new_modules( true );
4234
		}
4235
4236
		$message_code = Jetpack::state( 'message' );
4237
		if ( Jetpack::state( 'optin-manage' ) ) {
4238
			$activated_manage = $message_code;
4239
			$message_code = 'jetpack-manage';
4240
		}
4241
4242
		switch ( $message_code ) {
4243
		case 'jetpack-manage':
4244
			$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>';
4245
			if ( $activated_manage ) {
4246
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4247
			}
4248
			break;
4249
4250
		}
4251
4252
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4253
4254
		if ( ! empty( $deactivated_plugins ) ) {
4255
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4256
			$deactivated_titles  = array();
4257
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4258
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4259
					continue;
4260
				}
4261
4262
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4263
			}
4264
4265
			if ( $deactivated_titles ) {
4266
				if ( $this->message ) {
4267
					$this->message .= "<br /><br />\n";
4268
				}
4269
4270
				$this->message .= wp_sprintf(
4271
					_n(
4272
						'Jetpack contains the most recent version of the old %l plugin.',
4273
						'Jetpack contains the most recent versions of the old %l plugins.',
4274
						count( $deactivated_titles ),
4275
						'jetpack'
4276
					),
4277
					$deactivated_titles
4278
				);
4279
4280
				$this->message .= "<br />\n";
4281
4282
				$this->message .= _n(
4283
					'The old version has been deactivated and can be removed from your site.',
4284
					'The old versions have been deactivated and can be removed from your site.',
4285
					count( $deactivated_titles ),
4286
					'jetpack'
4287
				);
4288
			}
4289
		}
4290
4291
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4292
4293
		if ( $this->message || $this->error || $this->privacy_checks ) {
4294
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4295
		}
4296
4297
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4298
	}
4299
4300
	function admin_notices() {
4301
4302
		if ( $this->error ) {
4303
?>
4304
<div id="message" class="jetpack-message jetpack-err">
4305
	<div class="squeezer">
4306
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4307
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4308
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4309
<?php	endif; ?>
4310
	</div>
4311
</div>
4312
<?php
4313
		}
4314
4315
		if ( $this->message ) {
4316
?>
4317
<div id="message" class="jetpack-message">
4318
	<div class="squeezer">
4319
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4320
	</div>
4321
</div>
4322
<?php
4323
		}
4324
4325
		if ( $this->privacy_checks ) :
4326
			$module_names = $module_slugs = array();
4327
4328
			$privacy_checks = explode( ',', $this->privacy_checks );
4329
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4330
			foreach ( $privacy_checks as $module_slug ) {
4331
				$module = Jetpack::get_module( $module_slug );
4332
				if ( ! $module ) {
4333
					continue;
4334
				}
4335
4336
				$module_slugs[] = $module_slug;
4337
				$module_names[] = "<strong>{$module['name']}</strong>";
4338
			}
4339
4340
			$module_slugs = join( ',', $module_slugs );
4341
?>
4342
<div id="message" class="jetpack-message jetpack-err">
4343
	<div class="squeezer">
4344
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4345
		<p><?php
4346
			echo wp_kses(
4347
				wptexturize(
4348
					wp_sprintf(
4349
						_nx(
4350
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4351
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4352
							count( $privacy_checks ),
4353
							'%l = list of Jetpack module/feature names',
4354
							'jetpack'
4355
						),
4356
						$module_names
4357
					)
4358
				),
4359
				array( 'strong' => true )
4360
			);
4361
4362
			echo "\n<br />\n";
4363
4364
			echo wp_kses(
4365
				sprintf(
4366
					_nx(
4367
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4368
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4369
						count( $privacy_checks ),
4370
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4371
						'jetpack'
4372
					),
4373
					wp_nonce_url(
4374
						Jetpack::admin_url(
4375
							array(
4376
								'page'   => 'jetpack',
4377
								'action' => 'deactivate',
4378
								'module' => urlencode( $module_slugs ),
4379
							)
4380
						),
4381
						"jetpack_deactivate-$module_slugs"
4382
					),
4383
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4384
				),
4385
				array( 'a' => array( 'href' => true, 'title' => true ) )
4386
			);
4387
		?></p>
4388
	</div>
4389
</div>
4390
<?php endif;
4391
	}
4392
4393
	/**
4394
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4395
	 */
4396
	function stat( $group, $detail ) {
4397
		if ( ! isset( $this->stats[ $group ] ) )
4398
			$this->stats[ $group ] = array();
4399
		$this->stats[ $group ][] = $detail;
4400
	}
4401
4402
	/**
4403
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4404
	 */
4405
	function do_stats( $method = '' ) {
4406
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4407
			foreach ( $this->stats as $group => $stats ) {
4408
				if ( is_array( $stats ) && count( $stats ) ) {
4409
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4410
					if ( 'server_side' === $method ) {
4411
						self::do_server_side_stat( $args );
4412
					} else {
4413
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4414
					}
4415
				}
4416
				unset( $this->stats[ $group ] );
4417
			}
4418
		}
4419
	}
4420
4421
	/**
4422
	 * Runs stats code for a one-off, server-side.
4423
	 *
4424
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4425
	 *
4426
	 * @return bool If it worked.
4427
	 */
4428
	static function do_server_side_stat( $args ) {
4429
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4430
		if ( is_wp_error( $response ) )
4431
			return false;
4432
4433
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4434
			return false;
4435
4436
		return true;
4437
	}
4438
4439
	/**
4440
	 * Builds the stats url.
4441
	 *
4442
	 * @param $args array|string The arguments to append to the URL.
4443
	 *
4444
	 * @return string The URL to be pinged.
4445
	 */
4446
	static function build_stats_url( $args ) {
4447
		$defaults = array(
4448
			'v'    => 'wpcom2',
4449
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4450
		);
4451
		$args     = wp_parse_args( $args, $defaults );
4452
		/**
4453
		 * Filter the URL used as the Stats tracking pixel.
4454
		 *
4455
		 * @since 2.3.2
4456
		 *
4457
		 * @param string $url Base URL used as the Stats tracking pixel.
4458
		 */
4459
		$base_url = apply_filters(
4460
			'jetpack_stats_base_url',
4461
			'https://pixel.wp.com/g.gif'
4462
		);
4463
		$url      = add_query_arg( $args, $base_url );
4464
		return $url;
4465
	}
4466
4467
	static function translate_current_user_to_role() {
4468
		foreach ( self::$capability_translations as $role => $cap ) {
4469
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4470
				return $role;
4471
			}
4472
		}
4473
4474
		return false;
4475
	}
4476
4477
	static function translate_user_to_role( $user ) {
4478
		foreach ( self::$capability_translations as $role => $cap ) {
4479
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4480
				return $role;
4481
			}
4482
		}
4483
4484
		return false;
4485
    }
4486
4487
	static function translate_role_to_cap( $role ) {
4488
		if ( ! isset( self::$capability_translations[$role] ) ) {
4489
			return false;
4490
		}
4491
4492
		return self::$capability_translations[$role];
4493
	}
4494
4495
	static function sign_role( $role, $user_id = null ) {
4496
		if ( empty( $user_id ) ) {
4497
			$user_id = (int) get_current_user_id();
4498
		}
4499
4500
		if ( ! $user_id  ) {
4501
			return false;
4502
		}
4503
4504
		$token = Jetpack_Data::get_access_token();
4505
		if ( ! $token || is_wp_error( $token ) ) {
4506
			return false;
4507
		}
4508
4509
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4510
	}
4511
4512
4513
	/**
4514
	 * Builds a URL to the Jetpack connection auth page
4515
	 *
4516
	 * @since 3.9.5
4517
	 *
4518
	 * @param bool $raw If true, URL will not be escaped.
4519
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4520
	 *                              If string, will be a custom redirect.
4521
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4522
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4523
	 *
4524
	 * @return string Connect URL
4525
	 */
4526
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4527
		$site_id = Jetpack_Options::get_option( 'id' );
4528
		$blog_token = Jetpack_Data::get_access_token();
4529
4530
		if ( $register || ! $blog_token || ! $site_id ) {
4531
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4532
4533
			if ( ! empty( $redirect ) ) {
4534
				$url = add_query_arg(
4535
					'redirect',
4536
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4537
					$url
4538
				);
4539
			}
4540
4541
			if( is_network_admin() ) {
4542
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4543
			}
4544
		} else {
4545
4546
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4547
			// because otherwise this logic can get us in to a loop.
4548
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4549
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4550
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4551
4552
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4553
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4554
					'1.1'
4555
				);
4556
4557
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4558
4559
					// Generating a register URL instead to refresh the existing token
4560
					return $this->build_connect_url( $raw, $redirect, $from, true );
4561
				}
4562
			}
4563
4564
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4565
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4566
			}
4567
4568
			$role = self::translate_current_user_to_role();
4569
			$signed_role = self::sign_role( $role );
4570
4571
			$user = wp_get_current_user();
4572
4573
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4574
			$redirect = $redirect
4575
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4576
				: $jetpack_admin_page;
4577
4578
			if( isset( $_REQUEST['is_multisite'] ) ) {
4579
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4580
			}
4581
4582
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4583
4584
			/**
4585
			 * Filter the type of authorization.
4586
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4587
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4588
			 *
4589
			 * @since 4.3.3
4590
			 *
4591
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4592
			 */
4593
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4594
4595
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4596
4597
			$args = urlencode_deep(
4598
				array(
4599
					'response_type' => 'code',
4600
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4601
					'redirect_uri'  => add_query_arg(
4602
						array(
4603
							'action'   => 'authorize',
4604
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4605
							'redirect' => urlencode( $redirect ),
4606
						),
4607
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4608
					),
4609
					'state'         => $user->ID,
4610
					'scope'         => $signed_role,
4611
					'user_email'    => $user->user_email,
4612
					'user_login'    => $user->user_login,
4613
					'is_active'     => Jetpack::is_active(),
4614
					'jp_version'    => JETPACK__VERSION,
4615
					'auth_type'     => $auth_type,
4616
					'secret'        => $secrets['secret_1'],
4617
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4618
					'blogname'      => get_option( 'blogname' ),
4619
					'site_url'      => site_url(),
4620
					'home_url'      => home_url(),
4621
					'site_icon'     => get_site_icon_url(),
4622
					'site_lang'     => get_locale(),
4623
					'_ui'           => $tracks_identity['_ui'],
4624
					'_ut'           => $tracks_identity['_ut'],
4625
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4626
				)
4627
			);
4628
4629
			self::apply_activation_source_to_args( $args );
4630
4631
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4632
		}
4633
4634
		if ( $from ) {
4635
			$url = add_query_arg( 'from', $from, $url );
4636
		}
4637
4638
		// Ensure that class to get the affiliate code is loaded
4639
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4640
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4641
		}
4642
		// Get affiliate code and add it to the URL
4643
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4644
4645
		$calypso_env = $this->get_calypso_env();
4646
4647
		if ( ! empty( $calypso_env ) ) {
4648
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4649
		}
4650
4651
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4652
	}
4653
4654
	/**
4655
	 * Get our assumed site creation date.
4656
	 * Calculated based on the earlier date of either:
4657
	 * - Earliest admin user registration date.
4658
	 * - Earliest date of post of any post type.
4659
	 *
4660
	 * @since 7.2.0
4661
	 *
4662
	 * @return string Assumed site creation date and time.
4663
	 */
4664
	public static function get_assumed_site_creation_date() {
4665
		$earliest_registered_users = get_users( array(
4666
			'role'    => 'administrator',
4667
			'orderby' => 'user_registered',
4668
			'order'   => 'ASC',
4669
			'fields'  => array( 'user_registered' ),
4670
			'number'  => 1,
4671
		) );
4672
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4673
4674
		$earliest_posts = get_posts( array(
4675
			'posts_per_page' => 1,
4676
			'post_type'      => 'any',
4677
			'post_status'    => 'any',
4678
			'orderby'        => 'date',
4679
			'order'          => 'ASC',
4680
		) );
4681
4682
		// If there are no posts at all, we'll count only on user registration date.
4683
		if ( $earliest_posts ) {
4684
			$earliest_post_date = $earliest_posts[0]->post_date;
4685
		} else {
4686
			$earliest_post_date = PHP_INT_MAX;
4687
		}
4688
4689
		return min( $earliest_registration_date, $earliest_post_date );
4690
	}
4691
4692
	public static function apply_activation_source_to_args( &$args ) {
4693
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4694
4695
		if ( $activation_source_name ) {
4696
			$args['_as'] = urlencode( $activation_source_name );
4697
		}
4698
4699
		if ( $activation_source_keyword ) {
4700
			$args['_ak'] = urlencode( $activation_source_keyword );
4701
		}
4702
	}
4703
4704
	function build_reconnect_url( $raw = false ) {
4705
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4706
		return $raw ? $url : esc_url( $url );
4707
	}
4708
4709
	public static function admin_url( $args = null ) {
4710
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4711
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4712
		return $url;
4713
	}
4714
4715
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4716
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4717
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4718
	}
4719
4720
	function dismiss_jetpack_notice() {
4721
4722
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4723
			return;
4724
		}
4725
4726
		switch( $_GET['jetpack-notice'] ) {
4727
			case 'dismiss':
4728
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4729
4730
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4731
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4732
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4733
				}
4734
				break;
4735
			case 'jetpack-protect-multisite-opt-out':
4736
4737
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4738
					// Don't show the banner again
4739
4740
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4741
					// redirect back to the page that had the notice
4742
					if ( wp_get_referer() ) {
4743
						wp_safe_redirect( wp_get_referer() );
4744
					} else {
4745
						// Take me to Jetpack
4746
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4747
					}
4748
				}
4749
				break;
4750
		}
4751
	}
4752
4753
	public static function sort_modules( $a, $b ) {
4754
		if ( $a['sort'] == $b['sort'] )
4755
			return 0;
4756
4757
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4758
	}
4759
4760
	function ajax_recheck_ssl() {
4761
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4762
		$result = Jetpack::permit_ssl( true );
4763
		wp_send_json( array(
4764
			'enabled' => $result,
4765
			'message' => get_transient( 'jetpack_https_test_message' )
4766
		) );
4767
	}
4768
4769
/* Client API */
4770
4771
	/**
4772
	 * Returns the requested Jetpack API URL
4773
	 *
4774
	 * @return string
4775
	 */
4776
	public static function api_url( $relative_url ) {
4777
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4778
	}
4779
4780
	/**
4781
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4782
	 */
4783
	public static function fix_url_for_bad_hosts( $url ) {
4784
		if ( 0 !== strpos( $url, 'https://' ) ) {
4785
			return $url;
4786
		}
4787
4788
		switch ( JETPACK_CLIENT__HTTPS ) {
4789
			case 'ALWAYS' :
4790
				return $url;
4791
			case 'NEVER' :
4792
				return set_url_scheme( $url, 'http' );
4793
			// default : case 'AUTO' :
4794
		}
4795
4796
		// we now return the unmodified SSL URL by default, as a security precaution
4797
		return $url;
4798
	}
4799
4800
	/**
4801
	 * Create a random secret for validating onboarding payload
4802
	 *
4803
	 * @return string Secret token
4804
	 */
4805
	public static function create_onboarding_token() {
4806
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4807
			$token = wp_generate_password( 32, false );
4808
			Jetpack_Options::update_option( 'onboarding', $token );
4809
		}
4810
4811
		return $token;
4812
	}
4813
4814
	/**
4815
	 * Remove the onboarding token
4816
	 *
4817
	 * @return bool True on success, false on failure
4818
	 */
4819
	public static function invalidate_onboarding_token() {
4820
		return Jetpack_Options::delete_option( 'onboarding' );
4821
	}
4822
4823
	/**
4824
	 * Validate an onboarding token for a specific action
4825
	 *
4826
	 * @return boolean True if token/action pair is accepted, false if not
4827
	 */
4828
	public static function validate_onboarding_token_action( $token, $action ) {
4829
		// Compare tokens, bail if tokens do not match
4830
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4831
			return false;
4832
		}
4833
4834
		// List of valid actions we can take
4835
		$valid_actions = array(
4836
			'/jetpack/v4/settings',
4837
		);
4838
4839
		// Whitelist the action
4840
		if ( ! in_array( $action, $valid_actions ) ) {
4841
			return false;
4842
		}
4843
4844
		return true;
4845
	}
4846
4847
	/**
4848
	 * Checks to see if the URL is using SSL to connect with Jetpack
4849
	 *
4850
	 * @since 2.3.3
4851
	 * @return boolean
4852
	 */
4853
	public static function permit_ssl( $force_recheck = false ) {
4854
		// Do some fancy tests to see if ssl is being supported
4855
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4856
			$message = '';
4857
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4858
				$ssl = 0;
4859
			} else {
4860
				switch ( JETPACK_CLIENT__HTTPS ) {
4861
					case 'NEVER':
4862
						$ssl = 0;
4863
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4864
						break;
4865
					case 'ALWAYS':
4866
					case 'AUTO':
4867
					default:
4868
						$ssl = 1;
4869
						break;
4870
				}
4871
4872
				// If it's not 'NEVER', test to see
4873
				if ( $ssl ) {
4874
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4875
						$ssl = 0;
4876
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4877
					} else {
4878
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4879
						if ( is_wp_error( $response ) ) {
4880
							$ssl = 0;
4881
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4882
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4883
							$ssl = 0;
4884
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4885
						}
4886
					}
4887
				}
4888
			}
4889
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4890
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4891
		}
4892
4893
		return (bool) $ssl;
4894
	}
4895
4896
	/*
4897
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4898
	 */
4899
	public function alert_auto_ssl_fail() {
4900
		if ( ! current_user_can( 'manage_options' ) )
4901
			return;
4902
4903
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4904
		?>
4905
4906
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4907
			<div class="jp-banner__content">
4908
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4909
				<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>
4910
				<p>
4911
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4912
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4913
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4914
				</p>
4915
				<p>
4916
					<?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' ),
4917
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4918
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4919
				</p>
4920
			</div>
4921
		</div>
4922
		<style>
4923
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4924
		</style>
4925
		<script type="text/javascript">
4926
			jQuery( document ).ready( function( $ ) {
4927
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4928
					var $this = $( this );
4929
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4930
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4931
					e.preventDefault();
4932
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4933
					$.post( ajaxurl, data )
4934
					  .done( function( response ) {
4935
					  	if ( response.enabled ) {
4936
					  		$( '#jetpack-ssl-warning' ).hide();
4937
					  	} else {
4938
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4939
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4940
					  	}
4941
					  }.bind( $this ) );
4942
				} );
4943
			} );
4944
		</script>
4945
4946
		<?php
4947
	}
4948
4949
	/**
4950
	 * Returns the Jetpack XML-RPC API
4951
	 *
4952
	 * @return string
4953
	 */
4954
	public static function xmlrpc_api_url() {
4955
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4956
		return untrailingslashit( $base ) . '/xmlrpc.php';
4957
	}
4958
4959
	/**
4960
	 * Creates two secret tokens and the end of life timestamp for them.
4961
	 *
4962
	 * Note these tokens are unique per call, NOT static per site for connecting.
4963
	 *
4964
	 * @since 2.6
4965
	 * @return array
4966
	 */
4967
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4968
		if ( false === $user_id ) {
4969
			$user_id = get_current_user_id();
4970
		}
4971
4972
		return self::init()->connection_manager->generate_secrets( $action, $user_id, $exp );
4973
	}
4974
4975
	public static function get_secrets( $action, $user_id ) {
4976
		$secrets = self::init()->connection_manager->get_secrets( $action, $user_id );
4977
4978
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4979
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4980
		}
4981
4982
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4983
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4984
		}
4985
4986
		return $secrets;
4987
	}
4988
4989
	public static function delete_secrets( $action, $user_id ) {
4990
		return self::init()->connection_manager->delete_secrets( $action, $user_id );
4991
	}
4992
4993
	/**
4994
	 * Builds the timeout limit for queries talking with the wpcom servers.
4995
	 *
4996
	 * Based on local php max_execution_time in php.ini
4997
	 *
4998
	 * @since 2.6
4999
	 * @return int
5000
	 * @deprecated
5001
	 **/
5002
	public function get_remote_query_timeout_limit() {
5003
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5004
		return Jetpack::get_max_execution_time();
5005
	}
5006
5007
	/**
5008
	 * Builds the timeout limit for queries talking with the wpcom servers.
5009
	 *
5010
	 * Based on local php max_execution_time in php.ini
5011
	 *
5012
	 * @since 5.4
5013
	 * @return int
5014
	 **/
5015
	public static function get_max_execution_time() {
5016
		$timeout = (int) ini_get( 'max_execution_time' );
5017
5018
		// Ensure exec time set in php.ini
5019
		if ( ! $timeout ) {
5020
			$timeout = 30;
5021
		}
5022
		return $timeout;
5023
	}
5024
5025
	/**
5026
	 * Sets a minimum request timeout, and returns the current timeout
5027
	 *
5028
	 * @since 5.4
5029
	 **/
5030
	public static function set_min_time_limit( $min_timeout ) {
5031
		$timeout = self::get_max_execution_time();
5032
		if ( $timeout < $min_timeout ) {
5033
			$timeout = $min_timeout;
5034
			set_time_limit( $timeout );
5035
		}
5036
		return $timeout;
5037
	}
5038
5039
5040
	/**
5041
	 * Takes the response from the Jetpack register new site endpoint and
5042
	 * verifies it worked properly.
5043
	 *
5044
	 * @since 2.6
5045
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5046
	 **/
5047
	public function validate_remote_register_response( $response ) {
5048
	  if ( is_wp_error( $response ) ) {
5049
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5050
		}
5051
5052
		$code   = wp_remote_retrieve_response_code( $response );
5053
		$entity = wp_remote_retrieve_body( $response );
5054
		if ( $entity )
5055
			$registration_response = json_decode( $entity );
5056
		else
5057
			$registration_response = false;
5058
5059
		$code_type = intval( $code / 100 );
5060
		if ( 5 == $code_type ) {
5061
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5062
		} elseif ( 408 == $code ) {
5063
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5064
		} elseif ( ! empty( $registration_response->error ) ) {
5065
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5066
				$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' );
5067
			} else {
5068
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5069
			}
5070
5071
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5072
		} elseif ( 200 != $code ) {
5073
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5074
		}
5075
5076
		// Jetpack ID error block
5077
		if ( empty( $registration_response->jetpack_id ) ) {
5078
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5079
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5080
			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 );
5081
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5082
			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 );
5083
		}
5084
5085
	    return $registration_response;
5086
	}
5087
	/**
5088
	 * @return bool|WP_Error
5089
	 */
5090
	public static function register() {
5091
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5092
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5093
		$secrets = Jetpack::generate_secrets( 'register' );
5094
5095 View Code Duplication
		if (
5096
			empty( $secrets['secret_1'] ) ||
5097
			empty( $secrets['secret_2'] ) ||
5098
			empty( $secrets['exp'] )
5099
		) {
5100
			return new Jetpack_Error( 'missing_secrets' );
5101
		}
5102
5103
		// better to try (and fail) to set a higher timeout than this system
5104
		// supports than to have register fail for more users than it should
5105
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5106
5107
		$gmt_offset = get_option( 'gmt_offset' );
5108
		if ( ! $gmt_offset ) {
5109
			$gmt_offset = 0;
5110
		}
5111
5112
		$stats_options = get_option( 'stats_options' );
5113
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5114
5115
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5116
5117
		$args = array(
5118
			'method'  => 'POST',
5119
			'body'    => array(
5120
				'siteurl'         => site_url(),
5121
				'home'            => home_url(),
5122
				'gmt_offset'      => $gmt_offset,
5123
				'timezone_string' => (string) get_option( 'timezone_string' ),
5124
				'site_name'       => (string) get_option( 'blogname' ),
5125
				'secret_1'        => $secrets['secret_1'],
5126
				'secret_2'        => $secrets['secret_2'],
5127
				'site_lang'       => get_locale(),
5128
				'timeout'         => $timeout,
5129
				'stats_id'        => $stats_id,
5130
				'state'           => get_current_user_id(),
5131
				'_ui'             => $tracks_identity['_ui'],
5132
				'_ut'             => $tracks_identity['_ut'],
5133
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5134
				'jetpack_version' => JETPACK__VERSION
5135
			),
5136
			'headers' => array(
5137
				'Accept' => 'application/json',
5138
			),
5139
			'timeout' => $timeout,
5140
		);
5141
5142
		self::apply_activation_source_to_args( $args['body'] );
5143
5144
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5145
5146
		// Make sure the response is valid and does not contain any Jetpack errors
5147
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5148
		if ( is_wp_error( $registration_details ) ) {
5149
			return $registration_details;
5150
		} elseif ( ! $registration_details ) {
5151
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5152
		}
5153
5154 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5155
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5156
		}
5157
5158
		if ( isset( $registration_details->jetpack_public ) ) {
5159
			$jetpack_public = (int) $registration_details->jetpack_public;
5160
		} else {
5161
			$jetpack_public = false;
5162
		}
5163
5164
		Jetpack_Options::update_options(
5165
			array(
5166
				'id'         => (int)    $registration_details->jetpack_id,
5167
				'blog_token' => (string) $registration_details->jetpack_secret,
5168
				'public'     => $jetpack_public,
5169
			)
5170
		);
5171
5172
		/**
5173
		 * Fires when a site is registered on WordPress.com.
5174
		 *
5175
		 * @since 3.7.0
5176
		 *
5177
		 * @param int $json->jetpack_id Jetpack Blog ID.
5178
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5179
		 * @param int|bool $jetpack_public Is the site public.
5180
		 */
5181
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5182
5183
		// Initialize Jump Start for the first and only time.
5184
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5185
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5186
5187
			$jetpack = Jetpack::init();
5188
5189
			$jetpack->stat( 'jumpstart', 'unique-views' );
5190
			$jetpack->do_stats( 'server_side' );
5191
		};
5192
5193
		return true;
5194
	}
5195
5196
	/**
5197
	 * If the db version is showing something other that what we've got now, bump it to current.
5198
	 *
5199
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5200
	 */
5201
	public static function maybe_set_version_option() {
5202
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5203
		if ( JETPACK__VERSION != $version ) {
5204
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5205
5206
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5207
				/** This action is documented in class.jetpack.php */
5208
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5209
			}
5210
5211
			return true;
5212
		}
5213
		return false;
5214
	}
5215
5216
/* Client Server API */
5217
5218
	/**
5219
	 * Loads the Jetpack XML-RPC client
5220
	 */
5221
	public static function load_xml_rpc_client() {
5222
		require_once ABSPATH . WPINC . '/class-IXR.php';
5223
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5224
	}
5225
5226
	/**
5227
	 * Resets the saved authentication state in between testing requests.
5228
	 */
5229
	public function reset_saved_auth_state() {
5230
		$this->xmlrpc_verification = null;
5231
		$this->rest_authentication_status = null;
5232
	}
5233
5234
	function verify_xml_rpc_signature() {
5235
		if ( $this->xmlrpc_verification ) {
5236
			return $this->xmlrpc_verification;
5237
		}
5238
5239
		// It's not for us
5240
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5241
			return false;
5242
		}
5243
5244
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5245
		if (
5246
			empty( $token_key )
5247
		||
5248
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5249
		) {
5250
			return false;
5251
		}
5252
5253
		if ( '0' === $user_id ) {
5254
			$token_type = 'blog';
5255
			$user_id = 0;
5256
		} else {
5257
			$token_type = 'user';
5258
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5259
				return false;
5260
			}
5261
			$user_id = (int) $user_id;
5262
5263
			$user = new WP_User( $user_id );
5264
			if ( ! $user || ! $user->exists() ) {
5265
				return false;
5266
			}
5267
		}
5268
5269
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
5270
		if ( ! $token ) {
5271
			return false;
5272
		}
5273
5274
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5275
5276
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5277
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5278
			$post_data   = $_POST;
5279
			$file_hashes = array();
5280
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5281
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5282
					continue;
5283
				}
5284
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5285
				$file_hashes[$post_data_key] = $post_data_value;
5286
			}
5287
5288
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5289
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5290
				$post_data[$post_data_key] = $post_data_value;
5291
			}
5292
5293
			ksort( $post_data );
5294
5295
			$body = http_build_query( stripslashes_deep( $post_data ) );
5296
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5297
			$body = file_get_contents( 'php://input' );
5298
		} else {
5299
			$body = null;
5300
		}
5301
5302
		$signature = $jetpack_signature->sign_current_request(
5303
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5304
		);
5305
5306
		if ( ! $signature ) {
5307
			return false;
5308
		} else if ( is_wp_error( $signature ) ) {
5309
			return $signature;
5310
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5311
			return false;
5312
		}
5313
5314
		$timestamp = (int) $_GET['timestamp'];
5315
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5316
5317
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5318
			return false;
5319
		}
5320
5321
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5322
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5323
			if ( ! empty( $_GET['onboarding'] ) ) {
5324
				$jpo = $_GET;
5325
			} else {
5326
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5327
			}
5328
5329
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5330
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5331
5332
			if (
5333
				isset( $jpo_user ) && isset( $jpo_token ) &&
5334
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5335
				isset( $_GET['rest_route'] ) &&
5336
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5337
			) {
5338
				$jpUser = get_user_by( 'email', $jpo_user );
5339
				if ( is_a( $jpUser, 'WP_User' ) ) {
5340
					wp_set_current_user( $jpUser->ID );
5341
					$user_can = is_multisite()
5342
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5343
						: current_user_can( 'manage_options' );
5344
					if ( $user_can ) {
5345
						$token_type = 'user';
5346
						$token->external_user_id = $jpUser->ID;
5347
					}
5348
				}
5349
			}
5350
		}
5351
5352
		$this->xmlrpc_verification = array(
5353
			'type'      => $token_type,
5354
			'token_key' => $token_key,
5355
			'user_id'   => $token->external_user_id,
5356
		);
5357
5358
		return $this->xmlrpc_verification;
5359
	}
5360
5361
	/**
5362
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5363
	 */
5364
	function authenticate_jetpack( $user, $username, $password ) {
5365
		if ( is_a( $user, 'WP_User' ) ) {
5366
			return $user;
5367
		}
5368
5369
		$token_details = $this->verify_xml_rpc_signature();
5370
5371
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5372
			return $user;
5373
		}
5374
5375
		if ( 'user' !== $token_details['type'] ) {
5376
			return $user;
5377
		}
5378
5379
		if ( ! $token_details['user_id'] ) {
5380
			return $user;
5381
		}
5382
5383
		nocache_headers();
5384
5385
		return new WP_User( $token_details['user_id'] );
5386
	}
5387
5388
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5389
	// Uses the existing XMLRPC request signing implementation.
5390
	function wp_rest_authenticate( $user ) {
5391
		if ( ! empty( $user ) ) {
5392
			// Another authentication method is in effect.
5393
			return $user;
5394
		}
5395
5396
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5397
			// Nothing to do for this authentication method.
5398
			return null;
5399
		}
5400
5401
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5402
			// Nothing to do for this authentication method.
5403
			return null;
5404
		}
5405
5406
		// Ensure that we always have the request body available.  At this
5407
		// point, the WP REST API code to determine the request body has not
5408
		// run yet.  That code may try to read from 'php://input' later, but
5409
		// this can only be done once per request in PHP versions prior to 5.6.
5410
		// So we will go ahead and perform this read now if needed, and save
5411
		// the request body where both the Jetpack signature verification code
5412
		// and the WP REST API code can see it.
5413
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5414
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5415
		}
5416
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5417
5418
		// Only support specific request parameters that have been tested and
5419
		// are known to work with signature verification.  A different method
5420
		// can be passed to the WP REST API via the '?_method=' parameter if
5421
		// needed.
5422
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5423
			$this->rest_authentication_status = new WP_Error(
5424
				'rest_invalid_request',
5425
				__( 'This request method is not supported.', 'jetpack' ),
5426
				array( 'status' => 400 )
5427
			);
5428
			return null;
5429
		}
5430
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5431
			$this->rest_authentication_status = new WP_Error(
5432
				'rest_invalid_request',
5433
				__( 'This request method does not support body parameters.', 'jetpack' ),
5434
				array( 'status' => 400 )
5435
			);
5436
			return null;
5437
		}
5438
5439
		$verified = $this->verify_xml_rpc_signature();
5440
5441
		if ( is_wp_error( $verified ) ) {
5442
			$this->rest_authentication_status = $verified;
5443
			return null;
5444
		}
5445
5446
		if (
5447
			$verified &&
5448
			isset( $verified['type'] ) &&
5449
			'user' === $verified['type'] &&
5450
			! empty( $verified['user_id'] )
5451
		) {
5452
			// Authentication successful.
5453
			$this->rest_authentication_status = true;
5454
			return $verified['user_id'];
5455
		}
5456
5457
		// Something else went wrong.  Probably a signature error.
5458
		$this->rest_authentication_status = new WP_Error(
5459
			'rest_invalid_signature',
5460
			__( 'The request is not signed correctly.', 'jetpack' ),
5461
			array( 'status' => 400 )
5462
		);
5463
		return null;
5464
	}
5465
5466
	/**
5467
	 * Report authentication status to the WP REST API.
5468
	 *
5469
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5470
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5471
	 */
5472
	public function wp_rest_authentication_errors( $value ) {
5473
		if ( $value !== null ) {
5474
			return $value;
5475
		}
5476
		return $this->rest_authentication_status;
5477
	}
5478
5479
	function add_nonce( $timestamp, $nonce ) {
5480
		global $wpdb;
5481
		static $nonces_used_this_request = array();
5482
5483
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5484
			return $nonces_used_this_request["$timestamp:$nonce"];
5485
		}
5486
5487
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5488
		$timestamp = (int) $timestamp;
5489
		$nonce     = esc_sql( $nonce );
5490
5491
		// Raw query so we can avoid races: add_option will also update
5492
		$show_errors = $wpdb->show_errors( false );
5493
5494
		$old_nonce = $wpdb->get_row(
5495
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5496
		);
5497
5498
		if ( is_null( $old_nonce ) ) {
5499
			$return = $wpdb->query(
5500
				$wpdb->prepare(
5501
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5502
					"jetpack_nonce_{$timestamp}_{$nonce}",
5503
					time(),
5504
					'no'
5505
				)
5506
			);
5507
		} else {
5508
			$return = false;
5509
		}
5510
5511
		$wpdb->show_errors( $show_errors );
5512
5513
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5514
5515
		return $return;
5516
	}
5517
5518
	/**
5519
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5520
	 * Capture it here so we can verify the signature later.
5521
	 */
5522
	function xmlrpc_methods( $methods ) {
5523
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5524
		return $methods;
5525
	}
5526
5527
	function public_xmlrpc_methods( $methods ) {
5528
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5529
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5530
		}
5531
		return $methods;
5532
	}
5533
5534
	function jetpack_getOptions( $args ) {
5535
		global $wp_xmlrpc_server;
5536
5537
		$wp_xmlrpc_server->escape( $args );
5538
5539
		$username	= $args[1];
5540
		$password	= $args[2];
5541
5542
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5543
			return $wp_xmlrpc_server->error;
5544
		}
5545
5546
		$options = array();
5547
		$user_data = $this->get_connected_user_data();
5548
		if ( is_array( $user_data ) ) {
5549
			$options['jetpack_user_id'] = array(
5550
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5551
				'readonly'      => true,
5552
				'value'         => $user_data['ID'],
5553
			);
5554
			$options['jetpack_user_login'] = array(
5555
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5556
				'readonly'      => true,
5557
				'value'         => $user_data['login'],
5558
			);
5559
			$options['jetpack_user_email'] = array(
5560
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5561
				'readonly'      => true,
5562
				'value'         => $user_data['email'],
5563
			);
5564
			$options['jetpack_user_site_count'] = array(
5565
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5566
				'readonly'      => true,
5567
				'value'         => $user_data['site_count'],
5568
			);
5569
		}
5570
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5571
		$args = stripslashes_deep( $args );
5572
		return $wp_xmlrpc_server->wp_getOptions( $args );
5573
	}
5574
5575
	function xmlrpc_options( $options ) {
5576
		$jetpack_client_id = false;
5577
		if ( self::is_active() ) {
5578
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5579
		}
5580
		$options['jetpack_version'] = array(
5581
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5582
				'readonly'      => true,
5583
				'value'         => JETPACK__VERSION,
5584
		);
5585
5586
		$options['jetpack_client_id'] = array(
5587
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5588
				'readonly'      => true,
5589
				'value'         => $jetpack_client_id,
5590
		);
5591
		return $options;
5592
	}
5593
5594
	public static function clean_nonces( $all = false ) {
5595
		global $wpdb;
5596
5597
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5598
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5599
5600
		if ( true !== $all ) {
5601
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5602
			$sql_args[] = time() - 3600;
5603
		}
5604
5605
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5606
5607
		$sql = $wpdb->prepare( $sql, $sql_args );
5608
5609
		for ( $i = 0; $i < 1000; $i++ ) {
5610
			if ( ! $wpdb->query( $sql ) ) {
5611
				break;
5612
			}
5613
		}
5614
	}
5615
5616
	/**
5617
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5618
	 * SET: state( $key, $value );
5619
	 * GET: $value = state( $key );
5620
	 *
5621
	 * @param string $key
5622
	 * @param string $value
5623
	 * @param bool $restate private
5624
	 */
5625
	public static function state( $key = null, $value = null, $restate = false ) {
5626
		static $state = array();
5627
		static $path, $domain;
5628
		if ( ! isset( $path ) ) {
5629
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5630
			$admin_url = Jetpack::admin_url();
5631
			$bits      = wp_parse_url( $admin_url );
5632
5633
			if ( is_array( $bits ) ) {
5634
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5635
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5636
			} else {
5637
				$path = $domain = null;
5638
			}
5639
		}
5640
5641
		// Extract state from cookies and delete cookies
5642
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5643
			$yum = $_COOKIE[ 'jetpackState' ];
5644
			unset( $_COOKIE[ 'jetpackState' ] );
5645
			foreach ( $yum as $k => $v ) {
5646
				if ( strlen( $v ) )
5647
					$state[ $k ] = $v;
5648
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5649
			}
5650
		}
5651
5652
		if ( $restate ) {
5653
			foreach ( $state as $k => $v ) {
5654
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5655
			}
5656
			return;
5657
		}
5658
5659
		// Get a state variable
5660
		if ( isset( $key ) && ! isset( $value ) ) {
5661
			if ( array_key_exists( $key, $state ) )
5662
				return $state[ $key ];
5663
			return null;
5664
		}
5665
5666
		// Set a state variable
5667
		if ( isset ( $key ) && isset( $value ) ) {
5668
			if( is_array( $value ) && isset( $value[0] ) ) {
5669
				$value = $value[0];
5670
			}
5671
			$state[ $key ] = $value;
5672
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5673
		}
5674
	}
5675
5676
	public static function restate() {
5677
		Jetpack::state( null, null, true );
5678
	}
5679
5680
	public static function check_privacy( $file ) {
5681
		static $is_site_publicly_accessible = null;
5682
5683
		if ( is_null( $is_site_publicly_accessible ) ) {
5684
			$is_site_publicly_accessible = false;
5685
5686
			Jetpack::load_xml_rpc_client();
5687
			$rpc = new Jetpack_IXR_Client();
5688
5689
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5690
			if ( $success ) {
5691
				$response = $rpc->getResponse();
5692
				if ( $response ) {
5693
					$is_site_publicly_accessible = true;
5694
				}
5695
			}
5696
5697
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5698
		}
5699
5700
		if ( $is_site_publicly_accessible ) {
5701
			return;
5702
		}
5703
5704
		$module_slug = self::get_module_slug( $file );
5705
5706
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5707
		if ( ! $privacy_checks ) {
5708
			$privacy_checks = $module_slug;
5709
		} else {
5710
			$privacy_checks .= ",$module_slug";
5711
		}
5712
5713
		Jetpack::state( 'privacy_checks', $privacy_checks );
5714
	}
5715
5716
	/**
5717
	 * Helper method for multicall XMLRPC.
5718
	 */
5719
	public static function xmlrpc_async_call() {
5720
		global $blog_id;
5721
		static $clients = array();
5722
5723
		$client_blog_id = is_multisite() ? $blog_id : 0;
5724
5725
		if ( ! isset( $clients[$client_blog_id] ) ) {
5726
			Jetpack::load_xml_rpc_client();
5727
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5728
			if ( function_exists( 'ignore_user_abort' ) ) {
5729
				ignore_user_abort( true );
5730
			}
5731
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5732
		}
5733
5734
		$args = func_get_args();
5735
5736
		if ( ! empty( $args[0] ) ) {
5737
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5738
		} elseif ( is_multisite() ) {
5739
			foreach ( $clients as $client_blog_id => $client ) {
5740
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5741
					continue;
5742
				}
5743
5744
				$switch_success = switch_to_blog( $client_blog_id, true );
5745
				if ( ! $switch_success ) {
5746
					continue;
5747
				}
5748
5749
				flush();
5750
				$client->query();
5751
5752
				restore_current_blog();
5753
			}
5754
		} else {
5755
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5756
				flush();
5757
				$clients[0]->query();
5758
			}
5759
		}
5760
	}
5761
5762
	public static function staticize_subdomain( $url ) {
5763
5764
		// Extract hostname from URL
5765
		$host = parse_url( $url, PHP_URL_HOST );
5766
5767
		// Explode hostname on '.'
5768
		$exploded_host = explode( '.', $host );
5769
5770
		// Retrieve the name and TLD
5771
		if ( count( $exploded_host ) > 1 ) {
5772
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5773
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5774
			// Rebuild domain excluding subdomains
5775
			$domain = $name . '.' . $tld;
5776
		} else {
5777
			$domain = $host;
5778
		}
5779
		// Array of Automattic domains
5780
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5781
5782
		// Return $url if not an Automattic domain
5783
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5784
			return $url;
5785
		}
5786
5787
		if ( is_ssl() ) {
5788
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5789
		}
5790
5791
		srand( crc32( basename( $url ) ) );
5792
		$static_counter = rand( 0, 2 );
5793
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5794
5795
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5796
	}
5797
5798
/* JSON API Authorization */
5799
5800
	/**
5801
	 * Handles the login action for Authorizing the JSON API
5802
	 */
5803
	function login_form_json_api_authorization() {
5804
		$this->verify_json_api_authorization_request();
5805
5806
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5807
5808
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5809
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5810
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5811
	}
5812
5813
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5814
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5815
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5816
			return $url;
5817
		}
5818
5819
		$parsed_url = parse_url( $url );
5820
		$url = strtok( $url, '?' );
5821
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5822
		if ( ! empty( $parsed_url['query'] ) )
5823
			$url .= "&{$parsed_url['query']}";
5824
5825
		return $url;
5826
	}
5827
5828
	// Make sure the POSTed request is handled by the same action
5829
	function preserve_action_in_login_form_for_json_api_authorization() {
5830
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5831
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5832
	}
5833
5834
	// If someone logs in to approve API access, store the Access Code in usermeta
5835
	function store_json_api_authorization_token( $user_login, $user ) {
5836
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5837
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5838
		$token = wp_generate_password( 32, false );
5839
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5840
	}
5841
5842
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5843
	function allow_wpcom_public_api_domain( $domains ) {
5844
		$domains[] = 'public-api.wordpress.com';
5845
		return $domains;
5846
	}
5847
5848
	static function is_redirect_encoded( $redirect_url ) {
5849
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5850
	}
5851
5852
	// Add all wordpress.com environments to the safe redirect whitelist
5853
	function allow_wpcom_environments( $domains ) {
5854
		$domains[] = 'wordpress.com';
5855
		$domains[] = 'wpcalypso.wordpress.com';
5856
		$domains[] = 'horizon.wordpress.com';
5857
		$domains[] = 'calypso.localhost';
5858
		return $domains;
5859
	}
5860
5861
	// Add the Access Code details to the public-api.wordpress.com redirect
5862
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5863
		return add_query_arg(
5864
			urlencode_deep(
5865
				array(
5866
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5867
					'jetpack-user-id' => (int) $user->ID,
5868
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5869
				)
5870
			),
5871
			$redirect_to
5872
		);
5873
	}
5874
5875
5876
	/**
5877
	 * Verifies the request by checking the signature
5878
	 *
5879
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5880
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5881
	 *
5882
	 * @param null|array $environment
5883
	 */
5884
	function verify_json_api_authorization_request( $environment = null ) {
5885
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5886
5887
		$environment = is_null( $environment )
5888
			? $_REQUEST
5889
			: $environment;
5890
5891
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5892
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5893
		if ( ! $token || empty( $token->secret ) ) {
5894
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5895
		}
5896
5897
		$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' );
5898
5899
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5900
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5901
			JetpackTracking::record_user_event( 'error_double_encode' );
5902
5903
			$die_error = sprintf(
5904
				/* translators: %s is a URL */
5905
				__( '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' ),
5906
				'https://jetpack.com/support/double-encoding/'
5907
			);
5908
		}
5909
5910
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5911
5912
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5913
			$signature = $jetpack_signature->sign_request(
5914
				$environment['token'],
5915
				$environment['timestamp'],
5916
				$environment['nonce'],
5917
				'',
5918
				'GET',
5919
				$environment['jetpack_json_api_original_query'],
5920
				null,
5921
				true
5922
			);
5923
		} else {
5924
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5925
		}
5926
5927
		if ( ! $signature ) {
5928
			wp_die( $die_error );
5929
		} else if ( is_wp_error( $signature ) ) {
5930
			wp_die( $die_error );
5931
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5932
			if ( is_ssl() ) {
5933
				// 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
5934
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5935
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5936
					wp_die( $die_error );
5937
				}
5938
			} else {
5939
				wp_die( $die_error );
5940
			}
5941
		}
5942
5943
		$timestamp = (int) $environment['timestamp'];
5944
		$nonce     = stripslashes( (string) $environment['nonce'] );
5945
5946
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5947
			// De-nonce the nonce, at least for 5 minutes.
5948
			// 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)
5949
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5950
			if ( $old_nonce_time < time() - 300 ) {
5951
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5952
			}
5953
		}
5954
5955
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5956
		$data_filters = array(
5957
			'state'        => 'opaque',
5958
			'client_id'    => 'int',
5959
			'client_title' => 'string',
5960
			'client_image' => 'url',
5961
		);
5962
5963
		foreach ( $data_filters as $key => $sanitation ) {
5964
			if ( ! isset( $data->$key ) ) {
5965
				wp_die( $die_error );
5966
			}
5967
5968
			switch ( $sanitation ) {
5969
			case 'int' :
5970
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5971
				break;
5972
			case 'opaque' :
5973
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5974
				break;
5975
			case 'string' :
5976
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5977
				break;
5978
			case 'url' :
5979
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5980
				break;
5981
			}
5982
		}
5983
5984
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5985
			wp_die( $die_error );
5986
		}
5987
	}
5988
5989
	function login_message_json_api_authorization( $message ) {
5990
		return '<p class="message">' . sprintf(
5991
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5992
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5993
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5994
	}
5995
5996
	/**
5997
	 * Get $content_width, but with a <s>twist</s> filter.
5998
	 */
5999
	public static function get_content_width() {
6000
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6001
			? $GLOBALS['content_width']
6002
			: false;
6003
		/**
6004
		 * Filter the Content Width value.
6005
		 *
6006
		 * @since 2.2.3
6007
		 *
6008
		 * @param string $content_width Content Width value.
6009
		 */
6010
		return apply_filters( 'jetpack_content_width', $content_width );
6011
	}
6012
6013
	/**
6014
	 * Pings the WordPress.com Mirror Site for the specified options.
6015
	 *
6016
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6017
	 *
6018
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6019
	 */
6020
	public function get_cloud_site_options( $option_names ) {
6021
		$option_names = array_filter( (array) $option_names, 'is_string' );
6022
6023
		Jetpack::load_xml_rpc_client();
6024
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6025
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6026
		if ( $xml->isError() ) {
6027
			return array(
6028
				'error_code' => $xml->getErrorCode(),
6029
				'error_msg'  => $xml->getErrorMessage(),
6030
			);
6031
		}
6032
		$cloud_site_options = $xml->getResponse();
6033
6034
		return $cloud_site_options;
6035
	}
6036
6037
	/**
6038
	 * Checks if the site is currently in an identity crisis.
6039
	 *
6040
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6041
	 */
6042
	public static function check_identity_crisis() {
6043
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6044
			return false;
6045
		}
6046
6047
		return Jetpack_Options::get_option( 'sync_error_idc' );
6048
	}
6049
6050
	/**
6051
	 * Checks whether the home and siteurl specifically are whitelisted
6052
	 * Written so that we don't have re-check $key and $value params every time
6053
	 * we want to check if this site is whitelisted, for example in footer.php
6054
	 *
6055
	 * @since  3.8.0
6056
	 * @return bool True = already whitelisted False = not whitelisted
6057
	 */
6058
	public static function is_staging_site() {
6059
		$is_staging = false;
6060
6061
		$known_staging = array(
6062
			'urls' => array(
6063
				'#\.staging\.wpengine\.com$#i', // WP Engine
6064
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6065
				),
6066
			'constants' => array(
6067
				'IS_WPE_SNAPSHOT',      // WP Engine
6068
				'KINSTA_DEV_ENV',       // Kinsta.com
6069
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6070
				'JETPACK_STAGING_MODE', // Generic
6071
				)
6072
			);
6073
		/**
6074
		 * Filters the flags of known staging sites.
6075
		 *
6076
		 * @since 3.9.0
6077
		 *
6078
		 * @param array $known_staging {
6079
		 *     An array of arrays that each are used to check if the current site is staging.
6080
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6081
		 *     @type array $constants PHP constants of known staging/developement environments.
6082
		 *  }
6083
		 */
6084
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6085
6086
		if ( isset( $known_staging['urls'] ) ) {
6087
			foreach ( $known_staging['urls'] as $url ){
6088
				if ( preg_match( $url, site_url() ) ) {
6089
					$is_staging = true;
6090
					break;
6091
				}
6092
			}
6093
		}
6094
6095
		if ( isset( $known_staging['constants'] ) ) {
6096
			foreach ( $known_staging['constants'] as $constant ) {
6097
				if ( defined( $constant ) && constant( $constant ) ) {
6098
					$is_staging = true;
6099
				}
6100
			}
6101
		}
6102
6103
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6104
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6105
			$is_staging = true;
6106
		}
6107
6108
		/**
6109
		 * Filters is_staging_site check.
6110
		 *
6111
		 * @since 3.9.0
6112
		 *
6113
		 * @param bool $is_staging If the current site is a staging site.
6114
		 */
6115
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6116
	}
6117
6118
	/**
6119
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6120
	 *
6121
	 * @since 4.4.0
6122
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6123
	 *
6124
	 * @return bool
6125
	 */
6126
	public static function validate_sync_error_idc_option() {
6127
		$is_valid = false;
6128
6129
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6130
		if ( false === $idc_allowed ) {
6131
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6132
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6133
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6134
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6135
				$transient_duration = HOUR_IN_SECONDS;
6136
			} else {
6137
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6138
				$idc_allowed = '1';
6139
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6140
			}
6141
6142
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6143
		}
6144
6145
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6146
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6147
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6148
			$local_options = self::get_sync_error_idc_option();
6149
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6150
				$is_valid = true;
6151
			}
6152
		}
6153
6154
		/**
6155
		 * Filters whether the sync_error_idc option is valid.
6156
		 *
6157
		 * @since 4.4.0
6158
		 *
6159
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6160
		 */
6161
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6162
6163
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6164
			// Since the option exists, and did not validate, delete it
6165
			Jetpack_Options::delete_option( 'sync_error_idc' );
6166
		}
6167
6168
		return $is_valid;
6169
	}
6170
6171
	/**
6172
	 * Normalizes a url by doing three things:
6173
	 *  - Strips protocol
6174
	 *  - Strips www
6175
	 *  - Adds a trailing slash
6176
	 *
6177
	 * @since 4.4.0
6178
	 * @param string $url
6179
	 * @return WP_Error|string
6180
	 */
6181
	public static function normalize_url_protocol_agnostic( $url ) {
6182
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6183
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6184
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6185
		}
6186
6187
		// Strip www and protocols
6188
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6189
		return $url;
6190
	}
6191
6192
	/**
6193
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6194
	 *
6195
	 * @since 4.4.0
6196
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6197
	 *
6198
	 * @param array $response
6199
	 * @return array Array of the local urls, wpcom urls, and error code
6200
	 */
6201
	public static function get_sync_error_idc_option( $response = array() ) {
6202
		// Since the local options will hit the database directly, store the values
6203
		// in a transient to allow for autoloading and caching on subsequent views.
6204
		$local_options = get_transient( 'jetpack_idc_local' );
6205
		if ( false === $local_options ) {
6206
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6207
			$local_options = array(
6208
				'home'    => Jetpack_Sync_Functions::home_url(),
6209
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6210
			);
6211
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6212
		}
6213
6214
		$options = array_merge( $local_options, $response );
6215
6216
		$returned_values = array();
6217
		foreach( $options as $key => $option ) {
6218
			if ( 'error_code' === $key ) {
6219
				$returned_values[ $key ] = $option;
6220
				continue;
6221
			}
6222
6223
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6224
				continue;
6225
			}
6226
6227
			$returned_values[ $key ] = $normalized_url;
6228
		}
6229
6230
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6231
6232
		return $returned_values;
6233
	}
6234
6235
	/**
6236
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6237
	 * If set to true, the site will be put into staging mode.
6238
	 *
6239
	 * @since 4.3.2
6240
	 * @return bool
6241
	 */
6242
	public static function sync_idc_optin() {
6243
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6244
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6245
		} else {
6246
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6247
		}
6248
6249
		/**
6250
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6251
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6252
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6253
		 *
6254
		 * @since 4.3.2
6255
		 *
6256
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6257
		 */
6258
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6259
	}
6260
6261
	/**
6262
	 * Maybe Use a .min.css stylesheet, maybe not.
6263
	 *
6264
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6265
	 */
6266
	public static function maybe_min_asset( $url, $path, $plugin ) {
6267
		// Short out on things trying to find actual paths.
6268
		if ( ! $path || empty( $plugin ) ) {
6269
			return $url;
6270
		}
6271
6272
		$path = ltrim( $path, '/' );
6273
6274
		// Strip out the abspath.
6275
		$base = dirname( plugin_basename( $plugin ) );
6276
6277
		// Short out on non-Jetpack assets.
6278
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6279
			return $url;
6280
		}
6281
6282
		// File name parsing.
6283
		$file              = "{$base}/{$path}";
6284
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6285
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6286
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6287
		$extension         = array_shift( $file_name_parts_r );
6288
6289
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6290
			// Already pointing at the minified version.
6291
			if ( 'min' === $file_name_parts_r[0] ) {
6292
				return $url;
6293
			}
6294
6295
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6296
			if ( file_exists( $min_full_path ) ) {
6297
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6298
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6299
				if ( 'css' === $extension ) {
6300
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6301
					self::$min_assets[ $key ] = $path;
6302
				}
6303
			}
6304
		}
6305
6306
		return $url;
6307
	}
6308
6309
	/**
6310
	 * If the asset is minified, let's flag .min as the suffix.
6311
	 *
6312
	 * Attached to `style_loader_src` filter.
6313
	 *
6314
	 * @param string $tag The tag that would link to the external asset.
6315
	 * @param string $handle The registered handle of the script in question.
6316
	 * @param string $href The url of the asset in question.
6317
	 */
6318
	public static function set_suffix_on_min( $src, $handle ) {
6319
		if ( false === strpos( $src, '.min.css' ) ) {
6320
			return $src;
6321
		}
6322
6323
		if ( ! empty( self::$min_assets ) ) {
6324
			foreach ( self::$min_assets as $file => $path ) {
6325
				if ( false !== strpos( $src, $file ) ) {
6326
					wp_style_add_data( $handle, 'suffix', '.min' );
6327
					return $src;
6328
				}
6329
			}
6330
		}
6331
6332
		return $src;
6333
	}
6334
6335
	/**
6336
	 * Maybe inlines a stylesheet.
6337
	 *
6338
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6339
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6340
	 *
6341
	 * Attached to `style_loader_tag` filter.
6342
	 *
6343
	 * @param string $tag The tag that would link to the external asset.
6344
	 * @param string $handle The registered handle of the script in question.
6345
	 *
6346
	 * @return string
6347
	 */
6348
	public static function maybe_inline_style( $tag, $handle ) {
6349
		global $wp_styles;
6350
		$item = $wp_styles->registered[ $handle ];
6351
6352
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6353
			return $tag;
6354
		}
6355
6356
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6357
			$href = $matches[1];
6358
			// Strip off query string
6359
			if ( $pos = strpos( $href, '?' ) ) {
6360
				$href = substr( $href, 0, $pos );
6361
			}
6362
			// Strip off fragment
6363
			if ( $pos = strpos( $href, '#' ) ) {
6364
				$href = substr( $href, 0, $pos );
6365
			}
6366
		} else {
6367
			return $tag;
6368
		}
6369
6370
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6371
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6372
			return $tag;
6373
		}
6374
6375
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6376
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6377
			// And this isn't the pass that actually deals with the RTL version...
6378
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6379
				// Short out, as the RTL version will deal with it in a moment.
6380
				return $tag;
6381
			}
6382
		}
6383
6384
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6385
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6386
		if ( $css ) {
6387
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6388
			if ( empty( $item->extra['after'] ) ) {
6389
				wp_add_inline_style( $handle, $css );
6390
			} else {
6391
				array_unshift( $item->extra['after'], $css );
6392
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6393
			}
6394
		}
6395
6396
		return $tag;
6397
	}
6398
6399
	/**
6400
	 * Loads a view file from the views
6401
	 *
6402
	 * Data passed in with the $data parameter will be available in the
6403
	 * template file as $data['value']
6404
	 *
6405
	 * @param string $template - Template file to load
6406
	 * @param array $data - Any data to pass along to the template
6407
	 * @return boolean - If template file was found
6408
	 **/
6409
	public function load_view( $template, $data = array() ) {
6410
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6411
6412
		if( file_exists( $views_dir . $template ) ) {
6413
			require_once( $views_dir . $template );
6414
			return true;
6415
		}
6416
6417
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6418
		return false;
6419
	}
6420
6421
	/**
6422
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6423
	 */
6424
	public function deprecated_hooks() {
6425
		global $wp_filter;
6426
6427
		/*
6428
		 * Format:
6429
		 * deprecated_filter_name => replacement_name
6430
		 *
6431
		 * If there is no replacement, use null for replacement_name
6432
		 */
6433
		$deprecated_list = array(
6434
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6435
			'wpl_sharing_2014_1'                                     => null,
6436
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6437
			'jetpack_identity_crisis_options_to_check'               => null,
6438
			'update_option_jetpack_single_user_site'                 => null,
6439
			'audio_player_default_colors'                            => null,
6440
			'add_option_jetpack_featured_images_enabled'             => null,
6441
			'add_option_jetpack_update_details'                      => null,
6442
			'add_option_jetpack_updates'                             => null,
6443
			'add_option_jetpack_network_name'                        => null,
6444
			'add_option_jetpack_network_allow_new_registrations'     => null,
6445
			'add_option_jetpack_network_add_new_users'               => null,
6446
			'add_option_jetpack_network_site_upload_space'           => null,
6447
			'add_option_jetpack_network_upload_file_types'           => null,
6448
			'add_option_jetpack_network_enable_administration_menus' => null,
6449
			'add_option_jetpack_is_multi_site'                       => null,
6450
			'add_option_jetpack_is_main_network'                     => null,
6451
			'add_option_jetpack_main_network_site'                   => null,
6452
			'jetpack_sync_all_registered_options'                    => null,
6453
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6454
			'jetpack_is_post_mailable'                               => null,
6455
			'jetpack_seo_site_host'                                  => null,
6456
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6457
			'jetpack_holiday_snow_option_name'                       => null,
6458
			'jetpack_holiday_chance_of_snow'                         => null,
6459
			'jetpack_holiday_snow_js_url'                            => null,
6460
			'jetpack_is_holiday_snow_season'                         => null,
6461
			'jetpack_holiday_snow_option_updated'                    => null,
6462
			'jetpack_holiday_snowing'                                => null,
6463
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6464
			'jetpack_cache_plans'                                    => null,
6465
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6466
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6467
			'jetpack_enable_site_verification'                       => null,
6468
			'can_display_jetpack_manage_notice'                      => null,
6469
			// Removed in Jetpack 7.3.0
6470
			'atd_load_scripts'                                       => null,
6471
			'atd_http_post_timeout'                                  => null,
6472
			'atd_http_post_error'                                    => null,
6473
			'atd_service_domain'                                     => null,
6474
		);
6475
6476
		// This is a silly loop depth. Better way?
6477
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6478
			if ( has_action( $hook ) ) {
6479
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6480
					foreach( $values AS $hooked ) {
6481
						if ( is_callable( $hooked['function'] ) ) {
6482
							$function_name = 'an anonymous function';
6483
						} else {
6484
							$function_name = $hooked['function'];
6485
						}
6486
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6487
					}
6488
				}
6489
			}
6490
		}
6491
	}
6492
6493
	/**
6494
	 * Converts any url in a stylesheet, to the correct absolute url.
6495
	 *
6496
	 * Considerations:
6497
	 *  - Normal, relative URLs     `feh.png`
6498
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6499
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6500
	 *  - Absolute URLs             `http://domain.com/feh.png`
6501
	 *  - Domain root relative URLs `/feh.png`
6502
	 *
6503
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6504
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6505
	 *
6506
	 * @return mixed|string
6507
	 */
6508
	public static function absolutize_css_urls( $css, $css_file_url ) {
6509
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6510
		$css_dir = dirname( $css_file_url );
6511
		$p       = parse_url( $css_dir );
6512
		$domain  = sprintf(
6513
					'%1$s//%2$s%3$s%4$s',
6514
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6515
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6516
					$p['host'],
6517
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6518
				);
6519
6520
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6521
			$find = $replace = array();
6522
			foreach ( $matches as $match ) {
6523
				$url = trim( $match['path'], "'\" \t" );
6524
6525
				// If this is a data url, we don't want to mess with it.
6526
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6527
					continue;
6528
				}
6529
6530
				// If this is an absolute or protocol-agnostic url,
6531
				// we don't want to mess with it.
6532
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6533
					continue;
6534
				}
6535
6536
				switch ( substr( $url, 0, 1 ) ) {
6537
					case '/':
6538
						$absolute = $domain . $url;
6539
						break;
6540
					default:
6541
						$absolute = $css_dir . '/' . $url;
6542
				}
6543
6544
				$find[]    = $match[0];
6545
				$replace[] = sprintf( 'url("%s")', $absolute );
6546
			}
6547
			$css = str_replace( $find, $replace, $css );
6548
		}
6549
6550
		return $css;
6551
	}
6552
6553
	/**
6554
	 * This methods removes all of the registered css files on the front end
6555
	 * from Jetpack in favor of using a single file. In effect "imploding"
6556
	 * all the files into one file.
6557
	 *
6558
	 * Pros:
6559
	 * - Uses only ONE css asset connection instead of 15
6560
	 * - Saves a minimum of 56k
6561
	 * - Reduces server load
6562
	 * - Reduces time to first painted byte
6563
	 *
6564
	 * Cons:
6565
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6566
	 *		should not cause any issues with themes.
6567
	 * - Plugins/themes dequeuing styles no longer do anything. See
6568
	 *		jetpack_implode_frontend_css filter for a workaround
6569
	 *
6570
	 * For some situations developers may wish to disable css imploding and
6571
	 * instead operate in legacy mode where each file loads seperately and
6572
	 * can be edited individually or dequeued. This can be accomplished with
6573
	 * the following line:
6574
	 *
6575
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6576
	 *
6577
	 * @since 3.2
6578
	 **/
6579
	public function implode_frontend_css( $travis_test = false ) {
6580
		$do_implode = true;
6581
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6582
			$do_implode = false;
6583
		}
6584
6585
		// Do not implode CSS when the page loads via the AMP plugin.
6586
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6587
			$do_implode = false;
6588
		}
6589
6590
		/**
6591
		 * Allow CSS to be concatenated into a single jetpack.css file.
6592
		 *
6593
		 * @since 3.2.0
6594
		 *
6595
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6596
		 */
6597
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6598
6599
		// Do not use the imploded file when default behavior was altered through the filter
6600
		if ( ! $do_implode ) {
6601
			return;
6602
		}
6603
6604
		// We do not want to use the imploded file in dev mode, or if not connected
6605
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6606
			if ( ! $travis_test ) {
6607
				return;
6608
			}
6609
		}
6610
6611
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6612
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6613
			return;
6614
		}
6615
6616
		/*
6617
		 * Now we assume Jetpack is connected and able to serve the single
6618
		 * file.
6619
		 *
6620
		 * In the future there will be a check here to serve the file locally
6621
		 * or potentially from the Jetpack CDN
6622
		 *
6623
		 * For now:
6624
		 * - Enqueue a single imploded css file
6625
		 * - Zero out the style_loader_tag for the bundled ones
6626
		 * - Be happy, drink scotch
6627
		 */
6628
6629
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6630
6631
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6632
6633
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6634
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6635
	}
6636
6637
	function concat_remove_style_loader_tag( $tag, $handle ) {
6638
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6639
			$tag = '';
6640
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6641
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6642
			}
6643
		}
6644
6645
		return $tag;
6646
	}
6647
6648
	/*
6649
	 * Check the heartbeat data
6650
	 *
6651
	 * Organizes the heartbeat data by severity.  For example, if the site
6652
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6653
	 *
6654
	 * Data will be added to "caution" array, if it either:
6655
	 *  - Out of date Jetpack version
6656
	 *  - Out of date WP version
6657
	 *  - Out of date PHP version
6658
	 *
6659
	 * $return array $filtered_data
6660
	 */
6661
	public static function jetpack_check_heartbeat_data() {
6662
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6663
6664
		$good    = array();
6665
		$caution = array();
6666
		$bad     = array();
6667
6668
		foreach ( $raw_data as $stat => $value ) {
6669
6670
			// Check jetpack version
6671
			if ( 'version' == $stat ) {
6672
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6673
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6674
					continue;
6675
				}
6676
			}
6677
6678
			// Check WP version
6679
			if ( 'wp-version' == $stat ) {
6680
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6681
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6682
					continue;
6683
				}
6684
			}
6685
6686
			// Check PHP version
6687
			if ( 'php-version' == $stat ) {
6688
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6689
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6690
					continue;
6691
				}
6692
			}
6693
6694
			// Check ID crisis
6695
			if ( 'identitycrisis' == $stat ) {
6696
				if ( 'yes' == $value ) {
6697
					$bad[ $stat ] = $value;
6698
					continue;
6699
				}
6700
			}
6701
6702
			// The rest are good :)
6703
			$good[ $stat ] = $value;
6704
		}
6705
6706
		$filtered_data = array(
6707
			'good'    => $good,
6708
			'caution' => $caution,
6709
			'bad'     => $bad
6710
		);
6711
6712
		return $filtered_data;
6713
	}
6714
6715
6716
	/*
6717
	 * This method is used to organize all options that can be reset
6718
	 * without disconnecting Jetpack.
6719
	 *
6720
	 * It is used in class.jetpack-cli.php to reset options
6721
	 *
6722
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6723
	 *
6724
	 * @return array of options to delete.
6725
	 */
6726
	public static function get_jetpack_options_for_reset() {
6727
		return Jetpack_Options::get_options_for_reset();
6728
	}
6729
6730
	/*
6731
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6732
	 * so we can bring them directly to their site in calypso.
6733
	 *
6734
	 * @param string | url
6735
	 * @return string | url without the guff
6736
	 */
6737
	public static function build_raw_urls( $url ) {
6738
		$strip_http = '/.*?:\/\//i';
6739
		$url = preg_replace( $strip_http, '', $url  );
6740
		$url = str_replace( '/', '::', $url );
6741
		return $url;
6742
	}
6743
6744
	/**
6745
	 * Stores and prints out domains to prefetch for page speed optimization.
6746
	 *
6747
	 * @param mixed $new_urls
6748
	 */
6749
	public static function dns_prefetch( $new_urls = null ) {
6750
		static $prefetch_urls = array();
6751
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6752
			echo "\r\n";
6753
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6754
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6755
			}
6756
		} elseif ( ! empty( $new_urls ) ) {
6757
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6758
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6759
			}
6760
			foreach ( (array) $new_urls as $this_new_url ) {
6761
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6762
			}
6763
			$prefetch_urls = array_unique( $prefetch_urls );
6764
		}
6765
	}
6766
6767
	public function wp_dashboard_setup() {
6768
		if ( self::is_active() ) {
6769
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6770
		}
6771
6772
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6773
			$widget_title = sprintf(
6774
				wp_kses(
6775
					/* translators: Placeholder is a Jetpack logo. */
6776
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6777
					array( 'span' => array() )
6778
				),
6779
				Jetpack::get_jp_emblem( true )
6780
			);
6781
6782
			wp_add_dashboard_widget(
6783
				'jetpack_summary_widget',
6784
				$widget_title,
6785
				array( __CLASS__, 'dashboard_widget' )
6786
			);
6787
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6788
6789
			// If we're inactive and not in development mode, sort our box to the top.
6790
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6791
				global $wp_meta_boxes;
6792
6793
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6794
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6795
6796
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6797
			}
6798
		}
6799
	}
6800
6801
	/**
6802
	 * @param mixed $result Value for the user's option
6803
	 * @return mixed
6804
	 */
6805
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6806
		if ( ! is_array( $sorted ) ) {
6807
			return $sorted;
6808
		}
6809
6810
		foreach ( $sorted as $box_context => $ids ) {
6811
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6812
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6813
				continue;
6814
			}
6815
6816
			$ids_array = explode( ',', $ids );
6817
			$key = array_search( 'dashboard_stats', $ids_array );
6818
6819
			if ( false !== $key ) {
6820
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6821
				$ids_array[ $key ] = 'jetpack_summary_widget';
6822
				$sorted[ $box_context ] = implode( ',', $ids_array );
6823
				// We've found it, stop searching, and just return.
6824
				break;
6825
			}
6826
		}
6827
6828
		return $sorted;
6829
	}
6830
6831
	public static function dashboard_widget() {
6832
		/**
6833
		 * Fires when the dashboard is loaded.
6834
		 *
6835
		 * @since 3.4.0
6836
		 */
6837
		do_action( 'jetpack_dashboard_widget' );
6838
	}
6839
6840
	public static function dashboard_widget_footer() {
6841
		?>
6842
		<footer>
6843
6844
		<div class="protect">
6845
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6846
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6847
				<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>
6848
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6849
				<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' ); ?>">
6850
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6851
				</a>
6852
			<?php else : ?>
6853
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6854
			<?php endif; ?>
6855
		</div>
6856
6857
		<div class="akismet">
6858
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6859
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6860
				<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>
6861
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6862
				<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">
6863
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6864
				</a>
6865
			<?php else : ?>
6866
				<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>
6867
			<?php endif; ?>
6868
		</div>
6869
6870
		</footer>
6871
		<?php
6872
	}
6873
6874
	/**
6875
	 * Return string containing the Jetpack logo.
6876
	 *
6877
	 * @since 3.9.0
6878
	 *
6879
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6880
	 *
6881
	 * @return string
6882
	 */
6883
	public static function get_jp_emblem( $logotype = false ) {
6884
		$logo = '<path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/>';
6885
		$text = '
6886
<path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" />
6887
<path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" />
6888
<path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" />
6889
<path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" />
6890
<path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" />
6891
<path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" />
6892
<path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" />
6893
		';
6894
6895
		return sprintf(
6896
			'<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 %1$s 32">%2$s</svg>',
6897
			( true === $logotype ? '118' : '32' ),
6898
			( true === $logotype ? $logo . $text : $logo )
6899
		);
6900
	}
6901
6902
	/*
6903
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6904
	 */
6905
	function jetpack_icon_user_connected( $columns ) {
6906
		$columns['user_jetpack'] = '';
6907
		return $columns;
6908
	}
6909
6910
	/*
6911
	 * Show Jetpack icon if the user is linked.
6912
	 */
6913
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6914
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6915
			$emblem_html = sprintf(
6916
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6917
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6918
				Jetpack::get_jp_emblem()
6919
			);
6920
			return $emblem_html;
6921
		}
6922
6923
		return $val;
6924
	}
6925
6926
	/*
6927
	 * Style the Jetpack user column
6928
	 */
6929
	function jetpack_user_col_style() {
6930
		global $current_screen;
6931
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6932
			<style>
6933
				.fixed .column-user_jetpack {
6934
					width: 21px;
6935
				}
6936
				.jp-emblem-user-admin svg {
6937
					width: 20px;
6938
					height: 20px;
6939
				}
6940
				.jp-emblem-user-admin path {
6941
					fill: #00BE28;
6942
				}
6943
			</style>
6944
		<?php }
6945
	}
6946
6947
	/**
6948
	 * Checks if Akismet is active and working.
6949
	 *
6950
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6951
	 * that implied usage of methods present since more recent version.
6952
	 * See https://github.com/Automattic/jetpack/pull/9585
6953
	 *
6954
	 * @since  5.1.0
6955
	 *
6956
	 * @return bool True = Akismet available. False = Aksimet not available.
6957
	 */
6958
	public static function is_akismet_active() {
6959
		static $status = null;
6960
6961
		if ( ! is_null( $status ) ) {
6962
			return $status;
6963
		}
6964
6965
		// Check if a modern version of Akismet is active.
6966
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6967
			$status = false;
6968
			return $status;
6969
		}
6970
6971
		// Make sure there is a key known to Akismet at all before verifying key.
6972
		$akismet_key = Akismet::get_api_key();
6973
		if ( ! $akismet_key ) {
6974
			$status = false;
6975
			return $status;
6976
		}
6977
6978
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6979
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6980
6981
		// Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
6982
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6983
		// We cache the result of the Akismet key verification for ten minutes.
6984
		if ( ! $akismet_key_state || $recheck ) {
6985
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6986
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6987
		}
6988
6989
		$status = 'valid' === $akismet_key_state;
6990
6991
		return $status;
6992
	}
6993
6994
	/**
6995
	 * Checks if one or more function names is in debug_backtrace
6996
	 *
6997
	 * @param $names Mixed string name of function or array of string names of functions
6998
	 *
6999
	 * @return bool
7000
	 */
7001
	public static function is_function_in_backtrace( $names ) {
7002
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
7003
		if ( ! is_array( $names ) ) {
7004
			$names = array( $names );
7005
		}
7006
		$names_as_keys = array_flip( $names );
7007
7008
		//Do check in constant O(1) time for PHP5.5+
7009
		if ( function_exists( 'array_column' ) ) {
7010
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
7011
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
7012
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
7013
			return ! empty ( $intersection );
7014
		}
7015
7016
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
7017
		foreach ( $backtrace as $call ) {
7018
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
7019
				return true;
7020
			}
7021
		}
7022
		return false;
7023
	}
7024
7025
	/**
7026
	 * Given a minified path, and a non-minified path, will return
7027
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7028
	 *
7029
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7030
	 * root Jetpack directory.
7031
	 *
7032
	 * @since 5.6.0
7033
	 *
7034
	 * @param string $min_path
7035
	 * @param string $non_min_path
7036
	 * @return string The URL to the file
7037
	 */
7038
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7039
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
7040
			? $non_min_path
7041
			: $min_path;
7042
7043
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7044
	}
7045
7046
	/**
7047
	 * Checks for whether Jetpack Backup & Scan is enabled.
7048
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7049
	 * @return bool|int|mixed
7050
	 */
7051
	public static function is_rewind_enabled() {
7052
		if ( ! Jetpack::is_active() ) {
7053
			return false;
7054
		}
7055
7056
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7057
		if ( false === $rewind_enabled ) {
7058
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7059
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7060
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7061
				&& ! empty( $rewind_data['state'] )
7062
				&& 'active' === $rewind_data['state'] )
7063
				? 1
7064
				: 0;
7065
7066
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7067
		}
7068
		return $rewind_enabled;
7069
	}
7070
7071
	/**
7072
	 * Return Calypso environment value; used for developing Jetpack and pairing
7073
	 * it with different Calypso enrionments, such as localhost.
7074
	 *
7075
	 * @since 7.4.0
7076
	 *
7077
	 * @return string Calypso environment
7078
	 */
7079
	public static function get_calypso_env() {
7080
		if ( isset( $_GET['calypso_env'] ) ) {
7081
			return sanitize_key( $_GET['calypso_env'] );
7082
		}
7083
7084
		if ( getenv( 'CALYPSO_ENV' ) ) {
7085
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7086
		}
7087
7088
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7089
			return sanitize_key( CALYPSO_ENV );
7090
		}
7091
7092
		return '';
7093
	}
7094
7095
	/**
7096
	 * Checks whether or not TOS has been agreed upon.
7097
	 * Will return true if a user has clicked to register, or is already connected.
7098
	 */
7099
	public static function jetpack_tos_agreed() {
7100
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7101
	}
7102
7103
	/**
7104
	 * Handles activating default modules as well general cleanup for the new connection.
7105
	 *
7106
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7107
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7108
	 * @param boolean $send_state_messages          Whether to send state messages.
7109
	 * @return void
7110
	 */
7111
	public static function handle_post_authorization_actions(
7112
		$activate_sso = false,
7113
		$redirect_on_activation_error = false,
7114
		$send_state_messages = true
7115
	) {
7116
		$other_modules = $activate_sso
7117
			? array( 'sso' )
7118
			: array();
7119
7120
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7121
			Jetpack::delete_active_modules();
7122
7123
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7124
		} else {
7125
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7126
		}
7127
7128
		// Since this is a fresh connection, be sure to clear out IDC options
7129
		Jetpack_IDC::clear_all_idc_options();
7130
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7131
7132
		// Start nonce cleaner
7133
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7134
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7135
7136
		if ( $send_state_messages ) {
7137
			Jetpack::state( 'message', 'authorized' );
7138
		}
7139
	}
7140
7141
	/**
7142
	 * Returns a boolean for whether backups UI should be displayed or not.
7143
	 *
7144
	 * @return bool Should backups UI be displayed?
7145
	 */
7146
	public static function show_backups_ui() {
7147
		/**
7148
		 * Whether UI for backups should be displayed.
7149
		 *
7150
		 * @since 6.5.0
7151
		 *
7152
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7153
		 */
7154
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7155
	}
7156
7157
	/*
7158
	 * Deprecated manage functions
7159
	 */
7160
	function prepare_manage_jetpack_notice() {
7161
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7162
	}
7163
	function manage_activate_screen() {
7164
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7165
	}
7166
	function admin_jetpack_manage_notice() {
7167
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7168
	}
7169
	function opt_out_jetpack_manage_url() {
7170
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7171
	}
7172
	function opt_in_jetpack_manage_url() {
7173
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7174
	}
7175
	function opt_in_jetpack_manage_notice() {
7176
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7177
	}
7178
	function can_display_jetpack_manage_notice() {
7179
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7180
	}
7181
7182
	/**
7183
	 * Clean leftoveruser meta.
7184
	 *
7185
	 * Delete Jetpack-related user meta when it is no longer needed.
7186
	 *
7187
	 * @since 7.3.0
7188
	 *
7189
	 * @param int $user_id User ID being updated.
7190
	 */
7191
	public static function user_meta_cleanup( $user_id ) {
7192
		$meta_keys = array(
7193
			// AtD removed from Jetpack 7.3
7194
			'AtD_options',
7195
			'AtD_check_when',
7196
			'AtD_guess_lang',
7197
			'AtD_ignored_phrases',
7198
		);
7199
7200
		foreach ( $meta_keys as $meta_key ) {
7201
			if ( get_user_meta( $user_id, $meta_key ) ) {
7202
				delete_user_meta( $user_id, $meta_key );
7203
			}
7204
		}
7205
	}
7206
}
7207