Completed
Push — update/remove-after-the-deadli... ( 6e49cc...508f50 )
by
unknown
283:10 queued 275:44
created

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

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...
2892
			Jetpack::state( 'module', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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...
2893
		}
2894
2895
		Jetpack::catch_errors( false );
2896
		/**
2897
		 * Fires when default modules are activated.
2898
		 *
2899
		 * @since 1.9.0
2900
		 *
2901
		 * @param string $min_version Minimum version number required to use modules.
2902
		 * @param string $max_version Maximum version number required to use modules.
2903
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2904
		 */
2905
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2906
	}
2907
2908
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2909
		/**
2910
		 * Fires before a module is activated.
2911
		 *
2912
		 * @since 2.6.0
2913
		 *
2914
		 * @param string $module Module slug.
2915
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2916
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2917
		 */
2918
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2919
2920
		$jetpack = Jetpack::init();
2921
2922
		if ( ! strlen( $module ) )
2923
			return false;
2924
2925
		if ( ! Jetpack::is_module( $module ) )
2926
			return false;
2927
2928
		// If it's already active, then don't do it again
2929
		$active = Jetpack::get_active_modules();
2930
		foreach ( $active as $act ) {
2931
			if ( $act == $module )
2932
				return true;
2933
		}
2934
2935
		$module_data = Jetpack::get_module( $module );
2936
2937
		if ( ! Jetpack::is_active() ) {
2938
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2939
				return false;
2940
2941
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2942
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2943
				return false;
2944
		}
2945
2946
		// Check and see if the old plugin is active
2947
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2948
			// Deactivate the old plugin
2949
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2950
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2951
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2952
				Jetpack::state( 'deactivated_plugins', $module );
2953
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2954
				exit;
2955
			}
2956
		}
2957
2958
		// Protect won't work with mis-configured IPs
2959
		if ( 'protect' === $module ) {
2960
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2961
			if ( ! jetpack_protect_get_ip() ) {
2962
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2963
				return false;
2964
			}
2965
		}
2966
2967
		if ( ! Jetpack_Plan::supports( $module ) ) {
2968
			return false;
2969
		}
2970
2971
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2972
		Jetpack::state( 'module', $module );
2973
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2974
2975
		Jetpack::catch_errors( true );
2976
		ob_start();
2977
		require Jetpack::get_module_path( $module );
2978
		/** This action is documented in class.jetpack.php */
2979
		do_action( 'jetpack_activate_module', $module );
2980
		$active[] = $module;
2981
		Jetpack::update_active_modules( $active );
2982
2983
		Jetpack::state( 'error', false ); // the override
2984
		ob_end_clean();
2985
		Jetpack::catch_errors( false );
2986
2987
		if ( $redirect ) {
2988
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2989
		}
2990
		if ( $exit ) {
2991
			exit;
2992
		}
2993
		return true;
2994
	}
2995
2996
	function activate_module_actions( $module ) {
2997
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2998
	}
2999
3000
	public static function deactivate_module( $module ) {
3001
		/**
3002
		 * Fires when a module is deactivated.
3003
		 *
3004
		 * @since 1.9.0
3005
		 *
3006
		 * @param string $module Module slug.
3007
		 */
3008
		do_action( 'jetpack_pre_deactivate_module', $module );
3009
3010
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3011
3012
		$active = Jetpack::get_active_modules();
3013
		$new    = array_filter( array_diff( $active, (array) $module ) );
3014
3015
		return self::update_active_modules( $new );
3016
	}
3017
3018
	public static function enable_module_configurable( $module ) {
3019
		$module = Jetpack::get_module_slug( $module );
3020
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3021
	}
3022
3023
	/**
3024
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3025
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3026
	 *
3027
	 * @param string $module Module slug
3028
	 * @return string $url module configuration URL
3029
	 */
3030
	public static function module_configuration_url( $module ) {
3031
		$module = Jetpack::get_module_slug( $module );
3032
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3033
		/**
3034
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3035
		 *
3036
		 * @since 6.9.0
3037
		 *
3038
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3039
		 */
3040
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3041
3042
		return $url;
3043
	}
3044
3045
/* Installation */
3046
	public static function bail_on_activation( $message, $deactivate = true ) {
3047
?>
3048
<!doctype html>
3049
<html>
3050
<head>
3051
<meta charset="<?php bloginfo( 'charset' ); ?>">
3052
<style>
3053
* {
3054
	text-align: center;
3055
	margin: 0;
3056
	padding: 0;
3057
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3058
}
3059
p {
3060
	margin-top: 1em;
3061
	font-size: 18px;
3062
}
3063
</style>
3064
<body>
3065
<p><?php echo esc_html( $message ); ?></p>
3066
</body>
3067
</html>
3068
<?php
3069
		if ( $deactivate ) {
3070
			$plugins = get_option( 'active_plugins' );
3071
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3072
			$update  = false;
3073
			foreach ( $plugins as $i => $plugin ) {
3074
				if ( $plugin === $jetpack ) {
3075
					$plugins[$i] = false;
3076
					$update = true;
3077
				}
3078
			}
3079
3080
			if ( $update ) {
3081
				update_option( 'active_plugins', array_filter( $plugins ) );
3082
			}
3083
		}
3084
		exit;
3085
	}
3086
3087
	/**
3088
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3089
	 * @static
3090
	 */
3091
	public static function plugin_activation( $network_wide ) {
3092
		Jetpack_Options::update_option( 'activated', 1 );
3093
3094
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3095
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3096
		}
3097
3098
		if ( $network_wide )
3099
			Jetpack::state( 'network_nag', true );
3100
3101
		// For firing one-off events (notices) immediately after activation
3102
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3103
3104
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3105
3106
		Jetpack::plugin_initialize();
3107
	}
3108
3109
	public static function get_activation_source( $referer_url ) {
3110
3111
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3112
			return array( 'wp-cli', null );
3113
		}
3114
3115
		$referer = parse_url( $referer_url );
3116
3117
		$source_type = 'unknown';
3118
		$source_query = null;
3119
3120
		if ( ! is_array( $referer ) ) {
3121
			return array( $source_type, $source_query );
3122
		}
3123
3124
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3125
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3126
3127
		if ( isset( $referer['query'] ) ) {
3128
			parse_str( $referer['query'], $query_parts );
3129
		} else {
3130
			$query_parts = array();
3131
		}
3132
3133
		if ( $plugins_path === $referer['path'] ) {
3134
			$source_type = 'list';
3135
		} elseif ( $plugins_install_path === $referer['path'] ) {
3136
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3137
			switch( $tab ) {
3138
				case 'popular':
3139
					$source_type = 'popular';
3140
					break;
3141
				case 'recommended':
3142
					$source_type = 'recommended';
3143
					break;
3144
				case 'favorites':
3145
					$source_type = 'favorites';
3146
					break;
3147
				case 'search':
3148
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3149
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3150
					break;
3151
				default:
3152
					$source_type = 'featured';
3153
			}
3154
		}
3155
3156
		return array( $source_type, $source_query );
3157
	}
3158
3159
	/**
3160
	 * Runs before bumping version numbers up to a new version
3161
	 * @param  string $version    Version:timestamp
3162
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3163
	 * @return null              [description]
3164
	 */
3165
	public static function do_version_bump( $version, $old_version ) {
3166
		if ( ! $old_version ) { // For new sites
3167
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3168
		}
3169
	}
3170
3171
	/**
3172
	 * Sets the internal version number and activation state.
3173
	 * @static
3174
	 */
3175
	public static function plugin_initialize() {
3176
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3177
			Jetpack_Options::update_option( 'activated', 2 );
3178
		}
3179
3180 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3181
			$version = $old_version = JETPACK__VERSION . ':' . time();
3182
			/** This action is documented in class.jetpack.php */
3183
			do_action( 'updating_jetpack_version', $version, false );
3184
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3185
		}
3186
3187
		Jetpack::load_modules();
3188
3189
		Jetpack_Options::delete_option( 'do_activate' );
3190
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3191
	}
3192
3193
	/**
3194
	 * Removes all connection options
3195
	 * @static
3196
	 */
3197
	public static function plugin_deactivation( ) {
3198
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3199
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3200
			Jetpack_Network::init()->deactivate();
3201
		} else {
3202
			Jetpack::disconnect( false );
3203
			//Jetpack_Heartbeat::init()->deactivate();
3204
		}
3205
	}
3206
3207
	/**
3208
	 * Disconnects from the Jetpack servers.
3209
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3210
	 * @static
3211
	 */
3212
	public static function disconnect( $update_activated_state = true ) {
3213
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3214
		Jetpack::clean_nonces( true );
3215
3216
		// If the site is in an IDC because sync is not allowed,
3217
		// let's make sure to not disconnect the production site.
3218
		if ( ! self::validate_sync_error_idc_option() ) {
3219
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3220
			Jetpack::load_xml_rpc_client();
3221
			$xml = new Jetpack_IXR_Client();
3222
			$xml->query( 'jetpack.deregister' );
3223
		}
3224
3225
		Jetpack_Options::delete_option(
3226
			array(
3227
				'blog_token',
3228
				'user_token',
3229
				'user_tokens',
3230
				'master_user',
3231
				'time_diff',
3232
				'fallback_no_verify_ssl_certs',
3233
			)
3234
		);
3235
3236
		Jetpack_IDC::clear_all_idc_options();
3237
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3238
3239
		if ( $update_activated_state ) {
3240
			Jetpack_Options::update_option( 'activated', 4 );
3241
		}
3242
3243
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3244
			// Check then record unique disconnection if site has never been disconnected previously
3245
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3246
				$jetpack_unique_connection['disconnected'] = 1;
3247
			} else {
3248
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3249
					//track unique disconnect
3250
					$jetpack = Jetpack::init();
3251
3252
					$jetpack->stat( 'connections', 'unique-disconnect' );
3253
					$jetpack->do_stats( 'server_side' );
3254
				}
3255
				// increment number of times disconnected
3256
				$jetpack_unique_connection['disconnected'] += 1;
3257
			}
3258
3259
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3260
		}
3261
3262
		// Delete cached connected user data
3263
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3264
		delete_transient( $transient_key );
3265
3266
		// Delete all the sync related data. Since it could be taking up space.
3267
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3268
		Jetpack_Sync_Sender::get_instance()->uninstall();
3269
3270
		// Disable the Heartbeat cron
3271
		Jetpack_Heartbeat::init()->deactivate();
3272
	}
3273
3274
	/**
3275
	 * Unlinks the current user from the linked WordPress.com user
3276
	 */
3277
	public static function unlink_user( $user_id = null ) {
3278
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3279
			return false;
3280
3281
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3282
3283
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3284
			return false;
3285
3286
		if ( ! isset( $tokens[ $user_id ] ) )
3287
			return false;
3288
3289
		Jetpack::load_xml_rpc_client();
3290
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3291
		$xml->query( 'jetpack.unlink_user', $user_id );
3292
3293
		unset( $tokens[ $user_id ] );
3294
3295
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3296
3297
		/**
3298
		 * Fires after the current user has been unlinked from WordPress.com.
3299
		 *
3300
		 * @since 4.1.0
3301
		 *
3302
		 * @param int $user_id The current user's ID.
3303
		 */
3304
		do_action( 'jetpack_unlinked_user', $user_id );
3305
3306
		return true;
3307
	}
3308
3309
	/**
3310
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3311
	 */
3312
	public static function try_registration() {
3313
		// The user has agreed to the TOS at some point by now.
3314
		Jetpack_Options::update_option( 'tos_agreed', true );
3315
3316
		// Let's get some testing in beta versions and such.
3317
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3318
			// Before attempting to connect, let's make sure that the domains are viable.
3319
			$domains_to_check = array_unique( array(
3320
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3321
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3322
			) );
3323
			foreach ( $domains_to_check as $domain ) {
3324
				$result = Jetpack_Data::is_usable_domain( $domain );
3325
				if ( is_wp_error( $result ) ) {
3326
					return $result;
3327
				}
3328
			}
3329
		}
3330
3331
		$result = Jetpack::register();
3332
3333
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3334
		if ( ! $result || is_wp_error( $result ) ) {
3335
			return $result;
3336
		} else {
3337
			return true;
3338
		}
3339
	}
3340
3341
	/**
3342
	 * Tracking an internal event log. Try not to put too much chaff in here.
3343
	 *
3344
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3345
	 */
3346
	public static function log( $code, $data = null ) {
3347
		// only grab the latest 200 entries
3348
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3349
3350
		// Append our event to the log
3351
		$log_entry = array(
3352
			'time'    => time(),
3353
			'user_id' => get_current_user_id(),
3354
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3355
			'code'    => $code,
3356
		);
3357
		// Don't bother storing it unless we've got some.
3358
		if ( ! is_null( $data ) ) {
3359
			$log_entry['data'] = $data;
3360
		}
3361
		$log[] = $log_entry;
3362
3363
		// Try add_option first, to make sure it's not autoloaded.
3364
		// @todo: Add an add_option method to Jetpack_Options
3365
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3366
			Jetpack_Options::update_option( 'log', $log );
3367
		}
3368
3369
		/**
3370
		 * Fires when Jetpack logs an internal event.
3371
		 *
3372
		 * @since 3.0.0
3373
		 *
3374
		 * @param array $log_entry {
3375
		 *	Array of details about the log entry.
3376
		 *
3377
		 *	@param string time Time of the event.
3378
		 *	@param int user_id ID of the user who trigerred the event.
3379
		 *	@param int blog_id Jetpack Blog ID.
3380
		 *	@param string code Unique name for the event.
3381
		 *	@param string data Data about the event.
3382
		 * }
3383
		 */
3384
		do_action( 'jetpack_log_entry', $log_entry );
3385
	}
3386
3387
	/**
3388
	 * Get the internal event log.
3389
	 *
3390
	 * @param $event (string) - only return the specific log events
3391
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3392
	 *
3393
	 * @return array of log events || WP_Error for invalid params
3394
	 */
3395
	public static function get_log( $event = false, $num = false ) {
3396
		if ( $event && ! is_string( $event ) ) {
3397
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3398
		}
3399
3400
		if ( $num && ! is_numeric( $num ) ) {
3401
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3402
		}
3403
3404
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3405
3406
		// If nothing set - act as it did before, otherwise let's start customizing the output
3407
		if ( ! $num && ! $event ) {
3408
			return $entire_log;
3409
		} else {
3410
			$entire_log = array_reverse( $entire_log );
3411
		}
3412
3413
		$custom_log_output = array();
3414
3415
		if ( $event ) {
3416
			foreach ( $entire_log as $log_event ) {
3417
				if ( $event == $log_event[ 'code' ] ) {
3418
					$custom_log_output[] = $log_event;
3419
				}
3420
			}
3421
		} else {
3422
			$custom_log_output = $entire_log;
3423
		}
3424
3425
		if ( $num ) {
3426
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3427
		}
3428
3429
		return $custom_log_output;
3430
	}
3431
3432
	/**
3433
	 * Log modification of important settings.
3434
	 */
3435
	public static function log_settings_change( $option, $old_value, $value ) {
3436
		switch( $option ) {
3437
			case 'jetpack_sync_non_public_post_stati':
3438
				self::log( $option, $value );
3439
				break;
3440
		}
3441
	}
3442
3443
	/**
3444
	 * Return stat data for WPCOM sync
3445
	 */
3446
	public static function get_stat_data( $encode = true, $extended = true ) {
3447
		$data = Jetpack_Heartbeat::generate_stats_array();
3448
3449
		if ( $extended ) {
3450
			$additional_data = self::get_additional_stat_data();
3451
			$data = array_merge( $data, $additional_data );
3452
		}
3453
3454
		if ( $encode ) {
3455
			return json_encode( $data );
3456
		}
3457
3458
		return $data;
3459
	}
3460
3461
	/**
3462
	 * Get additional stat data to sync to WPCOM
3463
	 */
3464
	public static function get_additional_stat_data( $prefix = '' ) {
3465
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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