Completed
Push — try/xmlrpc-server-package-clas... ( 6199c0...8e0ceb )
by
unknown
07:26
created

class.jetpack.php (10 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

Loading history...
1557
	}
1558
1559
	/**
1560
	 * Make an API call to WordPress.com for plan status
1561
	 *
1562
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1563
	 *
1564
	 * @return bool True if plan is updated, false if no update
1565
	 */
1566
	public static function refresh_active_plan_from_wpcom() {
1567
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1568
		return Jetpack_Plan::refresh_from_wpcom();
1569
	}
1570
1571
	/**
1572
	 * Get the plan that this Jetpack site is currently using
1573
	 *
1574
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1575
	 * @return array Active Jetpack plan details.
1576
	 */
1577
	public static function get_active_plan() {
1578
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1579
		return Jetpack_Plan::get();
1580
	}
1581
1582
	/**
1583
	 * Determine whether the active plan supports a particular feature
1584
	 *
1585
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1586
	 * @return bool True if plan supports feature, false if not.
1587
	 */
1588
	public static function active_plan_supports( $feature ) {
1589
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1590
		return Jetpack_Plan::supports( $feature );
1591
	}
1592
1593
	/**
1594
	 * Is Jetpack in development (offline) mode?
1595
	 */
1596
	public static function is_development_mode() {
1597
		$development_mode = false;
1598
1599
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1600
			$development_mode = JETPACK_DEV_DEBUG;
1601
		} elseif ( $site_url = site_url() ) {
1602
			$development_mode = false === strpos( $site_url, '.' );
1603
		}
1604
1605
		/**
1606
		 * Filters Jetpack's development mode.
1607
		 *
1608
		 * @see https://jetpack.com/support/development-mode/
1609
		 *
1610
		 * @since 2.2.1
1611
		 *
1612
		 * @param bool $development_mode Is Jetpack's development mode active.
1613
		 */
1614
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1615
		return $development_mode;
1616
	}
1617
1618
	/**
1619
	 * Whether the site is currently onboarding or not.
1620
	 * A site is considered as being onboarded if it currently has an onboarding token.
1621
	 *
1622
	 * @since 5.8
1623
	 *
1624
	 * @access public
1625
	 * @static
1626
	 *
1627
	 * @return bool True if the site is currently onboarding, false otherwise
1628
	 */
1629
	public static function is_onboarding() {
1630
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1631
	}
1632
1633
	/**
1634
	 * Determines reason for Jetpack development mode.
1635
	 */
1636
	public static function development_mode_trigger_text() {
1637
		if ( ! Jetpack::is_development_mode() ) {
1638
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1639
		}
1640
1641
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1642
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1643
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1644
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1645
		} else {
1646
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1647
		}
1648
1649
		return $notice;
1650
1651
	}
1652
	/**
1653
	* Get Jetpack development mode notice text and notice class.
1654
	*
1655
	* Mirrors the checks made in Jetpack::is_development_mode
1656
	*
1657
	*/
1658
	public static function show_development_mode_notice() {
1659 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1660
			$notice = sprintf(
1661
			/* translators: %s is a URL */
1662
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1663
				'https://jetpack.com/support/development-mode/'
1664
			);
1665
1666
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1667
1668
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1669
		}
1670
1671
		// Throw up a notice if using a development version and as for feedback.
1672
		if ( Jetpack::is_development_version() ) {
1673
			/* translators: %s is a URL */
1674
			$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/' );
1675
1676
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1677
		}
1678
		// Throw up a notice if using staging mode
1679
		if ( Jetpack::is_staging_site() ) {
1680
			/* translators: %s is a URL */
1681
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1682
1683
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1684
		}
1685
	}
1686
1687
	/**
1688
	 * Whether Jetpack's version maps to a public release, or a development version.
1689
	 */
1690
	public static function is_development_version() {
1691
		/**
1692
		 * Allows filtering whether this is a development version of Jetpack.
1693
		 *
1694
		 * This filter is especially useful for tests.
1695
		 *
1696
		 * @since 4.3.0
1697
		 *
1698
		 * @param bool $development_version Is this a develoment version of Jetpack?
1699
		 */
1700
		return (bool) apply_filters(
1701
			'jetpack_development_version',
1702
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1703
		);
1704
	}
1705
1706
	/**
1707
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1708
	 */
1709
	public static function is_user_connected( $user_id = false ) {
1710
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1711
		if ( ! $user_id ) {
1712
			return false;
1713
		}
1714
1715
		return (bool) Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1716
	}
1717
1718
	/**
1719
	 * Get the wpcom user data of the current|specified connected user.
1720
	 */
1721
	public static function get_connected_user_data( $user_id = null ) {
1722
		if ( ! $user_id ) {
1723
			$user_id = get_current_user_id();
1724
		}
1725
1726
		$transient_key = "jetpack_connected_user_data_$user_id";
1727
1728
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1729
			return $cached_user_data;
1730
		}
1731
1732
		Jetpack::load_xml_rpc_client();
1733
		$xml = new Jetpack_IXR_Client( array(
1734
			'user_id' => $user_id,
1735
		) );
1736
		$xml->query( 'wpcom.getUser' );
1737
		if ( ! $xml->isError() ) {
1738
			$user_data = $xml->getResponse();
1739
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1740
			return $user_data;
1741
		}
1742
1743
		return false;
1744
	}
1745
1746
	/**
1747
	 * Get the wpcom email of the current|specified connected user.
1748
	 */
1749 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1750
		if ( ! $user_id ) {
1751
			$user_id = get_current_user_id();
1752
		}
1753
		Jetpack::load_xml_rpc_client();
1754
		$xml = new Jetpack_IXR_Client( array(
1755
			'user_id' => $user_id,
1756
		) );
1757
		$xml->query( 'wpcom.getUserEmail' );
1758
		if ( ! $xml->isError() ) {
1759
			return $xml->getResponse();
1760
		}
1761
		return false;
1762
	}
1763
1764
	/**
1765
	 * Get the wpcom email of the master user.
1766
	 */
1767
	public static function get_master_user_email() {
1768
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1769
		if ( $master_user_id ) {
1770
			return self::get_connected_user_email( $master_user_id );
1771
		}
1772
		return '';
1773
	}
1774
1775
	function current_user_is_connection_owner() {
1776
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
1777
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1778
	}
1779
1780
	/**
1781
	 * Gets current user IP address.
1782
	 *
1783
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1784
	 *
1785
	 * @return string                  Current user IP address.
1786
	 */
1787
	public static function current_user_ip( $check_all_headers = false ) {
1788
		if ( $check_all_headers ) {
1789
			foreach ( array(
1790
				'HTTP_CF_CONNECTING_IP',
1791
				'HTTP_CLIENT_IP',
1792
				'HTTP_X_FORWARDED_FOR',
1793
				'HTTP_X_FORWARDED',
1794
				'HTTP_X_CLUSTER_CLIENT_IP',
1795
				'HTTP_FORWARDED_FOR',
1796
				'HTTP_FORWARDED',
1797
				'HTTP_VIA',
1798
			) as $key ) {
1799
				if ( ! empty( $_SERVER[ $key ] ) ) {
1800
					return $_SERVER[ $key ];
1801
				}
1802
			}
1803
		}
1804
1805
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1806
	}
1807
1808
	/**
1809
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1810
	 */
1811
	function extra_oembed_providers() {
1812
		// Cloudup: https://dev.cloudup.com/#oembed
1813
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1814
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1815
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1816
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1817
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1818
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1819
	}
1820
1821
	/**
1822
	 * Synchronize connected user role changes
1823
	 */
1824
	function user_role_change( $user_id ) {
1825
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1826
		Jetpack_Sync_Users::user_role_change( $user_id );
1827
	}
1828
1829
	/**
1830
	 * Loads the currently active modules.
1831
	 */
1832
	public static function load_modules() {
1833
		if (
1834
			! self::is_active()
1835
			&& ! self::is_development_mode()
1836
			&& ! self::is_onboarding()
1837
			&& (
1838
				! is_multisite()
1839
				|| ! get_site_option( 'jetpack_protect_active' )
1840
			)
1841
		) {
1842
			return;
1843
		}
1844
1845
		$version = Jetpack_Options::get_option( 'version' );
1846 View Code Duplication
		if ( ! $version ) {
1847
			$version = $old_version = JETPACK__VERSION . ':' . time();
1848
			/** This action is documented in class.jetpack.php */
1849
			do_action( 'updating_jetpack_version', $version, false );
1850
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1851
		}
1852
		list( $version ) = explode( ':', $version );
1853
1854
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1855
1856
		$modules_data = array();
1857
1858
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1859
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1860
			$updated_modules = array();
1861
			foreach ( $modules as $module ) {
1862
				$modules_data[ $module ] = Jetpack::get_module( $module );
1863
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1864
					continue;
1865
				}
1866
1867
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1868
					continue;
1869
				}
1870
1871
				$updated_modules[] = $module;
1872
			}
1873
1874
			$modules = array_diff( $modules, $updated_modules );
1875
		}
1876
1877
		$is_development_mode = Jetpack::is_development_mode();
1878
1879
		foreach ( $modules as $index => $module ) {
1880
			// If we're in dev mode, disable modules requiring a connection
1881
			if ( $is_development_mode ) {
1882
				// Prime the pump if we need to
1883
				if ( empty( $modules_data[ $module ] ) ) {
1884
					$modules_data[ $module ] = Jetpack::get_module( $module );
1885
				}
1886
				// If the module requires a connection, but we're in local mode, don't include it.
1887
				if ( $modules_data[ $module ]['requires_connection'] ) {
1888
					continue;
1889
				}
1890
			}
1891
1892
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1893
				continue;
1894
			}
1895
1896
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1897
				unset( $modules[ $index ] );
1898
				self::update_active_modules( array_values( $modules ) );
1899
				continue;
1900
			}
1901
1902
			/**
1903
			 * Fires when a specific module is loaded.
1904
			 * The dynamic part of the hook, $module, is the module slug.
1905
			 *
1906
			 * @since 1.1.0
1907
			 */
1908
			do_action( 'jetpack_module_loaded_' . $module );
1909
		}
1910
1911
		/**
1912
		 * Fires when all the modules are loaded.
1913
		 *
1914
		 * @since 1.1.0
1915
		 */
1916
		do_action( 'jetpack_modules_loaded' );
1917
1918
		// 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.
1919
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1920
	}
1921
1922
	/**
1923
	 * Check if Jetpack's REST API compat file should be included
1924
	 * @action plugins_loaded
1925
	 * @return null
1926
	 */
1927
	public function check_rest_api_compat() {
1928
		/**
1929
		 * Filters the list of REST API compat files to be included.
1930
		 *
1931
		 * @since 2.2.5
1932
		 *
1933
		 * @param array $args Array of REST API compat files to include.
1934
		 */
1935
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1936
1937
		if ( function_exists( 'bbpress' ) )
1938
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1939
1940
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1941
			require_once $_jetpack_rest_api_compat_include;
1942
	}
1943
1944
	/**
1945
	 * Gets all plugins currently active in values, regardless of whether they're
1946
	 * traditionally activated or network activated.
1947
	 *
1948
	 * @todo Store the result in core's object cache maybe?
1949
	 */
1950
	public static function get_active_plugins() {
1951
		$active_plugins = (array) get_option( 'active_plugins', array() );
1952
1953
		if ( is_multisite() ) {
1954
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1955
			// whereas active_plugins stores them in the values.
1956
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1957
			if ( $network_plugins ) {
1958
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1959
			}
1960
		}
1961
1962
		sort( $active_plugins );
1963
1964
		return array_unique( $active_plugins );
1965
	}
1966
1967
	/**
1968
	 * Gets and parses additional plugin data to send with the heartbeat data
1969
	 *
1970
	 * @since 3.8.1
1971
	 *
1972
	 * @return array Array of plugin data
1973
	 */
1974
	public static function get_parsed_plugin_data() {
1975
		if ( ! function_exists( 'get_plugins' ) ) {
1976
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1977
		}
1978
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1979
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1980
		$active_plugins = Jetpack::get_active_plugins();
1981
1982
		$plugins = array();
1983
		foreach ( $all_plugins as $path => $plugin_data ) {
1984
			$plugins[ $path ] = array(
1985
					'is_active' => in_array( $path, $active_plugins ),
1986
					'file'      => $path,
1987
					'name'      => $plugin_data['Name'],
1988
					'version'   => $plugin_data['Version'],
1989
					'author'    => $plugin_data['Author'],
1990
			);
1991
		}
1992
1993
		return $plugins;
1994
	}
1995
1996
	/**
1997
	 * Gets and parses theme data to send with the heartbeat data
1998
	 *
1999
	 * @since 3.8.1
2000
	 *
2001
	 * @return array Array of theme data
2002
	 */
2003
	public static function get_parsed_theme_data() {
2004
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2005
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2006
2007
		$themes = array();
2008
		foreach ( $all_themes as $slug => $theme_data ) {
2009
			$theme_headers = array();
2010
			foreach ( $header_keys as $header_key ) {
2011
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2012
			}
2013
2014
			$themes[ $slug ] = array(
2015
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2016
					'slug' => $slug,
2017
					'theme_root' => $theme_data->get_theme_root_uri(),
2018
					'parent' => $theme_data->parent(),
2019
					'headers' => $theme_headers
2020
			);
2021
		}
2022
2023
		return $themes;
2024
	}
2025
2026
	/**
2027
	 * Checks whether a specific plugin is active.
2028
	 *
2029
	 * We don't want to store these in a static variable, in case
2030
	 * there are switch_to_blog() calls involved.
2031
	 */
2032
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2033
		return in_array( $plugin, self::get_active_plugins() );
2034
	}
2035
2036
	/**
2037
	 * Check if Jetpack's Open Graph tags should be used.
2038
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2039
	 *
2040
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2041
	 * @action plugins_loaded
2042
	 * @return null
2043
	 */
2044
	public function check_open_graph() {
2045
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2046
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2047
		}
2048
2049
		$active_plugins = self::get_active_plugins();
2050
2051
		if ( ! empty( $active_plugins ) ) {
2052
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2053
				if ( in_array( $plugin, $active_plugins ) ) {
2054
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2055
					break;
2056
				}
2057
			}
2058
		}
2059
2060
		/**
2061
		 * Allow the addition of Open Graph Meta Tags to all pages.
2062
		 *
2063
		 * @since 2.0.3
2064
		 *
2065
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2066
		 */
2067
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2068
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2069
		}
2070
	}
2071
2072
	/**
2073
	 * Check if Jetpack's Twitter tags should be used.
2074
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2075
	 *
2076
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2077
	 * @action plugins_loaded
2078
	 * @return null
2079
	 */
2080
	public function check_twitter_tags() {
2081
2082
		$active_plugins = self::get_active_plugins();
2083
2084
		if ( ! empty( $active_plugins ) ) {
2085
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2086
				if ( in_array( $plugin, $active_plugins ) ) {
2087
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2088
					break;
2089
				}
2090
			}
2091
		}
2092
2093
		/**
2094
		 * Allow Twitter Card Meta tags to be disabled.
2095
		 *
2096
		 * @since 2.6.0
2097
		 *
2098
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2099
		 */
2100
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2101
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2102
		}
2103
	}
2104
2105
	/**
2106
	 * Allows plugins to submit security reports.
2107
 	 *
2108
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2109
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2110
	 * @param array   $args         See definitions above
2111
	 */
2112
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2113
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2114
	}
2115
2116
/* Jetpack Options API */
2117
2118
	public static function get_option_names( $type = 'compact' ) {
2119
		return Jetpack_Options::get_option_names( $type );
2120
	}
2121
2122
	/**
2123
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2124
 	 *
2125
	 * @param string $name    Option name
2126
	 * @param mixed  $default (optional)
2127
	 */
2128
	public static function get_option( $name, $default = false ) {
2129
		return Jetpack_Options::get_option( $name, $default );
2130
	}
2131
2132
	/**
2133
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2134
 	 *
2135
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2136
	 * @param string $name  Option name
2137
	 * @param mixed  $value Option value
2138
	 */
2139
	public static function update_option( $name, $value ) {
2140
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2141
		return Jetpack_Options::update_option( $name, $value );
2142
	}
2143
2144
	/**
2145
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2146
 	 *
2147
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2148
	 * @param array $array array( option name => option value, ... )
2149
	 */
2150
	public static function update_options( $array ) {
2151
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2152
		return Jetpack_Options::update_options( $array );
2153
	}
2154
2155
	/**
2156
	 * Deletes the given option.  May be passed multiple option names as an array.
2157
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2158
	 *
2159
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2160
	 * @param string|array $names
2161
	 */
2162
	public static function delete_option( $names ) {
2163
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2164
		return Jetpack_Options::delete_option( $names );
2165
	}
2166
2167
	/**
2168
	 * Enters a user token into the user_tokens option
2169
	 *
2170
	 * @param int $user_id
2171
	 * @param string $token
2172
	 * return bool
2173
	 */
2174
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2175
		// not designed for concurrent updates
2176
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2177
		if ( ! is_array( $user_tokens ) )
2178
			$user_tokens = array();
2179
		$user_tokens[$user_id] = $token;
2180
		if ( $is_master_user ) {
2181
			$master_user = $user_id;
2182
			$options     = compact( 'user_tokens', 'master_user' );
2183
		} else {
2184
			$options = compact( 'user_tokens' );
2185
		}
2186
		return Jetpack_Options::update_options( $options );
2187
	}
2188
2189
	/**
2190
	 * Returns an array of all PHP files in the specified absolute path.
2191
	 * Equivalent to glob( "$absolute_path/*.php" ).
2192
	 *
2193
	 * @param string $absolute_path The absolute path of the directory to search.
2194
	 * @return array Array of absolute paths to the PHP files.
2195
	 */
2196
	public static function glob_php( $absolute_path ) {
2197
		if ( function_exists( 'glob' ) ) {
2198
			return glob( "$absolute_path/*.php" );
2199
		}
2200
2201
		$absolute_path = untrailingslashit( $absolute_path );
2202
		$files = array();
2203
		if ( ! $dir = @opendir( $absolute_path ) ) {
2204
			return $files;
2205
		}
2206
2207
		while ( false !== $file = readdir( $dir ) ) {
2208
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2209
				continue;
2210
			}
2211
2212
			$file = "$absolute_path/$file";
2213
2214
			if ( ! is_file( $file ) ) {
2215
				continue;
2216
			}
2217
2218
			$files[] = $file;
2219
		}
2220
2221
		closedir( $dir );
2222
2223
		return $files;
2224
	}
2225
2226
	public static function activate_new_modules( $redirect = false ) {
2227
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2228
			return;
2229
		}
2230
2231
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2232 View Code Duplication
		if ( ! $jetpack_old_version ) {
2233
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2234
			/** This action is documented in class.jetpack.php */
2235
			do_action( 'updating_jetpack_version', $version, false );
2236
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2237
		}
2238
2239
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2240
2241
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2242
			return;
2243
		}
2244
2245
		$active_modules     = Jetpack::get_active_modules();
2246
		$reactivate_modules = array();
2247
		foreach ( $active_modules as $active_module ) {
2248
			$module = Jetpack::get_module( $active_module );
2249
			if ( ! isset( $module['changed'] ) ) {
2250
				continue;
2251
			}
2252
2253
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2254
				continue;
2255
			}
2256
2257
			$reactivate_modules[] = $active_module;
2258
			Jetpack::deactivate_module( $active_module );
2259
		}
2260
2261
		$new_version = JETPACK__VERSION . ':' . time();
2262
		/** This action is documented in class.jetpack.php */
2263
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2264
		Jetpack_Options::update_options(
2265
			array(
2266
				'version'     => $new_version,
2267
				'old_version' => $jetpack_old_version,
2268
			)
2269
		);
2270
2271
		Jetpack::state( 'message', 'modules_activated' );
2272
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2273
2274
		if ( $redirect ) {
2275
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2276
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2277
				$page = $_GET['page'];
2278
			}
2279
2280
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2281
			exit;
2282
		}
2283
	}
2284
2285
	/**
2286
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2287
	 * Make sure to tuck away module "library" files in a sub-directory.
2288
	 */
2289
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2290
		static $modules = null;
2291
2292
		if ( ! isset( $modules ) ) {
2293
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2294
			// Use the cache if we're on the front-end and it's available...
2295
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2296
				$modules = $available_modules_option[ JETPACK__VERSION ];
2297
			} else {
2298
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2299
2300
				$modules = array();
2301
2302
				foreach ( $files as $file ) {
2303
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2304
						continue;
2305
					}
2306
2307
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2308
				}
2309
2310
				Jetpack_Options::update_option( 'available_modules', array(
2311
					JETPACK__VERSION => $modules,
2312
				) );
2313
			}
2314
		}
2315
2316
		/**
2317
		 * Filters the array of modules available to be activated.
2318
		 *
2319
		 * @since 2.4.0
2320
		 *
2321
		 * @param array $modules Array of available modules.
2322
		 * @param string $min_version Minimum version number required to use modules.
2323
		 * @param string $max_version Maximum version number required to use modules.
2324
		 */
2325
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2326
2327
		if ( ! $min_version && ! $max_version ) {
2328
			return array_keys( $mods );
2329
		}
2330
2331
		$r = array();
2332
		foreach ( $mods as $slug => $introduced ) {
2333
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2334
				continue;
2335
			}
2336
2337
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2338
				continue;
2339
			}
2340
2341
			$r[] = $slug;
2342
		}
2343
2344
		return $r;
2345
	}
2346
2347
	/**
2348
	 * Default modules loaded on activation.
2349
	 */
2350
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2351
		$return = array();
2352
2353
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2354
			$module_data = Jetpack::get_module( $module );
2355
2356
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2357
				case 'yes' :
2358
					$return[] = $module;
2359
					break;
2360
				case 'public' :
2361
					if ( Jetpack_Options::get_option( 'public' ) ) {
2362
						$return[] = $module;
2363
					}
2364
					break;
2365
				case 'no' :
2366
				default :
2367
					break;
2368
			}
2369
		}
2370
		/**
2371
		 * Filters the array of default modules.
2372
		 *
2373
		 * @since 2.5.0
2374
		 *
2375
		 * @param array $return Array of default modules.
2376
		 * @param string $min_version Minimum version number required to use modules.
2377
		 * @param string $max_version Maximum version number required to use modules.
2378
		 */
2379
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2380
	}
2381
2382
	/**
2383
	 * Checks activated modules during auto-activation to determine
2384
	 * if any of those modules are being deprecated.  If so, close
2385
	 * them out, and add any replacement modules.
2386
	 *
2387
	 * Runs at priority 99 by default.
2388
	 *
2389
	 * This is run late, so that it can still activate a module if
2390
	 * the new module is a replacement for another that the user
2391
	 * currently has active, even if something at the normal priority
2392
	 * would kibosh everything.
2393
	 *
2394
	 * @since 2.6
2395
	 * @uses jetpack_get_default_modules filter
2396
	 * @param array $modules
2397
	 * @return array
2398
	 */
2399
	function handle_deprecated_modules( $modules ) {
2400
		$deprecated_modules = array(
2401
			'debug'            => null,  // Closed out and moved to the debugger library.
2402
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2403
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2404
		);
2405
2406
		// Don't activate SSO if they never completed activating WPCC.
2407
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2408
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2409
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2410
				$deprecated_modules['wpcc'] = null;
2411
			}
2412
		}
2413
2414
		foreach ( $deprecated_modules as $module => $replacement ) {
2415
			if ( Jetpack::is_module_active( $module ) ) {
2416
				self::deactivate_module( $module );
2417
				if ( $replacement ) {
2418
					$modules[] = $replacement;
2419
				}
2420
			}
2421
		}
2422
2423
		return array_unique( $modules );
2424
	}
2425
2426
	/**
2427
	 * Checks activated plugins during auto-activation to determine
2428
	 * if any of those plugins are in the list with a corresponding module
2429
	 * that is not compatible with the plugin. The module will not be allowed
2430
	 * to auto-activate.
2431
	 *
2432
	 * @since 2.6
2433
	 * @uses jetpack_get_default_modules filter
2434
	 * @param array $modules
2435
	 * @return array
2436
	 */
2437
	function filter_default_modules( $modules ) {
2438
2439
		$active_plugins = self::get_active_plugins();
2440
2441
		if ( ! empty( $active_plugins ) ) {
2442
2443
			// For each module we'd like to auto-activate...
2444
			foreach ( $modules as $key => $module ) {
2445
				// If there are potential conflicts for it...
2446
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2447
					// For each potential conflict...
2448
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2449
						// If that conflicting plugin is active...
2450
						if ( in_array( $plugin, $active_plugins ) ) {
2451
							// Remove that item from being auto-activated.
2452
							unset( $modules[ $key ] );
2453
						}
2454
					}
2455
				}
2456
			}
2457
		}
2458
2459
		return $modules;
2460
	}
2461
2462
	/**
2463
	 * Extract a module's slug from its full path.
2464
	 */
2465
	public static function get_module_slug( $file ) {
2466
		return str_replace( '.php', '', basename( $file ) );
2467
	}
2468
2469
	/**
2470
	 * Generate a module's path from its slug.
2471
	 */
2472
	public static function get_module_path( $slug ) {
2473
		/**
2474
		 * Filters the path of a modules.
2475
		 *
2476
		 * @since 7.4.0
2477
		 *
2478
		 * @param array $return The absolute path to a module's root php file
2479
		 * @param string $slug The module slug
2480
		 */
2481
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2482
	}
2483
2484
	/**
2485
	 * Load module data from module file. Headers differ from WordPress
2486
	 * plugin headers to avoid them being identified as standalone
2487
	 * plugins on the WordPress plugins page.
2488
	 */
2489
	public static function get_module( $module ) {
2490
		$headers = array(
2491
			'name'                      => 'Module Name',
2492
			'description'               => 'Module Description',
2493
			'jumpstart_desc'            => 'Jumpstart Description',
2494
			'sort'                      => 'Sort Order',
2495
			'recommendation_order'      => 'Recommendation Order',
2496
			'introduced'                => 'First Introduced',
2497
			'changed'                   => 'Major Changes In',
2498
			'deactivate'                => 'Deactivate',
2499
			'free'                      => 'Free',
2500
			'requires_connection'       => 'Requires Connection',
2501
			'auto_activate'             => 'Auto Activate',
2502
			'module_tags'               => 'Module Tags',
2503
			'feature'                   => 'Feature',
2504
			'additional_search_queries' => 'Additional Search Queries',
2505
			'plan_classes'              => 'Plans',
2506
		);
2507
2508
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2509
2510
		$mod = Jetpack::get_file_data( $file, $headers );
2511
		if ( empty( $mod['name'] ) ) {
2512
			return false;
2513
		}
2514
2515
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2516
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2517
		$mod['deactivate']              = empty( $mod['deactivate'] );
2518
		$mod['free']                    = empty( $mod['free'] );
2519
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2520
2521
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2522
			$mod['auto_activate'] = 'No';
2523
		} else {
2524
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2525
		}
2526
2527
		if ( $mod['module_tags'] ) {
2528
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2529
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2530
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2531
		} else {
2532
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2533
		}
2534
2535 View Code Duplication
		if ( $mod['plan_classes'] ) {
2536
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2537
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2538
		} else {
2539
			$mod['plan_classes'] = array( 'free' );
2540
		}
2541
2542 View Code Duplication
		if ( $mod['feature'] ) {
2543
			$mod['feature'] = explode( ',', $mod['feature'] );
2544
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2545
		} else {
2546
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2547
		}
2548
2549
		/**
2550
		 * Filters the feature array on a module.
2551
		 *
2552
		 * This filter allows you to control where each module is filtered: Recommended,
2553
		 * Jumpstart, and the default "Other" listing.
2554
		 *
2555
		 * @since 3.5.0
2556
		 *
2557
		 * @param array   $mod['feature'] The areas to feature this module:
2558
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2559
		 *     'Recommended' shows on the main Jetpack admin screen.
2560
		 *     'Other' should be the default if no other value is in the array.
2561
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2562
		 * @param array   $mod All the currently assembled module data.
2563
		 */
2564
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2565
2566
		/**
2567
		 * Filter the returned data about a module.
2568
		 *
2569
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2570
		 * so please be careful.
2571
		 *
2572
		 * @since 3.6.0
2573
		 *
2574
		 * @param array   $mod    The details of the requested module.
2575
		 * @param string  $module The slug of the module, e.g. sharedaddy
2576
		 * @param string  $file   The path to the module source file.
2577
		 */
2578
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2579
	}
2580
2581
	/**
2582
	 * Like core's get_file_data implementation, but caches the result.
2583
	 */
2584
	public static function get_file_data( $file, $headers ) {
2585
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2586
		$file_name = basename( $file );
2587
2588
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2589
2590
		$file_data_option = get_transient( $cache_key );
2591
2592
		if ( false === $file_data_option ) {
2593
			$file_data_option = array();
2594
		}
2595
2596
		$key           = md5( $file_name . serialize( $headers ) );
2597
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2598
2599
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2600
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2601
			return $file_data_option[ $key ];
2602
		}
2603
2604
		$data = get_file_data( $file, $headers );
2605
2606
		$file_data_option[ $key ] = $data;
2607
2608
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2609
2610
		return $data;
2611
	}
2612
2613
2614
	/**
2615
	 * Return translated module tag.
2616
	 *
2617
	 * @param string $tag Tag as it appears in each module heading.
2618
	 *
2619
	 * @return mixed
2620
	 */
2621
	public static function translate_module_tag( $tag ) {
2622
		return jetpack_get_module_i18n_tag( $tag );
2623
	}
2624
2625
	/**
2626
	 * Get i18n strings as a JSON-encoded string
2627
	 *
2628
	 * @return string The locale as JSON
2629
	 */
2630
	public static function get_i18n_data_json() {
2631
2632
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2633
		// JSON files with the file they should be included for. This is an md5
2634
		// of '_inc/build/admin.js'.
2635
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2636
2637
		$i18n_json =
2638
				   JETPACK__PLUGIN_DIR
2639
				   . 'languages/json/jetpack-'
2640
				   . get_user_locale()
2641
				   . '-'
2642
				   . $path_md5
2643
				   . '.json';
2644
2645
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2646
			$locale_data = @file_get_contents( $i18n_json );
2647
			if ( $locale_data ) {
2648
				return $locale_data;
2649
			}
2650
		}
2651
2652
		// Return valid empty Jed locale
2653
		return '{ "locale_data": { "messages": { "": {} } } }';
2654
	}
2655
2656
	/**
2657
	 * Add locale data setup to wp-i18n
2658
	 *
2659
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2660
	 *
2661
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2662
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2663
	 *
2664
	 * This method provides a safe way to request the setup multiple times but add the script at
2665
	 * most once.
2666
	 *
2667
	 * @since 6.7.0
2668
	 *
2669
	 * @return void
2670
	 */
2671
	public static function setup_wp_i18n_locale_data() {
2672
		static $script_added = false;
2673
		if ( ! $script_added ) {
2674
			$script_added = true;
2675
			wp_add_inline_script(
2676
				'wp-i18n',
2677
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2678
			);
2679
		}
2680
	}
2681
2682
	/**
2683
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2684
	 *
2685
	 * @since 3.9.2
2686
	 *
2687
	 * @param array $modules
2688
	 *
2689
	 * @return string|void
2690
	 */
2691
	public static function get_translated_modules( $modules ) {
2692
		foreach ( $modules as $index => $module ) {
2693
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2694
			if ( isset( $module['name'] ) ) {
2695
				$modules[ $index ]['name'] = $i18n_module['name'];
2696
			}
2697
			if ( isset( $module['description'] ) ) {
2698
				$modules[ $index ]['description'] = $i18n_module['description'];
2699
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2700
			}
2701
		}
2702
		return $modules;
2703
	}
2704
2705
	/**
2706
	 * Get a list of activated modules as an array of module slugs.
2707
	 */
2708
	public static function get_active_modules() {
2709
		$active = Jetpack_Options::get_option( 'active_modules' );
2710
2711
		if ( ! is_array( $active ) ) {
2712
			$active = array();
2713
		}
2714
2715
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2716
			$active[] = 'vaultpress';
2717
		} else {
2718
			$active = array_diff( $active, array( 'vaultpress' ) );
2719
		}
2720
2721
		//If protect is active on the main site of a multisite, it should be active on all sites.
2722
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2723
			$active[] = 'protect';
2724
		}
2725
2726
		/**
2727
		 * Allow filtering of the active modules.
2728
		 *
2729
		 * Gives theme and plugin developers the power to alter the modules that
2730
		 * are activated on the fly.
2731
		 *
2732
		 * @since 5.8.0
2733
		 *
2734
		 * @param array $active Array of active module slugs.
2735
		 */
2736
		$active = apply_filters( 'jetpack_active_modules', $active );
2737
2738
		return array_unique( $active );
2739
	}
2740
2741
	/**
2742
	 * Check whether or not a Jetpack module is active.
2743
	 *
2744
	 * @param string $module The slug of a Jetpack module.
2745
	 * @return bool
2746
	 *
2747
	 * @static
2748
	 */
2749
	public static function is_module_active( $module ) {
2750
		return in_array( $module, self::get_active_modules() );
2751
	}
2752
2753
	public static function is_module( $module ) {
2754
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2755
	}
2756
2757
	/**
2758
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2759
	 *
2760
	 * @param bool $catch True to start catching, False to stop.
2761
	 *
2762
	 * @static
2763
	 */
2764
	public static function catch_errors( $catch ) {
2765
		static $display_errors, $error_reporting;
2766
2767
		if ( $catch ) {
2768
			$display_errors  = @ini_set( 'display_errors', 1 );
2769
			$error_reporting = @error_reporting( E_ALL );
2770
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2771
		} else {
2772
			@ini_set( 'display_errors', $display_errors );
2773
			@error_reporting( $error_reporting );
2774
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2775
		}
2776
	}
2777
2778
	/**
2779
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2780
	 */
2781
	public static function catch_errors_on_shutdown() {
2782
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2783
	}
2784
2785
	/**
2786
	 * Rewrite any string to make paths easier to read.
2787
	 *
2788
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2789
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2790
	 *
2791
	 * @param $string
2792
	 * @return mixed
2793
	 */
2794
	public static function alias_directories( $string ) {
2795
		// ABSPATH has a trailing slash.
2796
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2797
		// WP_CONTENT_DIR does not have a trailing slash.
2798
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2799
2800
		return $string;
2801
	}
2802
2803
	public static function activate_default_modules(
2804
		$min_version = false,
2805
		$max_version = false,
2806
		$other_modules = array(),
2807
		$redirect = true,
2808
		$send_state_messages = true
2809
	) {
2810
		$jetpack = Jetpack::init();
2811
2812
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2813
		$modules = array_merge( $other_modules, $modules );
2814
2815
		// Look for standalone plugins and disable if active.
2816
2817
		$to_deactivate = array();
2818
		foreach ( $modules as $module ) {
2819
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2820
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2821
			}
2822
		}
2823
2824
		$deactivated = array();
2825
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2826
			list( $probable_file, $probable_title ) = $deactivate_me;
2827
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2828
				$deactivated[] = $module;
2829
			}
2830
		}
2831
2832
		if ( $deactivated && $redirect ) {
2833
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2834
2835
			$url = add_query_arg(
2836
				array(
2837
					'action'   => 'activate_default_modules',
2838
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2839
				),
2840
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2841
			);
2842
			wp_safe_redirect( $url );
2843
			exit;
2844
		}
2845
2846
		/**
2847
		 * Fires before default modules are activated.
2848
		 *
2849
		 * @since 1.9.0
2850
		 *
2851
		 * @param string $min_version Minimum version number required to use modules.
2852
		 * @param string $max_version Maximum version number required to use modules.
2853
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2854
		 */
2855
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2856
2857
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2858
		if ( $send_state_messages ) {
2859
			Jetpack::restate();
2860
			Jetpack::catch_errors( true );
2861
		}
2862
2863
		$active = Jetpack::get_active_modules();
2864
2865
		foreach ( $modules as $module ) {
2866
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2867
				$active[] = $module;
2868
				self::update_active_modules( $active );
2869
				continue;
2870
			}
2871
2872
			if ( $send_state_messages && in_array( $module, $active ) ) {
2873
				$module_info = Jetpack::get_module( $module );
2874 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
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
				continue;
2885
			}
2886
2887
			$file = Jetpack::get_module_path( $module );
2888
			if ( ! file_exists( $file ) ) {
2889
				continue;
2890
			}
2891
2892
			// we'll override this later if the plugin can be included without fatal error
2893
			if ( $redirect ) {
2894
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2895
			}
2896
2897
			if ( $send_state_messages ) {
2898
				Jetpack::state( 'error', 'module_activation_failed' );
2899
				Jetpack::state( 'module', $module );
2900
			}
2901
2902
			ob_start();
2903
			require_once $file;
2904
2905
			$active[] = $module;
2906
2907 View Code Duplication
			if ( $send_state_messages ) {
2908
2909
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2910
				if ( $active_state = Jetpack::state( $state ) ) {
2911
					$active_state = explode( ',', $active_state );
2912
				} else {
2913
					$active_state = array();
2914
				}
2915
				$active_state[] = $module;
2916
				Jetpack::state( $state, implode( ',', $active_state ) );
2917
			}
2918
2919
			Jetpack::update_active_modules( $active );
2920
2921
			ob_end_clean();
2922
		}
2923
2924
		if ( $send_state_messages ) {
2925
			Jetpack::state( 'error', false );
2926
			Jetpack::state( 'module', false );
2927
		}
2928
2929
		Jetpack::catch_errors( false );
2930
		/**
2931
		 * Fires when default modules are activated.
2932
		 *
2933
		 * @since 1.9.0
2934
		 *
2935
		 * @param string $min_version Minimum version number required to use modules.
2936
		 * @param string $max_version Maximum version number required to use modules.
2937
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2938
		 */
2939
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2940
	}
2941
2942
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2943
		/**
2944
		 * Fires before a module is activated.
2945
		 *
2946
		 * @since 2.6.0
2947
		 *
2948
		 * @param string $module Module slug.
2949
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2950
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2951
		 */
2952
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2953
2954
		$jetpack = Jetpack::init();
2955
2956
		if ( ! strlen( $module ) )
2957
			return false;
2958
2959
		if ( ! Jetpack::is_module( $module ) )
2960
			return false;
2961
2962
		// If it's already active, then don't do it again
2963
		$active = Jetpack::get_active_modules();
2964
		foreach ( $active as $act ) {
2965
			if ( $act == $module )
2966
				return true;
2967
		}
2968
2969
		$module_data = Jetpack::get_module( $module );
2970
2971
		if ( ! Jetpack::is_active() ) {
2972
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2973
				return false;
2974
2975
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2976
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2977
				return false;
2978
		}
2979
2980
		// Check and see if the old plugin is active
2981
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2982
			// Deactivate the old plugin
2983
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2984
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2985
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2986
				Jetpack::state( 'deactivated_plugins', $module );
2987
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2988
				exit;
2989
			}
2990
		}
2991
2992
		// Protect won't work with mis-configured IPs
2993
		if ( 'protect' === $module ) {
2994
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2995
			if ( ! jetpack_protect_get_ip() ) {
2996
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2997
				return false;
2998
			}
2999
		}
3000
3001
		if ( ! Jetpack_Plan::supports( $module ) ) {
3002
			return false;
3003
		}
3004
3005
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3006
		Jetpack::state( 'module', $module );
3007
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3008
3009
		Jetpack::catch_errors( true );
3010
		ob_start();
3011
		require Jetpack::get_module_path( $module );
3012
		/** This action is documented in class.jetpack.php */
3013
		do_action( 'jetpack_activate_module', $module );
3014
		$active[] = $module;
3015
		Jetpack::update_active_modules( $active );
3016
3017
		Jetpack::state( 'error', false ); // the override
3018
		ob_end_clean();
3019
		Jetpack::catch_errors( false );
3020
3021
		if ( $redirect ) {
3022
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3023
		}
3024
		if ( $exit ) {
3025
			exit;
3026
		}
3027
		return true;
3028
	}
3029
3030
	function activate_module_actions( $module ) {
3031
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3032
	}
3033
3034
	public static function deactivate_module( $module ) {
3035
		/**
3036
		 * Fires when a module is deactivated.
3037
		 *
3038
		 * @since 1.9.0
3039
		 *
3040
		 * @param string $module Module slug.
3041
		 */
3042
		do_action( 'jetpack_pre_deactivate_module', $module );
3043
3044
		$jetpack = Jetpack::init();
3045
3046
		$active = Jetpack::get_active_modules();
3047
		$new    = array_filter( array_diff( $active, (array) $module ) );
3048
3049
		return self::update_active_modules( $new );
3050
	}
3051
3052
	public static function enable_module_configurable( $module ) {
3053
		$module = Jetpack::get_module_slug( $module );
3054
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3055
	}
3056
3057
	/**
3058
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3059
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3060
	 *
3061
	 * @param string $module Module slug
3062
	 * @return string $url module configuration URL
3063
	 */
3064
	public static function module_configuration_url( $module ) {
3065
		$module = Jetpack::get_module_slug( $module );
3066
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3067
		/**
3068
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3069
		 *
3070
		 * @since 6.9.0
3071
		 *
3072
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3073
		 */
3074
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3075
3076
		return $url;
3077
	}
3078
3079
/* Installation */
3080
	public static function bail_on_activation( $message, $deactivate = true ) {
3081
?>
3082
<!doctype html>
3083
<html>
3084
<head>
3085
<meta charset="<?php bloginfo( 'charset' ); ?>">
3086
<style>
3087
* {
3088
	text-align: center;
3089
	margin: 0;
3090
	padding: 0;
3091
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3092
}
3093
p {
3094
	margin-top: 1em;
3095
	font-size: 18px;
3096
}
3097
</style>
3098
<body>
3099
<p><?php echo esc_html( $message ); ?></p>
3100
</body>
3101
</html>
3102
<?php
3103
		if ( $deactivate ) {
3104
			$plugins = get_option( 'active_plugins' );
3105
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3106
			$update  = false;
3107
			foreach ( $plugins as $i => $plugin ) {
3108
				if ( $plugin === $jetpack ) {
3109
					$plugins[$i] = false;
3110
					$update = true;
3111
				}
3112
			}
3113
3114
			if ( $update ) {
3115
				update_option( 'active_plugins', array_filter( $plugins ) );
3116
			}
3117
		}
3118
		exit;
3119
	}
3120
3121
	/**
3122
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3123
	 * @static
3124
	 */
3125
	public static function plugin_activation( $network_wide ) {
3126
		Jetpack_Options::update_option( 'activated', 1 );
3127
3128
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3129
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3130
		}
3131
3132
		if ( $network_wide )
3133
			Jetpack::state( 'network_nag', true );
3134
3135
		// For firing one-off events (notices) immediately after activation
3136
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3137
3138
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3139
3140
		Jetpack::plugin_initialize();
3141
	}
3142
3143
	public static function get_activation_source( $referer_url ) {
3144
3145
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3146
			return array( 'wp-cli', null );
3147
		}
3148
3149
		$referer = parse_url( $referer_url );
3150
3151
		$source_type = 'unknown';
3152
		$source_query = null;
3153
3154
		if ( ! is_array( $referer ) ) {
3155
			return array( $source_type, $source_query );
3156
		}
3157
3158
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3159
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3160
3161
		if ( isset( $referer['query'] ) ) {
3162
			parse_str( $referer['query'], $query_parts );
3163
		} else {
3164
			$query_parts = array();
3165
		}
3166
3167
		if ( $plugins_path === $referer['path'] ) {
3168
			$source_type = 'list';
3169
		} elseif ( $plugins_install_path === $referer['path'] ) {
3170
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3171
			switch( $tab ) {
3172
				case 'popular':
3173
					$source_type = 'popular';
3174
					break;
3175
				case 'recommended':
3176
					$source_type = 'recommended';
3177
					break;
3178
				case 'favorites':
3179
					$source_type = 'favorites';
3180
					break;
3181
				case 'search':
3182
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3183
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3184
					break;
3185
				default:
3186
					$source_type = 'featured';
3187
			}
3188
		}
3189
3190
		return array( $source_type, $source_query );
3191
	}
3192
3193
	/**
3194
	 * Runs before bumping version numbers up to a new version
3195
	 * @param  string $version    Version:timestamp
3196
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3197
	 * @return null              [description]
3198
	 */
3199
	public static function do_version_bump( $version, $old_version ) {
3200
		if ( ! $old_version ) { // For new sites
3201
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3202
		}
3203
	}
3204
3205
	/**
3206
	 * Sets the internal version number and activation state.
3207
	 * @static
3208
	 */
3209
	public static function plugin_initialize() {
3210
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3211
			Jetpack_Options::update_option( 'activated', 2 );
3212
		}
3213
3214 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3215
			$version = $old_version = JETPACK__VERSION . ':' . time();
3216
			/** This action is documented in class.jetpack.php */
3217
			do_action( 'updating_jetpack_version', $version, false );
3218
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3219
		}
3220
3221
		Jetpack::load_modules();
3222
3223
		Jetpack_Options::delete_option( 'do_activate' );
3224
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3225
	}
3226
3227
	/**
3228
	 * Removes all connection options
3229
	 * @static
3230
	 */
3231
	public static function plugin_deactivation( ) {
3232
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3233
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3234
			Jetpack_Network::init()->deactivate();
3235
		} else {
3236
			Jetpack::disconnect( false );
3237
			//Jetpack_Heartbeat::init()->deactivate();
3238
		}
3239
	}
3240
3241
	/**
3242
	 * Disconnects from the Jetpack servers.
3243
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3244
	 * @static
3245
	 */
3246
	public static function disconnect( $update_activated_state = true ) {
3247
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3248
		Jetpack::clean_nonces( true );
3249
3250
		// If the site is in an IDC because sync is not allowed,
3251
		// let's make sure to not disconnect the production site.
3252
		if ( ! self::validate_sync_error_idc_option() ) {
3253
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3254
			Jetpack::load_xml_rpc_client();
3255
			$xml = new Jetpack_IXR_Client();
3256
			$xml->query( 'jetpack.deregister' );
3257
		}
3258
3259
		Jetpack_Options::delete_option(
3260
			array(
3261
				'blog_token',
3262
				'user_token',
3263
				'user_tokens',
3264
				'master_user',
3265
				'time_diff',
3266
				'fallback_no_verify_ssl_certs',
3267
			)
3268
		);
3269
3270
		Jetpack_IDC::clear_all_idc_options();
3271
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3272
3273
		if ( $update_activated_state ) {
3274
			Jetpack_Options::update_option( 'activated', 4 );
3275
		}
3276
3277
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3278
			// Check then record unique disconnection if site has never been disconnected previously
3279
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3280
				$jetpack_unique_connection['disconnected'] = 1;
3281
			} else {
3282
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3283
					//track unique disconnect
3284
					$jetpack = Jetpack::init();
3285
3286
					$jetpack->stat( 'connections', 'unique-disconnect' );
3287
					$jetpack->do_stats( 'server_side' );
3288
				}
3289
				// increment number of times disconnected
3290
				$jetpack_unique_connection['disconnected'] += 1;
3291
			}
3292
3293
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3294
		}
3295
3296
		// Delete cached connected user data
3297
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3298
		delete_transient( $transient_key );
3299
3300
		// Delete all the sync related data. Since it could be taking up space.
3301
		Jetpack_Sync_Sender::get_instance()->uninstall();
3302
3303
		// Disable the Heartbeat cron
3304
		Jetpack_Heartbeat::init()->deactivate();
3305
	}
3306
3307
	/**
3308
	 * Unlinks the current user from the linked WordPress.com user
3309
	 */
3310
	public static function unlink_user( $user_id = null ) {
3311
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3312
			return false;
3313
3314
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3315
3316
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3317
			return false;
3318
3319
		if ( ! isset( $tokens[ $user_id ] ) )
3320
			return false;
3321
3322
		Jetpack::load_xml_rpc_client();
3323
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3324
		$xml->query( 'jetpack.unlink_user', $user_id );
3325
3326
		unset( $tokens[ $user_id ] );
3327
3328
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3329
3330
		/**
3331
		 * Fires after the current user has been unlinked from WordPress.com.
3332
		 *
3333
		 * @since 4.1.0
3334
		 *
3335
		 * @param int $user_id The current user's ID.
3336
		 */
3337
		do_action( 'jetpack_unlinked_user', $user_id );
3338
3339
		return true;
3340
	}
3341
3342
	/**
3343
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3344
	 */
3345
	public static function try_registration() {
3346
		// The user has agreed to the TOS at some point by now.
3347
		Jetpack_Options::update_option( 'tos_agreed', true );
3348
3349
		// Let's get some testing in beta versions and such.
3350
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3351
			// Before attempting to connect, let's make sure that the domains are viable.
3352
			$domains_to_check = array_unique( array(
3353
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3354
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3355
			) );
3356
			foreach ( $domains_to_check as $domain ) {
3357
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3356 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3358
				if ( is_wp_error( $result ) ) {
3359
					return $result;
3360
				}
3361
			}
3362
		}
3363
3364
		$result = Jetpack::register();
3365
3366
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3367
		if ( ! $result || is_wp_error( $result ) ) {
3368
			return $result;
3369
		} else {
3370
			return true;
3371
		}
3372
	}
3373
3374
	/**
3375
	 * Tracking an internal event log. Try not to put too much chaff in here.
3376
	 *
3377
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3378
	 */
3379
	public static function log( $code, $data = null ) {
3380
		// only grab the latest 200 entries
3381
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3382
3383
		// Append our event to the log
3384
		$log_entry = array(
3385
			'time'    => time(),
3386
			'user_id' => get_current_user_id(),
3387
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3388
			'code'    => $code,
3389
		);
3390
		// Don't bother storing it unless we've got some.
3391
		if ( ! is_null( $data ) ) {
3392
			$log_entry['data'] = $data;
3393
		}
3394
		$log[] = $log_entry;
3395
3396
		// Try add_option first, to make sure it's not autoloaded.
3397
		// @todo: Add an add_option method to Jetpack_Options
3398
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3399
			Jetpack_Options::update_option( 'log', $log );
3400
		}
3401
3402
		/**
3403
		 * Fires when Jetpack logs an internal event.
3404
		 *
3405
		 * @since 3.0.0
3406
		 *
3407
		 * @param array $log_entry {
3408
		 *	Array of details about the log entry.
3409
		 *
3410
		 *	@param string time Time of the event.
3411
		 *	@param int user_id ID of the user who trigerred the event.
3412
		 *	@param int blog_id Jetpack Blog ID.
3413
		 *	@param string code Unique name for the event.
3414
		 *	@param string data Data about the event.
3415
		 * }
3416
		 */
3417
		do_action( 'jetpack_log_entry', $log_entry );
3418
	}
3419
3420
	/**
3421
	 * Get the internal event log.
3422
	 *
3423
	 * @param $event (string) - only return the specific log events
3424
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3425
	 *
3426
	 * @return array of log events || WP_Error for invalid params
3427
	 */
3428
	public static function get_log( $event = false, $num = false ) {
3429
		if ( $event && ! is_string( $event ) ) {
3430
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3431
		}
3432
3433
		if ( $num && ! is_numeric( $num ) ) {
3434
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3435
		}
3436
3437
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3438
3439
		// If nothing set - act as it did before, otherwise let's start customizing the output
3440
		if ( ! $num && ! $event ) {
3441
			return $entire_log;
3442
		} else {
3443
			$entire_log = array_reverse( $entire_log );
3444
		}
3445
3446
		$custom_log_output = array();
3447
3448
		if ( $event ) {
3449
			foreach ( $entire_log as $log_event ) {
3450
				if ( $event == $log_event[ 'code' ] ) {
3451
					$custom_log_output[] = $log_event;
3452
				}
3453
			}
3454
		} else {
3455
			$custom_log_output = $entire_log;
3456
		}
3457
3458
		if ( $num ) {
3459
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3460
		}
3461
3462
		return $custom_log_output;
3463
	}
3464
3465
	/**
3466
	 * Log modification of important settings.
3467
	 */
3468
	public static function log_settings_change( $option, $old_value, $value ) {
3469
		switch( $option ) {
3470
			case 'jetpack_sync_non_public_post_stati':
3471
				self::log( $option, $value );
3472
				break;
3473
		}
3474
	}
3475
3476
	/**
3477
	 * Return stat data for WPCOM sync
3478
	 */
3479
	public static function get_stat_data( $encode = true, $extended = true ) {
3480
		$data = Jetpack_Heartbeat::generate_stats_array();
3481
3482
		if ( $extended ) {
3483
			$additional_data = self::get_additional_stat_data();
3484
			$data = array_merge( $data, $additional_data );
3485
		}
3486
3487
		if ( $encode ) {
3488
			return json_encode( $data );
3489
		}
3490
3491
		return $data;
3492
	}
3493
3494
	/**
3495
	 * Get additional stat data to sync to WPCOM
3496
	 */
3497
	public static function get_additional_stat_data( $prefix = '' ) {
3498
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3499
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3500
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3501
		$return["{$prefix}site-count"]     = 0;
3502
3503
		if ( function_exists( 'get_blog_count' ) ) {
3504
			$return["{$prefix}site-count"] = get_blog_count();
3505
		}
3506
		return $return;
3507
	}
3508
3509
	private static function get_site_user_count() {
3510
		global $wpdb;
3511
3512
		if ( function_exists( 'wp_is_large_network' ) ) {
3513
			if ( wp_is_large_network( 'users' ) ) {
3514
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3515
			}
3516
		}
3517 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3518
			// It wasn't there, so regenerate the data and save the transient
3519
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3520
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3521
		}
3522
		return $user_count;
3523
	}
3524
3525
	/* Admin Pages */
3526
3527
	function admin_init() {
3528
		// If the plugin is not connected, display a connect message.
3529
		if (
3530
			// the plugin was auto-activated and needs its candy
3531
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3532
		||
3533
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3534
			! Jetpack_Options::get_option( 'activated' )
3535
		) {
3536
			Jetpack::plugin_initialize();
3537
		}
3538
3539
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3540
			Jetpack_Connection_Banner::init();
3541
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3542
			// Upgrade: 1.1 -> 1.1.1
3543
			// Check and see if host can verify the Jetpack servers' SSL certificate
3544
			$args = array();
3545
			Jetpack_Client::_wp_remote_request(
3546
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3547
				$args,
3548
				true
3549
			);
3550
		}
3551
3552
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3553
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3554
		}
3555
3556
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3557
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3558
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3559
3560
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3561
			// Artificially throw errors in certain whitelisted cases during plugin activation
3562
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3563
		}
3564
3565
		// Add custom column in wp-admin/users.php to show whether user is linked.
3566
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3567
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3568
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3569
	}
3570
3571
	function admin_body_class( $admin_body_class = '' ) {
3572
		$classes = explode( ' ', trim( $admin_body_class ) );
3573
3574
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3575
3576
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3577
		return " $admin_body_class ";
3578
	}
3579
3580
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3581
		return $admin_body_class . ' jetpack-pagestyles ';
3582
	}
3583
3584
	/**
3585
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3586
	 * This function artificially throws errors for such cases (whitelisted).
3587
	 *
3588
	 * @param string $plugin The activated plugin.
3589
	 */
3590
	function throw_error_on_activate_plugin( $plugin ) {
3591
		$active_modules = Jetpack::get_active_modules();
3592
3593
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3594
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3595
			$throw = false;
3596
3597
			// Try and make sure it really was the stats plugin
3598
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3599
				if ( 'stats.php' == basename( $plugin ) ) {
3600
					$throw = true;
3601
				}
3602
			} else {
3603
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3604
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3605
					$throw = true;
3606
				}
3607
			}
3608
3609
			if ( $throw ) {
3610
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3611
			}
3612
		}
3613
	}
3614
3615
	function intercept_plugin_error_scrape_init() {
3616
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3617
	}
3618
3619
	function intercept_plugin_error_scrape( $action, $result ) {
3620
		if ( ! $result ) {
3621
			return;
3622
		}
3623
3624
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3625
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3626
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3627
			}
3628
		}
3629
	}
3630
3631
	function add_remote_request_handlers() {
3632
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3633
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3634
	}
3635
3636
	function remote_request_handlers() {
3637
		$action = current_filter();
3638
3639
		switch ( current_filter() ) {
3640
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3641
			$response = $this->upload_handler();
3642
			break;
3643
3644
		case 'wp_ajax_nopriv_jetpack_update_file' :
3645
			$response = $this->upload_handler( true );
3646
			break;
3647
		default :
3648
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3649
			break;
3650
		}
3651
3652
		if ( ! $response ) {
3653
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3654
		}
3655
3656
		if ( is_wp_error( $response ) ) {
3657
			$status_code       = $response->get_error_data();
3658
			$error             = $response->get_error_code();
3659
			$error_description = $response->get_error_message();
3660
3661
			if ( ! is_int( $status_code ) ) {
3662
				$status_code = 400;
3663
			}
3664
3665
			status_header( $status_code );
3666
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3667
		}
3668
3669
		status_header( 200 );
3670
		if ( true === $response ) {
3671
			exit;
3672
		}
3673
3674
		die( json_encode( (object) $response ) );
3675
	}
3676
3677
	/**
3678
	 * Uploads a file gotten from the global $_FILES.
3679
	 * If `$update_media_item` is true and `post_id` is defined
3680
	 * the attachment file of the media item (gotten through of the post_id)
3681
	 * will be updated instead of add a new one.
3682
	 *
3683
	 * @param  boolean $update_media_item - update media attachment
3684
	 * @return array - An array describing the uploadind files process
3685
	 */
3686
	function upload_handler( $update_media_item = false ) {
3687
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3688
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3689
		}
3690
3691
		$user = wp_authenticate( '', '' );
3692
		if ( ! $user || is_wp_error( $user ) ) {
3693
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3694
		}
3695
3696
		wp_set_current_user( $user->ID );
3697
3698
		if ( ! current_user_can( 'upload_files' ) ) {
3699
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3700
		}
3701
3702
		if ( empty( $_FILES ) ) {
3703
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3704
		}
3705
3706
		foreach ( array_keys( $_FILES ) as $files_key ) {
3707
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3708
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3709
			}
3710
		}
3711
3712
		$media_keys = array_keys( $_FILES['media'] );
3713
3714
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3715
		if ( ! $token || is_wp_error( $token ) ) {
3716
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3717
		}
3718
3719
		$uploaded_files = array();
3720
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3721
		unset( $GLOBALS['post'] );
3722
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3723
			$file = array();
3724
			foreach ( $media_keys as $media_key ) {
3725
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3726
			}
3727
3728
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3729
3730
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3731
			if ( $hmac_provided !== $hmac_file ) {
3732
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3733
				continue;
3734
			}
3735
3736
			$_FILES['.jetpack.upload.'] = $file;
3737
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3738
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3739
				$post_id = 0;
3740
			}
3741
3742
			if ( $update_media_item ) {
3743
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3744
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3745
				}
3746
3747
				$media_array = $_FILES['media'];
3748
3749
				$file_array['name'] = $media_array['name'][0];
3750
				$file_array['type'] = $media_array['type'][0];
3751
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3752
				$file_array['error'] = $media_array['error'][0];
3753
				$file_array['size'] = $media_array['size'][0];
3754
3755
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3756
3757
				if ( is_wp_error( $edited_media_item ) ) {
3758
					return $edited_media_item;
3759
				}
3760
3761
				$response = (object) array(
3762
					'id'   => (string) $post_id,
3763
					'file' => (string) $edited_media_item->post_title,
3764
					'url'  => (string) wp_get_attachment_url( $post_id ),
3765
					'type' => (string) $edited_media_item->post_mime_type,
3766
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3767
				);
3768
3769
				return (array) array( $response );
3770
			}
3771
3772
			$attachment_id = media_handle_upload(
3773
				'.jetpack.upload.',
3774
				$post_id,
3775
				array(),
3776
				array(
3777
					'action' => 'jetpack_upload_file',
3778
				)
3779
			);
3780
3781
			if ( ! $attachment_id ) {
3782
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3783
			} elseif ( is_wp_error( $attachment_id ) ) {
3784
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3785
			} else {
3786
				$attachment = get_post( $attachment_id );
3787
				$uploaded_files[$index] = (object) array(
3788
					'id'   => (string) $attachment_id,
3789
					'file' => $attachment->post_title,
3790
					'url'  => wp_get_attachment_url( $attachment_id ),
3791
					'type' => $attachment->post_mime_type,
3792
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3793
				);
3794
				// Zip files uploads are not supported unless they are done for installation purposed
3795
				// lets delete them in case something goes wrong in this whole process
3796
				if ( 'application/zip' === $attachment->post_mime_type ) {
3797
					// Schedule a cleanup for 2 hours from now in case of failed install.
3798
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3799
				}
3800
			}
3801
		}
3802
		if ( ! is_null( $global_post ) ) {
3803
			$GLOBALS['post'] = $global_post;
3804
		}
3805
3806
		return $uploaded_files;
3807
	}
3808
3809
	/**
3810
	 * Add help to the Jetpack page
3811
	 *
3812
	 * @since Jetpack (1.2.3)
3813
	 * @return false if not the Jetpack page
3814
	 */
3815
	function admin_help() {
3816
		$current_screen = get_current_screen();
3817
3818
		// Overview
3819
		$current_screen->add_help_tab(
3820
			array(
3821
				'id'		=> 'home',
3822
				'title'		=> __( 'Home', 'jetpack' ),
3823
				'content'	=>
3824
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3825
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3826
					'<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>',
3827
			)
3828
		);
3829
3830
		// Screen Content
3831
		if ( current_user_can( 'manage_options' ) ) {
3832
			$current_screen->add_help_tab(
3833
				array(
3834
					'id'		=> 'settings',
3835
					'title'		=> __( 'Settings', 'jetpack' ),
3836
					'content'	=>
3837
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3838
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3839
						'<ol>' .
3840
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3841
							'<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>' .
3842
						'</ol>' .
3843
						'<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>'
3844
				)
3845
			);
3846
		}
3847
3848
		// Help Sidebar
3849
		$current_screen->set_help_sidebar(
3850
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3851
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3852
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3853
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3854
		);
3855
	}
3856
3857
	function admin_menu_css() {
3858
		wp_enqueue_style( 'jetpack-icons' );
3859
	}
3860
3861
	function admin_menu_order() {
3862
		return true;
3863
	}
3864
3865 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3866
		$jp_menu_order = array();
3867
3868
		foreach ( $menu_order as $index => $item ) {
3869
			if ( $item != 'jetpack' ) {
3870
				$jp_menu_order[] = $item;
3871
			}
3872
3873
			if ( $index == 0 ) {
3874
				$jp_menu_order[] = 'jetpack';
3875
			}
3876
		}
3877
3878
		return $jp_menu_order;
3879
	}
3880
3881
	function admin_banner_styles() {
3882
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3883
3884
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3885
			wp_register_style(
3886
				'jetpack-dops-style',
3887
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3888
				array(),
3889
				JETPACK__VERSION
3890
			);
3891
		}
3892
3893
		wp_enqueue_style(
3894
			'jetpack',
3895
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3896
			array( 'jetpack-dops-style' ),
3897
			 JETPACK__VERSION . '-20121016'
3898
		);
3899
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3900
		wp_style_add_data( 'jetpack', 'suffix', $min );
3901
	}
3902
3903
	function plugin_action_links( $actions ) {
3904
3905
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3906
3907
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3908
			return array_merge(
3909
				$jetpack_home,
3910
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3911
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3912
				$actions
3913
				);
3914
			}
3915
3916
		return array_merge( $jetpack_home, $actions );
3917
	}
3918
3919
	/*
3920
	 * Registration flow:
3921
	 * 1 - ::admin_page_load() action=register
3922
	 * 2 - ::try_registration()
3923
	 * 3 - ::register()
3924
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3925
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3926
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3927
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3928
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3929
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3930
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3931
	 *       jetpack_id, jetpack_secret, jetpack_public
3932
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3933
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3934
	 * 5 - user logs in with WP.com account
3935
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3936
	 *		- Jetpack_Client_Server::authorize()
3937
	 *		- Jetpack_Client_Server::get_token()
3938
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3939
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3940
	 *			- which responds with access_token, token_type, scope
3941
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3942
	 *		- Jetpack::activate_default_modules()
3943
	 *     		- Deactivates deprecated plugins
3944
	 *     		- Activates all default modules
3945
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3946
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3947
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3948
	 *     Done!
3949
	 */
3950
3951
	/**
3952
	 * Handles the page load events for the Jetpack admin page
3953
	 */
3954
	function admin_page_load() {
3955
		$error = false;
3956
3957
		// Make sure we have the right body class to hook stylings for subpages off of.
3958
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3959
3960
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3961
			// Should only be used in intermediate redirects to preserve state across redirects
3962
			Jetpack::restate();
3963
		}
3964
3965
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3966
			// @todo: Add validation against a known whitelist
3967
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3968
			// User clicked in the iframe to link their accounts
3969
			if ( ! Jetpack::is_user_connected() ) {
3970
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3971
3972
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3973
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3974
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3975
3976
				if ( isset( $_GET['notes_iframe'] ) )
3977
					$connect_url .= '&notes_iframe';
3978
				wp_redirect( $connect_url );
3979
				exit;
3980
			} else {
3981
				if ( ! isset( $_GET['calypso_env'] ) ) {
3982
					Jetpack::state( 'message', 'already_authorized' );
3983
					wp_safe_redirect( Jetpack::admin_url() );
3984
					exit;
3985
				} else {
3986
					$connect_url = $this->build_connect_url( true, false, $from );
3987
					$connect_url .= '&already_authorized=true';
3988
					wp_redirect( $connect_url );
3989
					exit;
3990
				}
3991
			}
3992
		}
3993
3994
3995
		if ( isset( $_GET['action'] ) ) {
3996
			switch ( $_GET['action'] ) {
3997
			case 'authorize':
3998
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3999
					Jetpack::state( 'message', 'already_authorized' );
4000
					wp_safe_redirect( Jetpack::admin_url() );
4001
					exit;
4002
				}
4003
				Jetpack::log( 'authorize' );
4004
				$client_server = new Jetpack_Client_Server;
4005
				$client_server->client_authorize();
4006
				exit;
4007
			case 'register' :
4008
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4009
					$error = 'cheatin';
4010
					break;
4011
				}
4012
				check_admin_referer( 'jetpack-register' );
4013
				Jetpack::log( 'register' );
4014
				Jetpack::maybe_set_version_option();
4015
				$registered = Jetpack::try_registration();
4016
				if ( is_wp_error( $registered ) ) {
4017
					$error = $registered->get_error_code();
4018
					Jetpack::state( 'error', $error );
4019
					Jetpack::state( 'error', $registered->get_error_message() );
4020
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4021
						'error_code' => $error,
4022
						'error_message' => $registered->get_error_message()
4023
					) );
4024
					break;
4025
				}
4026
4027
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4028
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4029
4030
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4031
					'from' => $from
4032
				) );
4033
4034
				$url = $this->build_connect_url( true, $redirect, $from );
4035
4036
				if ( ! empty( $_GET['onboarding'] ) ) {
4037
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4038
				}
4039
4040
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4041
					$url = add_query_arg( 'auth_approved', 'true', $url );
4042
				}
4043
4044
				wp_redirect( $url );
4045
				exit;
4046
			case 'activate' :
4047
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4048
					$error = 'cheatin';
4049
					break;
4050
				}
4051
4052
				$module = stripslashes( $_GET['module'] );
4053
				check_admin_referer( "jetpack_activate-$module" );
4054
				Jetpack::log( 'activate', $module );
4055
				if ( ! Jetpack::activate_module( $module ) ) {
4056
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4057
				}
4058
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4059
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4060
				exit;
4061
			case 'activate_default_modules' :
4062
				check_admin_referer( 'activate_default_modules' );
4063
				Jetpack::log( 'activate_default_modules' );
4064
				Jetpack::restate();
4065
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4066
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4067
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4068
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4069
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4070
				exit;
4071
			case 'disconnect' :
4072
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4073
					$error = 'cheatin';
4074
					break;
4075
				}
4076
4077
				check_admin_referer( 'jetpack-disconnect' );
4078
				Jetpack::log( 'disconnect' );
4079
				Jetpack::disconnect();
4080
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4081
				exit;
4082
			case 'reconnect' :
4083
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4084
					$error = 'cheatin';
4085
					break;
4086
				}
4087
4088
				check_admin_referer( 'jetpack-reconnect' );
4089
				Jetpack::log( 'reconnect' );
4090
				$this->disconnect();
4091
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4092
				exit;
4093 View Code Duplication
			case 'deactivate' :
4094
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4095
					$error = 'cheatin';
4096
					break;
4097
				}
4098
4099
				$modules = stripslashes( $_GET['module'] );
4100
				check_admin_referer( "jetpack_deactivate-$modules" );
4101
				foreach ( explode( ',', $modules ) as $module ) {
4102
					Jetpack::log( 'deactivate', $module );
4103
					Jetpack::deactivate_module( $module );
4104
					Jetpack::state( 'message', 'module_deactivated' );
4105
				}
4106
				Jetpack::state( 'module', $modules );
4107
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4108
				exit;
4109
			case 'unlink' :
4110
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4111
				check_admin_referer( 'jetpack-unlink' );
4112
				Jetpack::log( 'unlink' );
4113
				$this->unlink_user();
4114
				Jetpack::state( 'message', 'unlinked' );
4115
				if ( 'sub-unlink' == $redirect ) {
4116
					wp_safe_redirect( admin_url() );
4117
				} else {
4118
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4119
				}
4120
				exit;
4121
			case 'onboard' :
4122
				if ( ! current_user_can( 'manage_options' ) ) {
4123
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4124
				} else {
4125
					Jetpack::create_onboarding_token();
4126
					$url = $this->build_connect_url( true );
4127
4128
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4129
						$url = add_query_arg( 'onboarding', $token, $url );
4130
					}
4131
4132
					$calypso_env = $this->get_calypso_env();
4133
					if ( ! empty( $calypso_env ) ) {
4134
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4135
					}
4136
4137
					wp_redirect( $url );
4138
					exit;
4139
				}
4140
				exit;
4141
			default:
4142
				/**
4143
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4144
				 *
4145
				 * @since 2.6.0
4146
				 *
4147
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4148
				 */
4149
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4150
			}
4151
		}
4152
4153
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4154
			self::activate_new_modules( true );
4155
		}
4156
4157
		$message_code = Jetpack::state( 'message' );
4158
		if ( Jetpack::state( 'optin-manage' ) ) {
4159
			$activated_manage = $message_code;
4160
			$message_code = 'jetpack-manage';
4161
		}
4162
4163
		switch ( $message_code ) {
4164
		case 'jetpack-manage':
4165
			$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>';
4166
			if ( $activated_manage ) {
4167
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4168
			}
4169
			break;
4170
4171
		}
4172
4173
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4174
4175
		if ( ! empty( $deactivated_plugins ) ) {
4176
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4177
			$deactivated_titles  = array();
4178
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4179
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4180
					continue;
4181
				}
4182
4183
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4184
			}
4185
4186
			if ( $deactivated_titles ) {
4187
				if ( $this->message ) {
4188
					$this->message .= "<br /><br />\n";
4189
				}
4190
4191
				$this->message .= wp_sprintf(
4192
					_n(
4193
						'Jetpack contains the most recent version of the old %l plugin.',
4194
						'Jetpack contains the most recent versions of the old %l plugins.',
4195
						count( $deactivated_titles ),
4196
						'jetpack'
4197
					),
4198
					$deactivated_titles
4199
				);
4200
4201
				$this->message .= "<br />\n";
4202
4203
				$this->message .= _n(
4204
					'The old version has been deactivated and can be removed from your site.',
4205
					'The old versions have been deactivated and can be removed from your site.',
4206
					count( $deactivated_titles ),
4207
					'jetpack'
4208
				);
4209
			}
4210
		}
4211
4212
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4213
4214
		if ( $this->message || $this->error || $this->privacy_checks ) {
4215
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4216
		}
4217
4218
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4219
	}
4220
4221
	function admin_notices() {
4222
4223
		if ( $this->error ) {
4224
?>
4225
<div id="message" class="jetpack-message jetpack-err">
4226
	<div class="squeezer">
4227
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4228
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4229
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4230
<?php	endif; ?>
4231
	</div>
4232
</div>
4233
<?php
4234
		}
4235
4236
		if ( $this->message ) {
4237
?>
4238
<div id="message" class="jetpack-message">
4239
	<div class="squeezer">
4240
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4241
	</div>
4242
</div>
4243
<?php
4244
		}
4245
4246
		if ( $this->privacy_checks ) :
4247
			$module_names = $module_slugs = array();
4248
4249
			$privacy_checks = explode( ',', $this->privacy_checks );
4250
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4251
			foreach ( $privacy_checks as $module_slug ) {
4252
				$module = Jetpack::get_module( $module_slug );
4253
				if ( ! $module ) {
4254
					continue;
4255
				}
4256
4257
				$module_slugs[] = $module_slug;
4258
				$module_names[] = "<strong>{$module['name']}</strong>";
4259
			}
4260
4261
			$module_slugs = join( ',', $module_slugs );
4262
?>
4263
<div id="message" class="jetpack-message jetpack-err">
4264
	<div class="squeezer">
4265
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4266
		<p><?php
4267
			echo wp_kses(
4268
				wptexturize(
4269
					wp_sprintf(
4270
						_nx(
4271
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4272
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4273
							count( $privacy_checks ),
4274
							'%l = list of Jetpack module/feature names',
4275
							'jetpack'
4276
						),
4277
						$module_names
4278
					)
4279
				),
4280
				array( 'strong' => true )
4281
			);
4282
4283
			echo "\n<br />\n";
4284
4285
			echo wp_kses(
4286
				sprintf(
4287
					_nx(
4288
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4289
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4290
						count( $privacy_checks ),
4291
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4292
						'jetpack'
4293
					),
4294
					wp_nonce_url(
4295
						Jetpack::admin_url(
4296
							array(
4297
								'page'   => 'jetpack',
4298
								'action' => 'deactivate',
4299
								'module' => urlencode( $module_slugs ),
4300
							)
4301
						),
4302
						"jetpack_deactivate-$module_slugs"
4303
					),
4304
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4305
				),
4306
				array( 'a' => array( 'href' => true, 'title' => true ) )
4307
			);
4308
		?></p>
4309
	</div>
4310
</div>
4311
<?php endif;
4312
	}
4313
4314
	/**
4315
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4316
	 */
4317
	function stat( $group, $detail ) {
4318
		if ( ! isset( $this->stats[ $group ] ) )
4319
			$this->stats[ $group ] = array();
4320
		$this->stats[ $group ][] = $detail;
4321
	}
4322
4323
	/**
4324
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4325
	 */
4326
	function do_stats( $method = '' ) {
4327
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4328
			foreach ( $this->stats as $group => $stats ) {
4329
				if ( is_array( $stats ) && count( $stats ) ) {
4330
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4331
					if ( 'server_side' === $method ) {
4332
						self::do_server_side_stat( $args );
4333
					} else {
4334
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4335
					}
4336
				}
4337
				unset( $this->stats[ $group ] );
4338
			}
4339
		}
4340
	}
4341
4342
	/**
4343
	 * Runs stats code for a one-off, server-side.
4344
	 *
4345
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4346
	 *
4347
	 * @return bool If it worked.
4348
	 */
4349
	static function do_server_side_stat( $args ) {
4350
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4351
		if ( is_wp_error( $response ) )
4352
			return false;
4353
4354
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4355
			return false;
4356
4357
		return true;
4358
	}
4359
4360
	/**
4361
	 * Builds the stats url.
4362
	 *
4363
	 * @param $args array|string The arguments to append to the URL.
4364
	 *
4365
	 * @return string The URL to be pinged.
4366
	 */
4367
	static function build_stats_url( $args ) {
4368
		$defaults = array(
4369
			'v'    => 'wpcom2',
4370
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4371
		);
4372
		$args     = wp_parse_args( $args, $defaults );
4373
		/**
4374
		 * Filter the URL used as the Stats tracking pixel.
4375
		 *
4376
		 * @since 2.3.2
4377
		 *
4378
		 * @param string $url Base URL used as the Stats tracking pixel.
4379
		 */
4380
		$base_url = apply_filters(
4381
			'jetpack_stats_base_url',
4382
			'https://pixel.wp.com/g.gif'
4383
		);
4384
		$url      = add_query_arg( $args, $base_url );
4385
		return $url;
4386
	}
4387
4388
	static function translate_current_user_to_role() {
4389
		foreach ( self::$capability_translations as $role => $cap ) {
4390
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4391
				return $role;
4392
			}
4393
		}
4394
4395
		return false;
4396
	}
4397
4398
	static function translate_user_to_role( $user ) {
4399
		foreach ( self::$capability_translations as $role => $cap ) {
4400
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4401
				return $role;
4402
			}
4403
		}
4404
4405
		return false;
4406
    }
4407
4408
	static function translate_role_to_cap( $role ) {
4409
		if ( ! isset( self::$capability_translations[$role] ) ) {
4410
			return false;
4411
		}
4412
4413
		return self::$capability_translations[$role];
4414
	}
4415
4416
	static function sign_role( $role, $user_id = null ) {
4417
		if ( empty( $user_id ) ) {
4418
			$user_id = (int) get_current_user_id();
4419
		}
4420
4421
		if ( ! $user_id  ) {
4422
			return false;
4423
		}
4424
4425
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4426
		if ( ! $token || is_wp_error( $token ) ) {
4427
			return false;
4428
		}
4429
4430
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4431
	}
4432
4433
4434
	/**
4435
	 * Builds a URL to the Jetpack connection auth page
4436
	 *
4437
	 * @since 3.9.5
4438
	 *
4439
	 * @param bool $raw If true, URL will not be escaped.
4440
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4441
	 *                              If string, will be a custom redirect.
4442
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4443
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4444
	 *
4445
	 * @return string Connect URL
4446
	 */
4447
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4448
		$site_id = Jetpack_Options::get_option( 'id' );
4449
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4450
4451
		if ( $register || ! $blog_token || ! $site_id ) {
4452
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4453
4454
			if ( ! empty( $redirect ) ) {
4455
				$url = add_query_arg(
4456
					'redirect',
4457
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4458
					$url
4459
				);
4460
			}
4461
4462
			if( is_network_admin() ) {
4463
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4464
			}
4465
		} else {
4466
4467
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4468
			// because otherwise this logic can get us in to a loop.
4469
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4470
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4471
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4472
4473
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4474
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4475
					'1.1'
4476
				);
4477
4478
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4479
4480
					// Generating a register URL instead to refresh the existing token
4481
					return $this->build_connect_url( $raw, $redirect, $from, true );
4482
				}
4483
			}
4484
4485
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4486
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4487
			}
4488
4489
			$role = self::translate_current_user_to_role();
4490
			$signed_role = self::sign_role( $role );
4491
4492
			$user = wp_get_current_user();
4493
4494
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4495
			$redirect = $redirect
4496
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4497
				: $jetpack_admin_page;
4498
4499
			if( isset( $_REQUEST['is_multisite'] ) ) {
4500
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4501
			}
4502
4503
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4504
4505
			/**
4506
			 * Filter the type of authorization.
4507
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4508
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4509
			 *
4510
			 * @since 4.3.3
4511
			 *
4512
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4513
			 */
4514
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4515
4516
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4517
4518
			$args = urlencode_deep(
4519
				array(
4520
					'response_type' => 'code',
4521
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4522
					'redirect_uri'  => add_query_arg(
4523
						array(
4524
							'action'   => 'authorize',
4525
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4526
							'redirect' => urlencode( $redirect ),
4527
						),
4528
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4529
					),
4530
					'state'         => $user->ID,
4531
					'scope'         => $signed_role,
4532
					'user_email'    => $user->user_email,
4533
					'user_login'    => $user->user_login,
4534
					'is_active'     => Jetpack::is_active(),
4535
					'jp_version'    => JETPACK__VERSION,
4536
					'auth_type'     => $auth_type,
4537
					'secret'        => $secrets['secret_1'],
4538
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4539
					'blogname'      => get_option( 'blogname' ),
4540
					'site_url'      => site_url(),
4541
					'home_url'      => home_url(),
4542
					'site_icon'     => get_site_icon_url(),
4543
					'site_lang'     => get_locale(),
4544
					'_ui'           => $tracks_identity['_ui'],
4545
					'_ut'           => $tracks_identity['_ut'],
4546
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4547
				)
4548
			);
4549
4550
			self::apply_activation_source_to_args( $args );
4551
4552
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4553
		}
4554
4555
		if ( $from ) {
4556
			$url = add_query_arg( 'from', $from, $url );
4557
		}
4558
4559
		// Ensure that class to get the affiliate code is loaded
4560
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4561
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4562
		}
4563
		// Get affiliate code and add it to the URL
4564
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4565
4566
		$calypso_env = $this->get_calypso_env();
4567
4568
		if ( ! empty( $calypso_env ) ) {
4569
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4570
		}
4571
4572
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4573
	}
4574
4575
	/**
4576
	 * Get our assumed site creation date.
4577
	 * Calculated based on the earlier date of either:
4578
	 * - Earliest admin user registration date.
4579
	 * - Earliest date of post of any post type.
4580
	 *
4581
	 * @since 7.2.0
4582
	 *
4583
	 * @return string Assumed site creation date and time.
4584
	 */
4585
	public static function get_assumed_site_creation_date() {
4586
		$earliest_registered_users = get_users( array(
4587
			'role'    => 'administrator',
4588
			'orderby' => 'user_registered',
4589
			'order'   => 'ASC',
4590
			'fields'  => array( 'user_registered' ),
4591
			'number'  => 1,
4592
		) );
4593
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4594
4595
		$earliest_posts = get_posts( array(
4596
			'posts_per_page' => 1,
4597
			'post_type'      => 'any',
4598
			'post_status'    => 'any',
4599
			'orderby'        => 'date',
4600
			'order'          => 'ASC',
4601
		) );
4602
4603
		// If there are no posts at all, we'll count only on user registration date.
4604
		if ( $earliest_posts ) {
4605
			$earliest_post_date = $earliest_posts[0]->post_date;
4606
		} else {
4607
			$earliest_post_date = PHP_INT_MAX;
4608
		}
4609
4610
		return min( $earliest_registration_date, $earliest_post_date );
4611
	}
4612
4613
	public static function apply_activation_source_to_args( &$args ) {
4614
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4615
4616
		if ( $activation_source_name ) {
4617
			$args['_as'] = urlencode( $activation_source_name );
4618
		}
4619
4620
		if ( $activation_source_keyword ) {
4621
			$args['_ak'] = urlencode( $activation_source_keyword );
4622
		}
4623
	}
4624
4625
	function build_reconnect_url( $raw = false ) {
4626
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4627
		return $raw ? $url : esc_url( $url );
4628
	}
4629
4630
	public static function admin_url( $args = null ) {
4631
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4632
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4633
		return $url;
4634
	}
4635
4636
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4637
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4638
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4639
	}
4640
4641
	function dismiss_jetpack_notice() {
4642
4643
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4644
			return;
4645
		}
4646
4647
		switch( $_GET['jetpack-notice'] ) {
4648
			case 'dismiss':
4649
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4650
4651
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4652
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4653
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4654
				}
4655
				break;
4656
			case 'jetpack-protect-multisite-opt-out':
4657
4658
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4659
					// Don't show the banner again
4660
4661
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4662
					// redirect back to the page that had the notice
4663
					if ( wp_get_referer() ) {
4664
						wp_safe_redirect( wp_get_referer() );
4665
					} else {
4666
						// Take me to Jetpack
4667
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4668
					}
4669
				}
4670
				break;
4671
		}
4672
	}
4673
4674
	public static function sort_modules( $a, $b ) {
4675
		if ( $a['sort'] == $b['sort'] )
4676
			return 0;
4677
4678
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4679
	}
4680
4681
	function ajax_recheck_ssl() {
4682
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4683
		$result = Jetpack::permit_ssl( true );
4684
		wp_send_json( array(
4685
			'enabled' => $result,
4686
			'message' => get_transient( 'jetpack_https_test_message' )
4687
		) );
4688
	}
4689
4690
/* Client API */
4691
4692
	/**
4693
	 * Returns the requested Jetpack API URL
4694
	 *
4695
	 * @return string
4696
	 */
4697
	public static function api_url( $relative_url ) {
4698
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4699
	}
4700
4701
	/**
4702
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4703
	 */
4704
	public static function fix_url_for_bad_hosts( $url ) {
4705
		if ( 0 !== strpos( $url, 'https://' ) ) {
4706
			return $url;
4707
		}
4708
4709
		switch ( JETPACK_CLIENT__HTTPS ) {
4710
			case 'ALWAYS' :
4711
				return $url;
4712
			case 'NEVER' :
4713
				return set_url_scheme( $url, 'http' );
4714
			// default : case 'AUTO' :
4715
		}
4716
4717
		// we now return the unmodified SSL URL by default, as a security precaution
4718
		return $url;
4719
	}
4720
4721
	/**
4722
	 * Create a random secret for validating onboarding payload
4723
	 *
4724
	 * @return string Secret token
4725
	 */
4726
	public static function create_onboarding_token() {
4727
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4728
			$token = wp_generate_password( 32, false );
4729
			Jetpack_Options::update_option( 'onboarding', $token );
4730
		}
4731
4732
		return $token;
4733
	}
4734
4735
	/**
4736
	 * Remove the onboarding token
4737
	 *
4738
	 * @return bool True on success, false on failure
4739
	 */
4740
	public static function invalidate_onboarding_token() {
4741
		return Jetpack_Options::delete_option( 'onboarding' );
4742
	}
4743
4744
	/**
4745
	 * Validate an onboarding token for a specific action
4746
	 *
4747
	 * @return boolean True if token/action pair is accepted, false if not
4748
	 */
4749
	public static function validate_onboarding_token_action( $token, $action ) {
4750
		// Compare tokens, bail if tokens do not match
4751
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4752
			return false;
4753
		}
4754
4755
		// List of valid actions we can take
4756
		$valid_actions = array(
4757
			'/jetpack/v4/settings',
4758
		);
4759
4760
		// Whitelist the action
4761
		if ( ! in_array( $action, $valid_actions ) ) {
4762
			return false;
4763
		}
4764
4765
		return true;
4766
	}
4767
4768
	/**
4769
	 * Checks to see if the URL is using SSL to connect with Jetpack
4770
	 *
4771
	 * @since 2.3.3
4772
	 * @return boolean
4773
	 */
4774
	public static function permit_ssl( $force_recheck = false ) {
4775
		// Do some fancy tests to see if ssl is being supported
4776
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4777
			$message = '';
4778
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4779
				$ssl = 0;
4780
			} else {
4781
				switch ( JETPACK_CLIENT__HTTPS ) {
4782
					case 'NEVER':
4783
						$ssl = 0;
4784
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4785
						break;
4786
					case 'ALWAYS':
4787
					case 'AUTO':
4788
					default:
4789
						$ssl = 1;
4790
						break;
4791
				}
4792
4793
				// If it's not 'NEVER', test to see
4794
				if ( $ssl ) {
4795
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4796
						$ssl = 0;
4797
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4798
					} else {
4799
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4800
						if ( is_wp_error( $response ) ) {
4801
							$ssl = 0;
4802
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4803
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4804
							$ssl = 0;
4805
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4806
						}
4807
					}
4808
				}
4809
			}
4810
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4811
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4812
		}
4813
4814
		return (bool) $ssl;
4815
	}
4816
4817
	/*
4818
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4819
	 */
4820
	public function alert_auto_ssl_fail() {
4821
		if ( ! current_user_can( 'manage_options' ) )
4822
			return;
4823
4824
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4825
		?>
4826
4827
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4828
			<div class="jp-banner__content">
4829
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4830
				<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>
4831
				<p>
4832
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4833
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4834
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4835
				</p>
4836
				<p>
4837
					<?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' ),
4838
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4839
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4840
				</p>
4841
			</div>
4842
		</div>
4843
		<style>
4844
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4845
		</style>
4846
		<script type="text/javascript">
4847
			jQuery( document ).ready( function( $ ) {
4848
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4849
					var $this = $( this );
4850
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4851
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4852
					e.preventDefault();
4853
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4854
					$.post( ajaxurl, data )
4855
					  .done( function( response ) {
4856
					  	if ( response.enabled ) {
4857
					  		$( '#jetpack-ssl-warning' ).hide();
4858
					  	} else {
4859
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4860
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4861
					  	}
4862
					  }.bind( $this ) );
4863
				} );
4864
			} );
4865
		</script>
4866
4867
		<?php
4868
	}
4869
4870
	/**
4871
	 * Returns the Jetpack XML-RPC API
4872
	 *
4873
	 * @return string
4874
	 */
4875
	public static function xmlrpc_api_url() {
4876
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4877
		return untrailingslashit( $base ) . '/xmlrpc.php';
4878
	}
4879
4880
	public static function connection() {
4881
		return self::init()->connection_manager;
4882
	}
4883
4884
	/**
4885
	 * Creates two secret tokens and the end of life timestamp for them.
4886
	 *
4887
	 * Note these tokens are unique per call, NOT static per site for connecting.
4888
	 *
4889
	 * @since 2.6
4890
	 * @return array
4891
	 */
4892
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4893
		if ( false === $user_id ) {
4894
			$user_id = get_current_user_id();
4895
		}
4896
4897
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4898
	}
4899
4900
	public static function get_secrets( $action, $user_id ) {
4901
		$secrets = self::connection()->get_secrets( $action, $user_id );
4902
4903
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4904
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4905
		}
4906
4907
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4908
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4909
		}
4910
4911
		return $secrets;
4912
	}
4913
4914
	/**
4915
	 * @deprecated 7.5 Use Connection_Manager instead.
4916
	 *
4917
	 * @param $action
4918
	 * @param $user_id
4919
	 */
4920
	public static function delete_secrets( $action, $user_id ) {
4921
		return self::connection()->delete_secrets( $action, $user_id );
4922
	}
4923
4924
	/**
4925
	 * Builds the timeout limit for queries talking with the wpcom servers.
4926
	 *
4927
	 * Based on local php max_execution_time in php.ini
4928
	 *
4929
	 * @since 2.6
4930
	 * @return int
4931
	 * @deprecated
4932
	 **/
4933
	public function get_remote_query_timeout_limit() {
4934
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4935
		return Jetpack::get_max_execution_time();
4936
	}
4937
4938
	/**
4939
	 * Builds the timeout limit for queries talking with the wpcom servers.
4940
	 *
4941
	 * Based on local php max_execution_time in php.ini
4942
	 *
4943
	 * @since 5.4
4944
	 * @return int
4945
	 **/
4946
	public static function get_max_execution_time() {
4947
		$timeout = (int) ini_get( 'max_execution_time' );
4948
4949
		// Ensure exec time set in php.ini
4950
		if ( ! $timeout ) {
4951
			$timeout = 30;
4952
		}
4953
		return $timeout;
4954
	}
4955
4956
	/**
4957
	 * Sets a minimum request timeout, and returns the current timeout
4958
	 *
4959
	 * @since 5.4
4960
	 **/
4961
	public static function set_min_time_limit( $min_timeout ) {
4962
		$timeout = self::get_max_execution_time();
4963
		if ( $timeout < $min_timeout ) {
4964
			$timeout = $min_timeout;
4965
			set_time_limit( $timeout );
4966
		}
4967
		return $timeout;
4968
	}
4969
4970
4971
	/**
4972
	 * Takes the response from the Jetpack register new site endpoint and
4973
	 * verifies it worked properly.
4974
	 *
4975
	 * @since 2.6
4976
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4977
	 **/
4978
	public function validate_remote_register_response( $response ) {
4979
	  if ( is_wp_error( $response ) ) {
4980
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4981
		}
4982
4983
		$code   = wp_remote_retrieve_response_code( $response );
4984
		$entity = wp_remote_retrieve_body( $response );
4985
		if ( $entity )
4986
			$registration_response = json_decode( $entity );
4987
		else
4988
			$registration_response = false;
4989
4990
		$code_type = intval( $code / 100 );
4991
		if ( 5 == $code_type ) {
4992
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4993
		} elseif ( 408 == $code ) {
4994
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4995
		} elseif ( ! empty( $registration_response->error ) ) {
4996
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4997
				$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' );
4998
			} else {
4999
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5000
			}
5001
5002
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5003
		} elseif ( 200 != $code ) {
5004
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5005
		}
5006
5007
		// Jetpack ID error block
5008
		if ( empty( $registration_response->jetpack_id ) ) {
5009
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5010
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5011
			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 );
5012
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5013
			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 );
5014
		}
5015
5016
	    return $registration_response;
5017
	}
5018
	/**
5019
	 * @return bool|WP_Error
5020
	 */
5021
	public static function register() {
5022
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5023
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5024
		$secrets = Jetpack::generate_secrets( 'register' );
5025
5026 View Code Duplication
		if (
5027
			empty( $secrets['secret_1'] ) ||
5028
			empty( $secrets['secret_2'] ) ||
5029
			empty( $secrets['exp'] )
5030
		) {
5031
			return new Jetpack_Error( 'missing_secrets' );
5032
		}
5033
5034
		// better to try (and fail) to set a higher timeout than this system
5035
		// supports than to have register fail for more users than it should
5036
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5037
5038
		$gmt_offset = get_option( 'gmt_offset' );
5039
		if ( ! $gmt_offset ) {
5040
			$gmt_offset = 0;
5041
		}
5042
5043
		$stats_options = get_option( 'stats_options' );
5044
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5045
5046
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5047
5048
		$args = array(
5049
			'method'  => 'POST',
5050
			'body'    => array(
5051
				'siteurl'         => site_url(),
5052
				'home'            => home_url(),
5053
				'gmt_offset'      => $gmt_offset,
5054
				'timezone_string' => (string) get_option( 'timezone_string' ),
5055
				'site_name'       => (string) get_option( 'blogname' ),
5056
				'secret_1'        => $secrets['secret_1'],
5057
				'secret_2'        => $secrets['secret_2'],
5058
				'site_lang'       => get_locale(),
5059
				'timeout'         => $timeout,
5060
				'stats_id'        => $stats_id,
5061
				'state'           => get_current_user_id(),
5062
				'_ui'             => $tracks_identity['_ui'],
5063
				'_ut'             => $tracks_identity['_ut'],
5064
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5065
				'jetpack_version' => JETPACK__VERSION
5066
			),
5067
			'headers' => array(
5068
				'Accept' => 'application/json',
5069
			),
5070
			'timeout' => $timeout,
5071
		);
5072
5073
		self::apply_activation_source_to_args( $args['body'] );
5074
5075
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5076
5077
		// Make sure the response is valid and does not contain any Jetpack errors
5078
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5079
		if ( is_wp_error( $registration_details ) ) {
5080
			return $registration_details;
5081
		} elseif ( ! $registration_details ) {
5082
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5083
		}
5084
5085 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5086
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5087
		}
5088
5089
		if ( isset( $registration_details->jetpack_public ) ) {
5090
			$jetpack_public = (int) $registration_details->jetpack_public;
5091
		} else {
5092
			$jetpack_public = false;
5093
		}
5094
5095
		Jetpack_Options::update_options(
5096
			array(
5097
				'id'         => (int)    $registration_details->jetpack_id,
5098
				'blog_token' => (string) $registration_details->jetpack_secret,
5099
				'public'     => $jetpack_public,
5100
			)
5101
		);
5102
5103
		/**
5104
		 * Fires when a site is registered on WordPress.com.
5105
		 *
5106
		 * @since 3.7.0
5107
		 *
5108
		 * @param int $json->jetpack_id Jetpack Blog ID.
5109
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5110
		 * @param int|bool $jetpack_public Is the site public.
5111
		 */
5112
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5113
5114
		// Initialize Jump Start for the first and only time.
5115
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5116
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5117
5118
			$jetpack = Jetpack::init();
5119
5120
			$jetpack->stat( 'jumpstart', 'unique-views' );
5121
			$jetpack->do_stats( 'server_side' );
5122
		};
5123
5124
		return true;
5125
	}
5126
5127
	/**
5128
	 * If the db version is showing something other that what we've got now, bump it to current.
5129
	 *
5130
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5131
	 */
5132
	public static function maybe_set_version_option() {
5133
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5134
		if ( JETPACK__VERSION != $version ) {
5135
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5136
5137
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5138
				/** This action is documented in class.jetpack.php */
5139
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5140
			}
5141
5142
			return true;
5143
		}
5144
		return false;
5145
	}
5146
5147
/* Client Server API */
5148
5149
	/**
5150
	 * Loads the Jetpack XML-RPC client
5151
	 */
5152
	public static function load_xml_rpc_client() {
5153
		require_once ABSPATH . WPINC . '/class-IXR.php';
5154
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5155
	}
5156
5157
	/**
5158
	 * Resets the saved authentication state in between testing requests.
5159
	 */
5160
	public function reset_saved_auth_state() {
5161
		$this->xmlrpc_verification = null;
5162
		$this->rest_authentication_status = null;
5163
	}
5164
5165
	function verify_xml_rpc_signature() {
5166
		if ( $this->xmlrpc_verification ) {
5167
			return $this->xmlrpc_verification;
5168
		}
5169
5170
		// It's not for us
5171
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5172
			return false;
5173
		}
5174
5175
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5176
		if (
5177
			empty( $token_key )
5178
		||
5179
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5180
		) {
5181
			return false;
5182
		}
5183
5184
		if ( '0' === $user_id ) {
5185
			$token_type = 'blog';
5186
			$user_id = 0;
5187
		} else {
5188
			$token_type = 'user';
5189
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5190
				return false;
5191
			}
5192
			$user_id = (int) $user_id;
5193
5194
			$user = new WP_User( $user_id );
5195
			if ( ! $user || ! $user->exists() ) {
5196
				return false;
5197
			}
5198
		}
5199
5200
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
0 ignored issues
show
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
5201
		if ( ! $token ) {
5202
			return false;
5203
		}
5204
5205
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5206
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5207
			$post_data   = $_POST;
5208
			$file_hashes = array();
5209
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5210
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5211
					continue;
5212
				}
5213
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5214
				$file_hashes[$post_data_key] = $post_data_value;
5215
			}
5216
5217
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5218
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5219
				$post_data[$post_data_key] = $post_data_value;
5220
			}
5221
5222
			ksort( $post_data );
5223
5224
			$body = http_build_query( stripslashes_deep( $post_data ) );
5225
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5226
			$body = file_get_contents( 'php://input' );
5227
		} else {
5228
			$body = null;
5229
		}
5230
5231
		$signature = $jetpack_signature->sign_current_request(
5232
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5233
		);
5234
5235
		if ( ! $signature ) {
5236
			return false;
5237
		} else if ( is_wp_error( $signature ) ) {
5238
			return $signature;
5239
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5240
			return false;
5241
		}
5242
5243
		$timestamp = (int) $_GET['timestamp'];
5244
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5245
5246
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5247
			return false;
5248
		}
5249
5250
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5251
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5252
			if ( ! empty( $_GET['onboarding'] ) ) {
5253
				$jpo = $_GET;
5254
			} else {
5255
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5256
			}
5257
5258
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5259
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5260
5261
			if (
5262
				isset( $jpo_user ) && isset( $jpo_token ) &&
5263
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5264
				isset( $_GET['rest_route'] ) &&
5265
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5266
			) {
5267
				$jpUser = get_user_by( 'email', $jpo_user );
5268
				if ( is_a( $jpUser, 'WP_User' ) ) {
5269
					wp_set_current_user( $jpUser->ID );
5270
					$user_can = is_multisite()
5271
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5272
						: current_user_can( 'manage_options' );
5273
					if ( $user_can ) {
5274
						$token_type = 'user';
5275
						$token->external_user_id = $jpUser->ID;
5276
					}
5277
				}
5278
			}
5279
		}
5280
5281
		$this->xmlrpc_verification = array(
5282
			'type'      => $token_type,
5283
			'token_key' => $token_key,
5284
			'user_id'   => $token->external_user_id,
5285
		);
5286
5287
		return $this->xmlrpc_verification;
5288
	}
5289
5290
	/**
5291
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5292
	 */
5293
	function authenticate_jetpack( $user, $username, $password ) {
5294
		if ( is_a( $user, 'WP_User' ) ) {
5295
			return $user;
5296
		}
5297
5298
		$token_details = $this->verify_xml_rpc_signature();
5299
5300
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5301
			return $user;
5302
		}
5303
5304
		if ( 'user' !== $token_details['type'] ) {
5305
			return $user;
5306
		}
5307
5308
		if ( ! $token_details['user_id'] ) {
5309
			return $user;
5310
		}
5311
5312
		nocache_headers();
5313
5314
		return new WP_User( $token_details['user_id'] );
5315
	}
5316
5317
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5318
	// Uses the existing XMLRPC request signing implementation.
5319
	function wp_rest_authenticate( $user ) {
5320
		if ( ! empty( $user ) ) {
5321
			// Another authentication method is in effect.
5322
			return $user;
5323
		}
5324
5325
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5326
			// Nothing to do for this authentication method.
5327
			return null;
5328
		}
5329
5330
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5331
			// Nothing to do for this authentication method.
5332
			return null;
5333
		}
5334
5335
		// Ensure that we always have the request body available.  At this
5336
		// point, the WP REST API code to determine the request body has not
5337
		// run yet.  That code may try to read from 'php://input' later, but
5338
		// this can only be done once per request in PHP versions prior to 5.6.
5339
		// So we will go ahead and perform this read now if needed, and save
5340
		// the request body where both the Jetpack signature verification code
5341
		// and the WP REST API code can see it.
5342
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5343
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5344
		}
5345
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5346
5347
		// Only support specific request parameters that have been tested and
5348
		// are known to work with signature verification.  A different method
5349
		// can be passed to the WP REST API via the '?_method=' parameter if
5350
		// needed.
5351
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5352
			$this->rest_authentication_status = new WP_Error(
5353
				'rest_invalid_request',
5354
				__( 'This request method is not supported.', 'jetpack' ),
5355
				array( 'status' => 400 )
5356
			);
5357
			return null;
5358
		}
5359
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5360
			$this->rest_authentication_status = new WP_Error(
5361
				'rest_invalid_request',
5362
				__( 'This request method does not support body parameters.', 'jetpack' ),
5363
				array( 'status' => 400 )
5364
			);
5365
			return null;
5366
		}
5367
5368
		$verified = $this->verify_xml_rpc_signature();
5369
5370
		if ( is_wp_error( $verified ) ) {
5371
			$this->rest_authentication_status = $verified;
5372
			return null;
5373
		}
5374
5375
		if (
5376
			$verified &&
5377
			isset( $verified['type'] ) &&
5378
			'user' === $verified['type'] &&
5379
			! empty( $verified['user_id'] )
5380
		) {
5381
			// Authentication successful.
5382
			$this->rest_authentication_status = true;
5383
			return $verified['user_id'];
5384
		}
5385
5386
		// Something else went wrong.  Probably a signature error.
5387
		$this->rest_authentication_status = new WP_Error(
5388
			'rest_invalid_signature',
5389
			__( 'The request is not signed correctly.', 'jetpack' ),
5390
			array( 'status' => 400 )
5391
		);
5392
		return null;
5393
	}
5394
5395
	/**
5396
	 * Report authentication status to the WP REST API.
5397
	 *
5398
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5399
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5400
	 */
5401
	public function wp_rest_authentication_errors( $value ) {
5402
		if ( $value !== null ) {
5403
			return $value;
5404
		}
5405
		return $this->rest_authentication_status;
5406
	}
5407
5408
	function add_nonce( $timestamp, $nonce ) {
5409
		global $wpdb;
5410
		static $nonces_used_this_request = array();
5411
5412
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5413
			return $nonces_used_this_request["$timestamp:$nonce"];
5414
		}
5415
5416
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5417
		$timestamp = (int) $timestamp;
5418
		$nonce     = esc_sql( $nonce );
5419
5420
		// Raw query so we can avoid races: add_option will also update
5421
		$show_errors = $wpdb->show_errors( false );
5422
5423
		$old_nonce = $wpdb->get_row(
5424
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5425
		);
5426
5427
		if ( is_null( $old_nonce ) ) {
5428
			$return = $wpdb->query(
5429
				$wpdb->prepare(
5430
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5431
					"jetpack_nonce_{$timestamp}_{$nonce}",
5432
					time(),
5433
					'no'
5434
				)
5435
			);
5436
		} else {
5437
			$return = false;
5438
		}
5439
5440
		$wpdb->show_errors( $show_errors );
5441
5442
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5443
5444
		return $return;
5445
	}
5446
5447
	/**
5448
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5449
	 * Capture it here so we can verify the signature later.
5450
	 */
5451
	function xmlrpc_methods( $methods ) {
5452
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5453
		return $methods;
5454
	}
5455
5456
	function public_xmlrpc_methods( $methods ) {
5457
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5458
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5459
		}
5460
		return $methods;
5461
	}
5462
5463
	function jetpack_getOptions( $args ) {
5464
		global $wp_xmlrpc_server;
5465
5466
		$wp_xmlrpc_server->escape( $args );
5467
5468
		$username	= $args[1];
5469
		$password	= $args[2];
5470
5471
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5472
			return $wp_xmlrpc_server->error;
5473
		}
5474
5475
		$options = array();
5476
		$user_data = $this->get_connected_user_data();
5477
		if ( is_array( $user_data ) ) {
5478
			$options['jetpack_user_id'] = array(
5479
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5480
				'readonly'      => true,
5481
				'value'         => $user_data['ID'],
5482
			);
5483
			$options['jetpack_user_login'] = array(
5484
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5485
				'readonly'      => true,
5486
				'value'         => $user_data['login'],
5487
			);
5488
			$options['jetpack_user_email'] = array(
5489
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5490
				'readonly'      => true,
5491
				'value'         => $user_data['email'],
5492
			);
5493
			$options['jetpack_user_site_count'] = array(
5494
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5495
				'readonly'      => true,
5496
				'value'         => $user_data['site_count'],
5497
			);
5498
		}
5499
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5500
		$args = stripslashes_deep( $args );
5501
		return $wp_xmlrpc_server->wp_getOptions( $args );
5502
	}
5503
5504
	function xmlrpc_options( $options ) {
5505
		$jetpack_client_id = false;
5506
		if ( self::is_active() ) {
5507
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5508
		}
5509
		$options['jetpack_version'] = array(
5510
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5511
				'readonly'      => true,
5512
				'value'         => JETPACK__VERSION,
5513
		);
5514
5515
		$options['jetpack_client_id'] = array(
5516
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5517
				'readonly'      => true,
5518
				'value'         => $jetpack_client_id,
5519
		);
5520
		return $options;
5521
	}
5522
5523
	public static function clean_nonces( $all = false ) {
5524
		global $wpdb;
5525
5526
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5527
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5528
5529
		if ( true !== $all ) {
5530
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5531
			$sql_args[] = time() - 3600;
5532
		}
5533
5534
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5535
5536
		$sql = $wpdb->prepare( $sql, $sql_args );
5537
5538
		for ( $i = 0; $i < 1000; $i++ ) {
5539
			if ( ! $wpdb->query( $sql ) ) {
5540
				break;
5541
			}
5542
		}
5543
	}
5544
5545
	/**
5546
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5547
	 * SET: state( $key, $value );
5548
	 * GET: $value = state( $key );
5549
	 *
5550
	 * @param string $key
5551
	 * @param string $value
5552
	 * @param bool $restate private
5553
	 */
5554
	public static function state( $key = null, $value = null, $restate = false ) {
5555
		static $state = array();
5556
		static $path, $domain;
5557
		if ( ! isset( $path ) ) {
5558
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5559
			$admin_url = Jetpack::admin_url();
5560
			$bits      = wp_parse_url( $admin_url );
5561
5562
			if ( is_array( $bits ) ) {
5563
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5564
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5565
			} else {
5566
				$path = $domain = null;
5567
			}
5568
		}
5569
5570
		// Extract state from cookies and delete cookies
5571
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5572
			$yum = $_COOKIE[ 'jetpackState' ];
5573
			unset( $_COOKIE[ 'jetpackState' ] );
5574
			foreach ( $yum as $k => $v ) {
5575
				if ( strlen( $v ) )
5576
					$state[ $k ] = $v;
5577
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5578
			}
5579
		}
5580
5581
		if ( $restate ) {
5582
			foreach ( $state as $k => $v ) {
5583
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5584
			}
5585
			return;
5586
		}
5587
5588
		// Get a state variable
5589
		if ( isset( $key ) && ! isset( $value ) ) {
5590
			if ( array_key_exists( $key, $state ) )
5591
				return $state[ $key ];
5592
			return null;
5593
		}
5594
5595
		// Set a state variable
5596
		if ( isset ( $key ) && isset( $value ) ) {
5597
			if( is_array( $value ) && isset( $value[0] ) ) {
5598
				$value = $value[0];
5599
			}
5600
			$state[ $key ] = $value;
5601
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5602
		}
5603
	}
5604
5605
	public static function restate() {
5606
		Jetpack::state( null, null, true );
5607
	}
5608
5609
	public static function check_privacy( $file ) {
5610
		static $is_site_publicly_accessible = null;
5611
5612
		if ( is_null( $is_site_publicly_accessible ) ) {
5613
			$is_site_publicly_accessible = false;
5614
5615
			Jetpack::load_xml_rpc_client();
5616
			$rpc = new Jetpack_IXR_Client();
5617
5618
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5619
			if ( $success ) {
5620
				$response = $rpc->getResponse();
5621
				if ( $response ) {
5622
					$is_site_publicly_accessible = true;
5623
				}
5624
			}
5625
5626
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5627
		}
5628
5629
		if ( $is_site_publicly_accessible ) {
5630
			return;
5631
		}
5632
5633
		$module_slug = self::get_module_slug( $file );
5634
5635
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5636
		if ( ! $privacy_checks ) {
5637
			$privacy_checks = $module_slug;
5638
		} else {
5639
			$privacy_checks .= ",$module_slug";
5640
		}
5641
5642
		Jetpack::state( 'privacy_checks', $privacy_checks );
5643
	}
5644
5645
	/**
5646
	 * Helper method for multicall XMLRPC.
5647
	 */
5648
	public static function xmlrpc_async_call() {
5649
		global $blog_id;
5650
		static $clients = array();
5651
5652
		$client_blog_id = is_multisite() ? $blog_id : 0;
5653
5654
		if ( ! isset( $clients[$client_blog_id] ) ) {
5655
			Jetpack::load_xml_rpc_client();
5656
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5657
			if ( function_exists( 'ignore_user_abort' ) ) {
5658
				ignore_user_abort( true );
5659
			}
5660
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5661
		}
5662
5663
		$args = func_get_args();
5664
5665
		if ( ! empty( $args[0] ) ) {
5666
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5667
		} elseif ( is_multisite() ) {
5668
			foreach ( $clients as $client_blog_id => $client ) {
5669
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5670
					continue;
5671
				}
5672
5673
				$switch_success = switch_to_blog( $client_blog_id, true );
5674
				if ( ! $switch_success ) {
5675
					continue;
5676
				}
5677
5678
				flush();
5679
				$client->query();
5680
5681
				restore_current_blog();
5682
			}
5683
		} else {
5684
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5685
				flush();
5686
				$clients[0]->query();
5687
			}
5688
		}
5689
	}
5690
5691
	public static function staticize_subdomain( $url ) {
5692
5693
		// Extract hostname from URL
5694
		$host = parse_url( $url, PHP_URL_HOST );
5695
5696
		// Explode hostname on '.'
5697
		$exploded_host = explode( '.', $host );
5698
5699
		// Retrieve the name and TLD
5700
		if ( count( $exploded_host ) > 1 ) {
5701
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5702
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5703
			// Rebuild domain excluding subdomains
5704
			$domain = $name . '.' . $tld;
5705
		} else {
5706
			$domain = $host;
5707
		}
5708
		// Array of Automattic domains
5709
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5710
5711
		// Return $url if not an Automattic domain
5712
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5713
			return $url;
5714
		}
5715
5716
		if ( is_ssl() ) {
5717
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5718
		}
5719
5720
		srand( crc32( basename( $url ) ) );
5721
		$static_counter = rand( 0, 2 );
5722
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5723
5724
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5725
	}
5726
5727
/* JSON API Authorization */
5728
5729
	/**
5730
	 * Handles the login action for Authorizing the JSON API
5731
	 */
5732
	function login_form_json_api_authorization() {
5733
		$this->verify_json_api_authorization_request();
5734
5735
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5736
5737
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5738
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5739
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5740
	}
5741
5742
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5743
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5744
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5745
			return $url;
5746
		}
5747
5748
		$parsed_url = parse_url( $url );
5749
		$url = strtok( $url, '?' );
5750
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5751
		if ( ! empty( $parsed_url['query'] ) )
5752
			$url .= "&{$parsed_url['query']}";
5753
5754
		return $url;
5755
	}
5756
5757
	// Make sure the POSTed request is handled by the same action
5758
	function preserve_action_in_login_form_for_json_api_authorization() {
5759
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5760
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5761
	}
5762
5763
	// If someone logs in to approve API access, store the Access Code in usermeta
5764
	function store_json_api_authorization_token( $user_login, $user ) {
5765
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5766
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5767
		$token = wp_generate_password( 32, false );
5768
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5769
	}
5770
5771
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5772
	function allow_wpcom_public_api_domain( $domains ) {
5773
		$domains[] = 'public-api.wordpress.com';
5774
		return $domains;
5775
	}
5776
5777
	static function is_redirect_encoded( $redirect_url ) {
5778
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5779
	}
5780
5781
	// Add all wordpress.com environments to the safe redirect whitelist
5782
	function allow_wpcom_environments( $domains ) {
5783
		$domains[] = 'wordpress.com';
5784
		$domains[] = 'wpcalypso.wordpress.com';
5785
		$domains[] = 'horizon.wordpress.com';
5786
		$domains[] = 'calypso.localhost';
5787
		return $domains;
5788
	}
5789
5790
	// Add the Access Code details to the public-api.wordpress.com redirect
5791
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5792
		return add_query_arg(
5793
			urlencode_deep(
5794
				array(
5795
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5796
					'jetpack-user-id' => (int) $user->ID,
5797
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5798
				)
5799
			),
5800
			$redirect_to
5801
		);
5802
	}
5803
5804
5805
	/**
5806
	 * Verifies the request by checking the signature
5807
	 *
5808
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5809
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5810
	 *
5811
	 * @param null|array $environment
5812
	 */
5813
	function verify_json_api_authorization_request( $environment = null ) {
5814
		$environment = is_null( $environment )
5815
			? $_REQUEST
5816
			: $environment;
5817
5818
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5819
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5820
		if ( ! $token || empty( $token->secret ) ) {
5821
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5822
		}
5823
5824
		$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' );
5825
5826
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5827
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5828
			JetpackTracking::record_user_event( 'error_double_encode' );
5829
5830
			$die_error = sprintf(
5831
				/* translators: %s is a URL */
5832
				__( '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' ),
5833
				'https://jetpack.com/support/double-encoding/'
5834
			);
5835
		}
5836
5837
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5838
5839
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5840
			$signature = $jetpack_signature->sign_request(
5841
				$environment['token'],
5842
				$environment['timestamp'],
5843
				$environment['nonce'],
5844
				'',
5845
				'GET',
5846
				$environment['jetpack_json_api_original_query'],
5847
				null,
5848
				true
5849
			);
5850
		} else {
5851
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5852
		}
5853
5854
		if ( ! $signature ) {
5855
			wp_die( $die_error );
5856
		} else if ( is_wp_error( $signature ) ) {
5857
			wp_die( $die_error );
5858
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5859
			if ( is_ssl() ) {
5860
				// 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
5861
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5862
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5863
					wp_die( $die_error );
5864
				}
5865
			} else {
5866
				wp_die( $die_error );
5867
			}
5868
		}
5869
5870
		$timestamp = (int) $environment['timestamp'];
5871
		$nonce     = stripslashes( (string) $environment['nonce'] );
5872
5873
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5874
			// De-nonce the nonce, at least for 5 minutes.
5875
			// 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)
5876
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5877
			if ( $old_nonce_time < time() - 300 ) {
5878
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5879
			}
5880
		}
5881
5882
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5883
		$data_filters = array(
5884
			'state'        => 'opaque',
5885
			'client_id'    => 'int',
5886
			'client_title' => 'string',
5887
			'client_image' => 'url',
5888
		);
5889
5890
		foreach ( $data_filters as $key => $sanitation ) {
5891
			if ( ! isset( $data->$key ) ) {
5892
				wp_die( $die_error );
5893
			}
5894
5895
			switch ( $sanitation ) {
5896
			case 'int' :
5897
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5898
				break;
5899
			case 'opaque' :
5900
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5901
				break;
5902
			case 'string' :
5903
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5904
				break;
5905
			case 'url' :
5906
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5907
				break;
5908
			}
5909
		}
5910
5911
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5912
			wp_die( $die_error );
5913
		}
5914
	}
5915
5916
	function login_message_json_api_authorization( $message ) {
5917
		return '<p class="message">' . sprintf(
5918
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5919
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5920
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5921
	}
5922
5923
	/**
5924
	 * Get $content_width, but with a <s>twist</s> filter.
5925
	 */
5926
	public static function get_content_width() {
5927
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5928
			? $GLOBALS['content_width']
5929
			: false;
5930
		/**
5931
		 * Filter the Content Width value.
5932
		 *
5933
		 * @since 2.2.3
5934
		 *
5935
		 * @param string $content_width Content Width value.
5936
		 */
5937
		return apply_filters( 'jetpack_content_width', $content_width );
5938
	}
5939
5940
	/**
5941
	 * Pings the WordPress.com Mirror Site for the specified options.
5942
	 *
5943
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5944
	 *
5945
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5946
	 */
5947
	public function get_cloud_site_options( $option_names ) {
5948
		$option_names = array_filter( (array) $option_names, 'is_string' );
5949
5950
		Jetpack::load_xml_rpc_client();
5951
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5952
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5953
		if ( $xml->isError() ) {
5954
			return array(
5955
				'error_code' => $xml->getErrorCode(),
5956
				'error_msg'  => $xml->getErrorMessage(),
5957
			);
5958
		}
5959
		$cloud_site_options = $xml->getResponse();
5960
5961
		return $cloud_site_options;
5962
	}
5963
5964
	/**
5965
	 * Checks if the site is currently in an identity crisis.
5966
	 *
5967
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5968
	 */
5969
	public static function check_identity_crisis() {
5970
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5971
			return false;
5972
		}
5973
5974
		return Jetpack_Options::get_option( 'sync_error_idc' );
5975
	}
5976
5977
	/**
5978
	 * Checks whether the home and siteurl specifically are whitelisted
5979
	 * Written so that we don't have re-check $key and $value params every time
5980
	 * we want to check if this site is whitelisted, for example in footer.php
5981
	 *
5982
	 * @since  3.8.0
5983
	 * @return bool True = already whitelisted False = not whitelisted
5984
	 */
5985
	public static function is_staging_site() {
5986
		$is_staging = false;
5987
5988
		$known_staging = array(
5989
			'urls' => array(
5990
				'#\.staging\.wpengine\.com$#i', // WP Engine
5991
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5992
				),
5993
			'constants' => array(
5994
				'IS_WPE_SNAPSHOT',      // WP Engine
5995
				'KINSTA_DEV_ENV',       // Kinsta.com
5996
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5997
				'JETPACK_STAGING_MODE', // Generic
5998
				)
5999
			);
6000
		/**
6001
		 * Filters the flags of known staging sites.
6002
		 *
6003
		 * @since 3.9.0
6004
		 *
6005
		 * @param array $known_staging {
6006
		 *     An array of arrays that each are used to check if the current site is staging.
6007
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6008
		 *     @type array $constants PHP constants of known staging/developement environments.
6009
		 *  }
6010
		 */
6011
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6012
6013
		if ( isset( $known_staging['urls'] ) ) {
6014
			foreach ( $known_staging['urls'] as $url ){
6015
				if ( preg_match( $url, site_url() ) ) {
6016
					$is_staging = true;
6017
					break;
6018
				}
6019
			}
6020
		}
6021
6022
		if ( isset( $known_staging['constants'] ) ) {
6023
			foreach ( $known_staging['constants'] as $constant ) {
6024
				if ( defined( $constant ) && constant( $constant ) ) {
6025
					$is_staging = true;
6026
				}
6027
			}
6028
		}
6029
6030
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6031
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6032
			$is_staging = true;
6033
		}
6034
6035
		/**
6036
		 * Filters is_staging_site check.
6037
		 *
6038
		 * @since 3.9.0
6039
		 *
6040
		 * @param bool $is_staging If the current site is a staging site.
6041
		 */
6042
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6043
	}
6044
6045
	/**
6046
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6047
	 *
6048
	 * @since 4.4.0
6049
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6050
	 *
6051
	 * @return bool
6052
	 */
6053
	public static function validate_sync_error_idc_option() {
6054
		$is_valid = false;
6055
6056
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6057
		if ( false === $idc_allowed ) {
6058
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6059
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6060
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6061
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6062
				$transient_duration = HOUR_IN_SECONDS;
6063
			} else {
6064
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6065
				$idc_allowed = '1';
6066
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6067
			}
6068
6069
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6070
		}
6071
6072
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6073
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6074
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6075
			$local_options = self::get_sync_error_idc_option();
6076
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6077
				$is_valid = true;
6078
			}
6079
		}
6080
6081
		/**
6082
		 * Filters whether the sync_error_idc option is valid.
6083
		 *
6084
		 * @since 4.4.0
6085
		 *
6086
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6087
		 */
6088
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6089
6090
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6091
			// Since the option exists, and did not validate, delete it
6092
			Jetpack_Options::delete_option( 'sync_error_idc' );
6093
		}
6094
6095
		return $is_valid;
6096
	}
6097
6098
	/**
6099
	 * Normalizes a url by doing three things:
6100
	 *  - Strips protocol
6101
	 *  - Strips www
6102
	 *  - Adds a trailing slash
6103
	 *
6104
	 * @since 4.4.0
6105
	 * @param string $url
6106
	 * @return WP_Error|string
6107
	 */
6108
	public static function normalize_url_protocol_agnostic( $url ) {
6109
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6110
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6111
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6112
		}
6113
6114
		// Strip www and protocols
6115
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6116
		return $url;
6117
	}
6118
6119
	/**
6120
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6121
	 *
6122
	 * @since 4.4.0
6123
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6124
	 *
6125
	 * @param array $response
6126
	 * @return array Array of the local urls, wpcom urls, and error code
6127
	 */
6128
	public static function get_sync_error_idc_option( $response = array() ) {
6129
		// Since the local options will hit the database directly, store the values
6130
		// in a transient to allow for autoloading and caching on subsequent views.
6131
		$local_options = get_transient( 'jetpack_idc_local' );
6132
		if ( false === $local_options ) {
6133
			$local_options = array(
6134
				'home'    => Jetpack_Sync_Functions::home_url(),
6135
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6136
			);
6137
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6138
		}
6139
6140
		$options = array_merge( $local_options, $response );
6141
6142
		$returned_values = array();
6143
		foreach( $options as $key => $option ) {
6144
			if ( 'error_code' === $key ) {
6145
				$returned_values[ $key ] = $option;
6146
				continue;
6147
			}
6148
6149
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6150
				continue;
6151
			}
6152
6153
			$returned_values[ $key ] = $normalized_url;
6154
		}
6155
6156
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6157
6158
		return $returned_values;
6159
	}
6160
6161
	/**
6162
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6163
	 * If set to true, the site will be put into staging mode.
6164
	 *
6165
	 * @since 4.3.2
6166
	 * @return bool
6167
	 */
6168
	public static function sync_idc_optin() {
6169
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6170
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6171
		} else {
6172
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6173
		}
6174
6175
		/**
6176
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6177
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6178
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6179
		 *
6180
		 * @since 4.3.2
6181
		 *
6182
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6183
		 */
6184
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6185
	}
6186
6187
	/**
6188
	 * Maybe Use a .min.css stylesheet, maybe not.
6189
	 *
6190
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6191
	 */
6192
	public static function maybe_min_asset( $url, $path, $plugin ) {
6193
		// Short out on things trying to find actual paths.
6194
		if ( ! $path || empty( $plugin ) ) {
6195
			return $url;
6196
		}
6197
6198
		$path = ltrim( $path, '/' );
6199
6200
		// Strip out the abspath.
6201
		$base = dirname( plugin_basename( $plugin ) );
6202
6203
		// Short out on non-Jetpack assets.
6204
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6205
			return $url;
6206
		}
6207
6208
		// File name parsing.
6209
		$file              = "{$base}/{$path}";
6210
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6211
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6212
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6213
		$extension         = array_shift( $file_name_parts_r );
6214
6215
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6216
			// Already pointing at the minified version.
6217
			if ( 'min' === $file_name_parts_r[0] ) {
6218
				return $url;
6219
			}
6220
6221
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6222
			if ( file_exists( $min_full_path ) ) {
6223
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6224
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6225
				if ( 'css' === $extension ) {
6226
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6227
					self::$min_assets[ $key ] = $path;
6228
				}
6229
			}
6230
		}
6231
6232
		return $url;
6233
	}
6234
6235
	/**
6236
	 * If the asset is minified, let's flag .min as the suffix.
6237
	 *
6238
	 * Attached to `style_loader_src` filter.
6239
	 *
6240
	 * @param string $tag The tag that would link to the external asset.
6241
	 * @param string $handle The registered handle of the script in question.
6242
	 * @param string $href The url of the asset in question.
6243
	 */
6244
	public static function set_suffix_on_min( $src, $handle ) {
6245
		if ( false === strpos( $src, '.min.css' ) ) {
6246
			return $src;
6247
		}
6248
6249
		if ( ! empty( self::$min_assets ) ) {
6250
			foreach ( self::$min_assets as $file => $path ) {
6251
				if ( false !== strpos( $src, $file ) ) {
6252
					wp_style_add_data( $handle, 'suffix', '.min' );
6253
					return $src;
6254
				}
6255
			}
6256
		}
6257
6258
		return $src;
6259
	}
6260
6261
	/**
6262
	 * Maybe inlines a stylesheet.
6263
	 *
6264
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6265
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6266
	 *
6267
	 * Attached to `style_loader_tag` filter.
6268
	 *
6269
	 * @param string $tag The tag that would link to the external asset.
6270
	 * @param string $handle The registered handle of the script in question.
6271
	 *
6272
	 * @return string
6273
	 */
6274
	public static function maybe_inline_style( $tag, $handle ) {
6275
		global $wp_styles;
6276
		$item = $wp_styles->registered[ $handle ];
6277
6278
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6279
			return $tag;
6280
		}
6281
6282
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6283
			$href = $matches[1];
6284
			// Strip off query string
6285
			if ( $pos = strpos( $href, '?' ) ) {
6286
				$href = substr( $href, 0, $pos );
6287
			}
6288
			// Strip off fragment
6289
			if ( $pos = strpos( $href, '#' ) ) {
6290
				$href = substr( $href, 0, $pos );
6291
			}
6292
		} else {
6293
			return $tag;
6294
		}
6295
6296
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6297
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6298
			return $tag;
6299
		}
6300
6301
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6302
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6303
			// And this isn't the pass that actually deals with the RTL version...
6304
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6305
				// Short out, as the RTL version will deal with it in a moment.
6306
				return $tag;
6307
			}
6308
		}
6309
6310
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6311
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6312
		if ( $css ) {
6313
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6314
			if ( empty( $item->extra['after'] ) ) {
6315
				wp_add_inline_style( $handle, $css );
6316
			} else {
6317
				array_unshift( $item->extra['after'], $css );
6318
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6319
			}
6320
		}
6321
6322
		return $tag;
6323
	}
6324
6325
	/**
6326
	 * Loads a view file from the views
6327
	 *
6328
	 * Data passed in with the $data parameter will be available in the
6329
	 * template file as $data['value']
6330
	 *
6331
	 * @param string $template - Template file to load
6332
	 * @param array $data - Any data to pass along to the template
6333
	 * @return boolean - If template file was found
6334
	 **/
6335
	public function load_view( $template, $data = array() ) {
6336
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6337
6338
		if( file_exists( $views_dir . $template ) ) {
6339
			require_once( $views_dir . $template );
6340
			return true;
6341
		}
6342
6343
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6344
		return false;
6345
	}
6346
6347
	/**
6348
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6349
	 */
6350
	public function deprecated_hooks() {
6351
		global $wp_filter;
6352
6353
		/*
6354
		 * Format:
6355
		 * deprecated_filter_name => replacement_name
6356
		 *
6357
		 * If there is no replacement, use null for replacement_name
6358
		 */
6359
		$deprecated_list = array(
6360
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6361
			'wpl_sharing_2014_1'                                     => null,
6362
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6363
			'jetpack_identity_crisis_options_to_check'               => null,
6364
			'update_option_jetpack_single_user_site'                 => null,
6365
			'audio_player_default_colors'                            => null,
6366
			'add_option_jetpack_featured_images_enabled'             => null,
6367
			'add_option_jetpack_update_details'                      => null,
6368
			'add_option_jetpack_updates'                             => null,
6369
			'add_option_jetpack_network_name'                        => null,
6370
			'add_option_jetpack_network_allow_new_registrations'     => null,
6371
			'add_option_jetpack_network_add_new_users'               => null,
6372
			'add_option_jetpack_network_site_upload_space'           => null,
6373
			'add_option_jetpack_network_upload_file_types'           => null,
6374
			'add_option_jetpack_network_enable_administration_menus' => null,
6375
			'add_option_jetpack_is_multi_site'                       => null,
6376
			'add_option_jetpack_is_main_network'                     => null,
6377
			'add_option_jetpack_main_network_site'                   => null,
6378
			'jetpack_sync_all_registered_options'                    => null,
6379
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6380
			'jetpack_is_post_mailable'                               => null,
6381
			'jetpack_seo_site_host'                                  => null,
6382
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6383
			'jetpack_holiday_snow_option_name'                       => null,
6384
			'jetpack_holiday_chance_of_snow'                         => null,
6385
			'jetpack_holiday_snow_js_url'                            => null,
6386
			'jetpack_is_holiday_snow_season'                         => null,
6387
			'jetpack_holiday_snow_option_updated'                    => null,
6388
			'jetpack_holiday_snowing'                                => null,
6389
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6390
			'jetpack_cache_plans'                                    => null,
6391
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6392
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6393
			'jetpack_enable_site_verification'                       => null,
6394
			'can_display_jetpack_manage_notice'                      => null,
6395
			// Removed in Jetpack 7.3.0
6396
			'atd_load_scripts'                                       => null,
6397
			'atd_http_post_timeout'                                  => null,
6398
			'atd_http_post_error'                                    => null,
6399
			'atd_service_domain'                                     => null,
6400
		);
6401
6402
		// This is a silly loop depth. Better way?
6403
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6404
			if ( has_action( $hook ) ) {
6405
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6406
					foreach( $values AS $hooked ) {
6407
						if ( is_callable( $hooked['function'] ) ) {
6408
							$function_name = 'an anonymous function';
6409
						} else {
6410
							$function_name = $hooked['function'];
6411
						}
6412
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6413
					}
6414
				}
6415
			}
6416
		}
6417
	}
6418
6419
	/**
6420
	 * Converts any url in a stylesheet, to the correct absolute url.
6421
	 *
6422
	 * Considerations:
6423
	 *  - Normal, relative URLs     `feh.png`
6424
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6425
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6426
	 *  - Absolute URLs             `http://domain.com/feh.png`
6427
	 *  - Domain root relative URLs `/feh.png`
6428
	 *
6429
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6430
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6431
	 *
6432
	 * @return mixed|string
6433
	 */
6434
	public static function absolutize_css_urls( $css, $css_file_url ) {
6435
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6436
		$css_dir = dirname( $css_file_url );
6437
		$p       = parse_url( $css_dir );
6438
		$domain  = sprintf(
6439
					'%1$s//%2$s%3$s%4$s',
6440
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6441
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6442
					$p['host'],
6443
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6444
				);
6445
6446
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6447
			$find = $replace = array();
6448
			foreach ( $matches as $match ) {
6449
				$url = trim( $match['path'], "'\" \t" );
6450
6451
				// If this is a data url, we don't want to mess with it.
6452
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6453
					continue;
6454
				}
6455
6456
				// If this is an absolute or protocol-agnostic url,
6457
				// we don't want to mess with it.
6458
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6459
					continue;
6460
				}
6461
6462
				switch ( substr( $url, 0, 1 ) ) {
6463
					case '/':
6464
						$absolute = $domain . $url;
6465
						break;
6466
					default:
6467
						$absolute = $css_dir . '/' . $url;
6468
				}
6469
6470
				$find[]    = $match[0];
6471
				$replace[] = sprintf( 'url("%s")', $absolute );
6472
			}
6473
			$css = str_replace( $find, $replace, $css );
6474
		}
6475
6476
		return $css;
6477
	}
6478
6479
	/**
6480
	 * This methods removes all of the registered css files on the front end
6481
	 * from Jetpack in favor of using a single file. In effect "imploding"
6482
	 * all the files into one file.
6483
	 *
6484
	 * Pros:
6485
	 * - Uses only ONE css asset connection instead of 15
6486
	 * - Saves a minimum of 56k
6487
	 * - Reduces server load
6488
	 * - Reduces time to first painted byte
6489
	 *
6490
	 * Cons:
6491
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6492
	 *		should not cause any issues with themes.
6493
	 * - Plugins/themes dequeuing styles no longer do anything. See
6494
	 *		jetpack_implode_frontend_css filter for a workaround
6495
	 *
6496
	 * For some situations developers may wish to disable css imploding and
6497
	 * instead operate in legacy mode where each file loads seperately and
6498
	 * can be edited individually or dequeued. This can be accomplished with
6499
	 * the following line:
6500
	 *
6501
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6502
	 *
6503
	 * @since 3.2
6504
	 **/
6505
	public function implode_frontend_css( $travis_test = false ) {
6506
		$do_implode = true;
6507
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6508
			$do_implode = false;
6509
		}
6510
6511
		// Do not implode CSS when the page loads via the AMP plugin.
6512
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6513
			$do_implode = false;
6514
		}
6515
6516
		/**
6517
		 * Allow CSS to be concatenated into a single jetpack.css file.
6518
		 *
6519
		 * @since 3.2.0
6520
		 *
6521
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6522
		 */
6523
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6524
6525
		// Do not use the imploded file when default behavior was altered through the filter
6526
		if ( ! $do_implode ) {
6527
			return;
6528
		}
6529
6530
		// We do not want to use the imploded file in dev mode, or if not connected
6531
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6532
			if ( ! $travis_test ) {
6533
				return;
6534
			}
6535
		}
6536
6537
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6538
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6539
			return;
6540
		}
6541
6542
		/*
6543
		 * Now we assume Jetpack is connected and able to serve the single
6544
		 * file.
6545
		 *
6546
		 * In the future there will be a check here to serve the file locally
6547
		 * or potentially from the Jetpack CDN
6548
		 *
6549
		 * For now:
6550
		 * - Enqueue a single imploded css file
6551
		 * - Zero out the style_loader_tag for the bundled ones
6552
		 * - Be happy, drink scotch
6553
		 */
6554
6555
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6556
6557
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6558
6559
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6560
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6561
	}
6562
6563
	function concat_remove_style_loader_tag( $tag, $handle ) {
6564
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6565
			$tag = '';
6566
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6567
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6568
			}
6569
		}
6570
6571
		return $tag;
6572
	}
6573
6574
	/*
6575
	 * Check the heartbeat data
6576
	 *
6577
	 * Organizes the heartbeat data by severity.  For example, if the site
6578
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6579
	 *
6580
	 * Data will be added to "caution" array, if it either:
6581
	 *  - Out of date Jetpack version
6582
	 *  - Out of date WP version
6583
	 *  - Out of date PHP version
6584
	 *
6585
	 * $return array $filtered_data
6586
	 */
6587
	public static function jetpack_check_heartbeat_data() {
6588
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6589
6590
		$good    = array();
6591
		$caution = array();
6592
		$bad     = array();
6593
6594
		foreach ( $raw_data as $stat => $value ) {
6595
6596
			// Check jetpack version
6597
			if ( 'version' == $stat ) {
6598
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6599
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6600
					continue;
6601
				}
6602
			}
6603
6604
			// Check WP version
6605
			if ( 'wp-version' == $stat ) {
6606
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6607
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6608
					continue;
6609
				}
6610
			}
6611
6612
			// Check PHP version
6613
			if ( 'php-version' == $stat ) {
6614
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6615
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6616
					continue;
6617
				}
6618
			}
6619
6620
			// Check ID crisis
6621
			if ( 'identitycrisis' == $stat ) {
6622
				if ( 'yes' == $value ) {
6623
					$bad[ $stat ] = $value;
6624
					continue;
6625
				}
6626
			}
6627
6628
			// The rest are good :)
6629
			$good[ $stat ] = $value;
6630
		}
6631
6632
		$filtered_data = array(
6633
			'good'    => $good,
6634
			'caution' => $caution,
6635
			'bad'     => $bad
6636
		);
6637
6638
		return $filtered_data;
6639
	}
6640
6641
6642
	/*
6643
	 * This method is used to organize all options that can be reset
6644
	 * without disconnecting Jetpack.
6645
	 *
6646
	 * It is used in class.jetpack-cli.php to reset options
6647
	 *
6648
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6649
	 *
6650
	 * @return array of options to delete.
6651
	 */
6652
	public static function get_jetpack_options_for_reset() {
6653
		return Jetpack_Options::get_options_for_reset();
6654
	}
6655
6656
	/*
6657
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6658
	 * so we can bring them directly to their site in calypso.
6659
	 *
6660
	 * @param string | url
6661
	 * @return string | url without the guff
6662
	 */
6663
	public static function build_raw_urls( $url ) {
6664
		$strip_http = '/.*?:\/\//i';
6665
		$url = preg_replace( $strip_http, '', $url  );
6666
		$url = str_replace( '/', '::', $url );
6667
		return $url;
6668
	}
6669
6670
	/**
6671
	 * Stores and prints out domains to prefetch for page speed optimization.
6672
	 *
6673
	 * @param mixed $new_urls
6674
	 */
6675
	public static function dns_prefetch( $new_urls = null ) {
6676
		static $prefetch_urls = array();
6677
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6678
			echo "\r\n";
6679
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6680
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6681
			}
6682
		} elseif ( ! empty( $new_urls ) ) {
6683
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6684
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6685
			}
6686
			foreach ( (array) $new_urls as $this_new_url ) {
6687
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6688
			}
6689
			$prefetch_urls = array_unique( $prefetch_urls );
6690
		}
6691
	}
6692
6693
	public function wp_dashboard_setup() {
6694
		if ( self::is_active() ) {
6695
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6696
		}
6697
6698
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6699
			$jetpack_logo = new Jetpack_Logo();
6700
			$widget_title = sprintf(
6701
				wp_kses(
6702
					/* translators: Placeholder is a Jetpack logo. */
6703
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6704
					array( 'span' => array() )
6705
				),
6706
				$jetpack_logo->get_jp_emblem( true )
6707
			);
6708
6709
			wp_add_dashboard_widget(
6710
				'jetpack_summary_widget',
6711
				$widget_title,
6712
				array( __CLASS__, 'dashboard_widget' )
6713
			);
6714
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6715
6716
			// If we're inactive and not in development mode, sort our box to the top.
6717
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6718
				global $wp_meta_boxes;
6719
6720
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6721
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6722
6723
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6724
			}
6725
		}
6726
	}
6727
6728
	/**
6729
	 * @param mixed $result Value for the user's option
6730
	 * @return mixed
6731
	 */
6732
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6733
		if ( ! is_array( $sorted ) ) {
6734
			return $sorted;
6735
		}
6736
6737
		foreach ( $sorted as $box_context => $ids ) {
6738
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6739
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6740
				continue;
6741
			}
6742
6743
			$ids_array = explode( ',', $ids );
6744
			$key = array_search( 'dashboard_stats', $ids_array );
6745
6746
			if ( false !== $key ) {
6747
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6748
				$ids_array[ $key ] = 'jetpack_summary_widget';
6749
				$sorted[ $box_context ] = implode( ',', $ids_array );
6750
				// We've found it, stop searching, and just return.
6751
				break;
6752
			}
6753
		}
6754
6755
		return $sorted;
6756
	}
6757
6758
	public static function dashboard_widget() {
6759
		/**
6760
		 * Fires when the dashboard is loaded.
6761
		 *
6762
		 * @since 3.4.0
6763
		 */
6764
		do_action( 'jetpack_dashboard_widget' );
6765
	}
6766
6767
	public static function dashboard_widget_footer() {
6768
		?>
6769
		<footer>
6770
6771
		<div class="protect">
6772
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6773
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6774
				<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>
6775
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6776
				<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' ); ?>">
6777
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6778
				</a>
6779
			<?php else : ?>
6780
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6781
			<?php endif; ?>
6782
		</div>
6783
6784
		<div class="akismet">
6785
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6786
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6787
				<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>
6788
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6789
				<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">
6790
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6791
				</a>
6792
			<?php else : ?>
6793
				<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>
6794
			<?php endif; ?>
6795
		</div>
6796
6797
		</footer>
6798
		<?php
6799
	}
6800
6801
	/*
6802
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6803
	 */
6804
	function jetpack_icon_user_connected( $columns ) {
6805
		$columns['user_jetpack'] = '';
6806
		return $columns;
6807
	}
6808
6809
	/*
6810
	 * Show Jetpack icon if the user is linked.
6811
	 */
6812
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6813
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6814
			$jetpack_logo = new Jetpack_Logo();
6815
			$emblem_html = sprintf(
6816
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6817
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6818
				$jetpack_logo->get_jp_emblem()
6819
			);
6820
			return $emblem_html;
6821
		}
6822
6823
		return $val;
6824
	}
6825
6826
	/*
6827
	 * Style the Jetpack user column
6828
	 */
6829
	function jetpack_user_col_style() {
6830
		global $current_screen;
6831
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6832
			<style>
6833
				.fixed .column-user_jetpack {
6834
					width: 21px;
6835
				}
6836
				.jp-emblem-user-admin svg {
6837
					width: 20px;
6838
					height: 20px;
6839
				}
6840
				.jp-emblem-user-admin path {
6841
					fill: #00BE28;
6842
				}
6843
			</style>
6844
		<?php }
6845
	}
6846
6847
	/**
6848
	 * Checks if Akismet is active and working.
6849
	 *
6850
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6851
	 * that implied usage of methods present since more recent version.
6852
	 * See https://github.com/Automattic/jetpack/pull/9585
6853
	 *
6854
	 * @since  5.1.0
6855
	 *
6856
	 * @return bool True = Akismet available. False = Aksimet not available.
6857
	 */
6858
	public static function is_akismet_active() {
6859
		static $status = null;
6860
6861
		if ( ! is_null( $status ) ) {
6862
			return $status;
6863
		}
6864
6865
		// Check if a modern version of Akismet is active.
6866
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6867
			$status = false;
6868
			return $status;
6869
		}
6870
6871
		// Make sure there is a key known to Akismet at all before verifying key.
6872
		$akismet_key = Akismet::get_api_key();
6873
		if ( ! $akismet_key ) {
6874
			$status = false;
6875
			return $status;
6876
		}
6877
6878
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6879
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6880
6881
		// 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.
6882
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6883
		// We cache the result of the Akismet key verification for ten minutes.
6884
		if ( ! $akismet_key_state || $recheck ) {
6885
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6886
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6887
		}
6888
6889
		$status = 'valid' === $akismet_key_state;
6890
6891
		return $status;
6892
	}
6893
6894
	/**
6895
	 * Checks if one or more function names is in debug_backtrace
6896
	 *
6897
	 * @param $names Mixed string name of function or array of string names of functions
6898
	 *
6899
	 * @return bool
6900
	 */
6901
	public static function is_function_in_backtrace( $names ) {
6902
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6903
		if ( ! is_array( $names ) ) {
6904
			$names = array( $names );
6905
		}
6906
		$names_as_keys = array_flip( $names );
6907
6908
		//Do check in constant O(1) time for PHP5.5+
6909
		if ( function_exists( 'array_column' ) ) {
6910
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6911
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6912
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6913
			return ! empty ( $intersection );
6914
		}
6915
6916
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6917
		foreach ( $backtrace as $call ) {
6918
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6919
				return true;
6920
			}
6921
		}
6922
		return false;
6923
	}
6924
6925
	/**
6926
	 * Given a minified path, and a non-minified path, will return
6927
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6928
	 *
6929
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6930
	 * root Jetpack directory.
6931
	 *
6932
	 * @since 5.6.0
6933
	 *
6934
	 * @param string $min_path
6935
	 * @param string $non_min_path
6936
	 * @return string The URL to the file
6937
	 */
6938
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6939
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6940
			? $non_min_path
6941
			: $min_path;
6942
6943
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6944
	}
6945
6946
	/**
6947
	 * Checks for whether Jetpack Backup & Scan is enabled.
6948
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6949
	 * @return bool|int|mixed
6950
	 */
6951
	public static function is_rewind_enabled() {
6952
		if ( ! Jetpack::is_active() ) {
6953
			return false;
6954
		}
6955
6956
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6957
		if ( false === $rewind_enabled ) {
6958
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6959
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6960
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6961
				&& ! empty( $rewind_data['state'] )
6962
				&& 'active' === $rewind_data['state'] )
6963
				? 1
6964
				: 0;
6965
6966
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6967
		}
6968
		return $rewind_enabled;
6969
	}
6970
6971
	/**
6972
	 * Return Calypso environment value; used for developing Jetpack and pairing
6973
	 * it with different Calypso enrionments, such as localhost.
6974
	 *
6975
	 * @since 7.4.0
6976
	 *
6977
	 * @return string Calypso environment
6978
	 */
6979
	public static function get_calypso_env() {
6980
		if ( isset( $_GET['calypso_env'] ) ) {
6981
			return sanitize_key( $_GET['calypso_env'] );
6982
		}
6983
6984
		if ( getenv( 'CALYPSO_ENV' ) ) {
6985
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6986
		}
6987
6988
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6989
			return sanitize_key( CALYPSO_ENV );
6990
		}
6991
6992
		return '';
6993
	}
6994
6995
	/**
6996
	 * Checks whether or not TOS has been agreed upon.
6997
	 * Will return true if a user has clicked to register, or is already connected.
6998
	 */
6999
	public static function jetpack_tos_agreed() {
7000
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7001
	}
7002
7003
	/**
7004
	 * Handles activating default modules as well general cleanup for the new connection.
7005
	 *
7006
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7007
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7008
	 * @param boolean $send_state_messages          Whether to send state messages.
7009
	 * @return void
7010
	 */
7011
	public static function handle_post_authorization_actions(
7012
		$activate_sso = false,
7013
		$redirect_on_activation_error = false,
7014
		$send_state_messages = true
7015
	) {
7016
		$other_modules = $activate_sso
7017
			? array( 'sso' )
7018
			: array();
7019
7020
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7021
			Jetpack::delete_active_modules();
7022
7023
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7024
		} else {
7025
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7026
		}
7027
7028
		// Since this is a fresh connection, be sure to clear out IDC options
7029
		Jetpack_IDC::clear_all_idc_options();
7030
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7031
7032
		// Start nonce cleaner
7033
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7034
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7035
7036
		if ( $send_state_messages ) {
7037
			Jetpack::state( 'message', 'authorized' );
7038
		}
7039
	}
7040
7041
	/**
7042
	 * Returns a boolean for whether backups UI should be displayed or not.
7043
	 *
7044
	 * @return bool Should backups UI be displayed?
7045
	 */
7046
	public static function show_backups_ui() {
7047
		/**
7048
		 * Whether UI for backups should be displayed.
7049
		 *
7050
		 * @since 6.5.0
7051
		 *
7052
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7053
		 */
7054
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7055
	}
7056
7057
	/*
7058
	 * Deprecated manage functions
7059
	 */
7060
	function prepare_manage_jetpack_notice() {
7061
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7062
	}
7063
	function manage_activate_screen() {
7064
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7065
	}
7066
	function admin_jetpack_manage_notice() {
7067
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7068
	}
7069
	function opt_out_jetpack_manage_url() {
7070
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7071
	}
7072
	function opt_in_jetpack_manage_url() {
7073
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7074
	}
7075
	function opt_in_jetpack_manage_notice() {
7076
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7077
	}
7078
	function can_display_jetpack_manage_notice() {
7079
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7080
	}
7081
7082
	/**
7083
	 * Clean leftoveruser meta.
7084
	 *
7085
	 * Delete Jetpack-related user meta when it is no longer needed.
7086
	 *
7087
	 * @since 7.3.0
7088
	 *
7089
	 * @param int $user_id User ID being updated.
7090
	 */
7091
	public static function user_meta_cleanup( $user_id ) {
7092
		$meta_keys = array(
7093
			// AtD removed from Jetpack 7.3
7094
			'AtD_options',
7095
			'AtD_check_when',
7096
			'AtD_guess_lang',
7097
			'AtD_ignored_phrases',
7098
		);
7099
7100
		foreach ( $meta_keys as $meta_key ) {
7101
			if ( get_user_meta( $user_id, $meta_key ) ) {
7102
				delete_user_meta( $user_id, $meta_key );
7103
			}
7104
		}
7105
	}
7106
}
7107