Completed
Push — feature/jetpack-packages ( 62aec5...47fdbc )
by
unknown
204:56 queued 198:07
created

Jetpack::load_modules()   D

Complexity

Conditions 17
Paths 49

Size

Total Lines 89

Duplication

Lines 6
Ratio 6.74 %

Importance

Changes 0
Metric Value
cc 17
nc 49
nop 0
dl 6
loc 89
rs 4.4132
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
453
	 */
454
	static function update_active_modules( $modules ) {
455
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
456
		$active_modules       = Jetpack::get_active_modules();
457
		$new_active_modules   = array_diff( $modules, $current_modules );
458
		$new_inactive_modules = array_diff( $active_modules, $modules );
459
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
460
		$reindexed_modules    = array_values( $new_current_modules );
461
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
462
463
		foreach ( $new_active_modules as $module ) {
464
			/**
465
			 * Fires when a specific module is activated.
466
			 *
467
			 * @since 1.9.0
468
			 *
469
			 * @param string $module Module slug.
470
			 * @param boolean $success whether the module was activated. @since 4.2
471
			 */
472
			do_action( 'jetpack_activate_module', $module, $success );
473
			/**
474
			 * Fires when a module is activated.
475
			 * The dynamic part of the filter, $module, is the module slug.
476
			 *
477
			 * @since 1.9.0
478
			 *
479
			 * @param string $module Module slug.
480
			 */
481
			do_action( "jetpack_activate_module_$module", $module );
482
		}
483
484
		foreach ( $new_inactive_modules as $module ) {
485
			/**
486
			 * Fired after a module has been deactivated.
487
			 *
488
			 * @since 4.2.0
489
			 *
490
			 * @param string $module Module slug.
491
			 * @param boolean $success whether the module was deactivated.
492
			 */
493
			do_action( 'jetpack_deactivate_module', $module, $success );
494
			/**
495
			 * Fires when a module is deactivated.
496
			 * The dynamic part of the filter, $module, is the module slug.
497
			 *
498
			 * @since 1.9.0
499
			 *
500
			 * @param string $module Module slug.
501
			 */
502
			do_action( "jetpack_deactivate_module_$module", $module );
503
		}
504
505
		return $success;
506
	}
507
508
	static function delete_active_modules() {
509
		self::update_active_modules( array() );
510
	}
511
512
	/**
513
	 * Constructor.  Initializes WordPress hooks
514
	 */
515
	private function __construct() {
516
		/*
517
		 * Check for and alert any deprecated hooks
518
		 */
519
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
520
521
		/*
522
		 * Enable enhanced handling of previewing sites in Calypso
523
		 */
524
		if ( Jetpack::is_active() ) {
525
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
526
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
527
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
528
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
529
		}
530
531
		/*
532
		 * Load things that should only be in Network Admin.
533
		 *
534
		 * For now blow away everything else until a more full
535
		 * understanding of what is needed at the network level is
536
		 * available
537
		 */
538
		if ( is_multisite() ) {
539
			Jetpack_Network::init();
540
		}
541
542
		add_filter( 'jetpack_connection_option_manager', function() {
543
			return new Jetpack_Options_Manager();
544
		} );
545
546
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
547
			return function() {
548
				return wp_generate_password( 32, false );
549
			};
550
		} );
551
552
		$this->connection_manager = new Connection_Manager( );
553
554
		/**
555
		 * Prepare Gutenberg Editor functionality
556
		 */
557
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
558
		Jetpack_Gutenberg::init();
559
		Jetpack_Gutenberg::load_independent_blocks();
560
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
561
562
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
563
564
		// Unlink user before deleting the user from .com
565
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
566
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
567
568
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
569
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
570
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
571
				define( 'XMLRPC_REQUEST', true );
572
			}
573
574
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
575
576
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
577
		}
578
579
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
580
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
581
582
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
583
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
584
585
			$this->require_jetpack_authentication();
586
587
			if ( Jetpack::is_active() ) {
588
				// Hack to preserve $HTTP_RAW_POST_DATA
589
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
590
591
				$signed = $this->verify_xml_rpc_signature();
592 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
593
					// The actual API methods.
594
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
595
				} else {
596
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
597
					// active Jetpack connection, so that additional users can link their account.
598
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
599
				}
600 View Code Duplication
			} else {
601
				// The bootstrap API methods.
602
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
603
				$signed = $this->verify_xml_rpc_signature();
604
				if ( $signed && ! is_wp_error( $signed ) ) {
605
					// the jetpack Provision method is available for blog-token-signed requests
606
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
607
				}
608
			}
609
610
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
611
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
612
		} elseif (
613
			is_admin() &&
614
			isset( $_POST['action'] ) && (
615
				'jetpack_upload_file' == $_POST['action'] ||
616
				'jetpack_update_file' == $_POST['action']
617
			)
618
		) {
619
			$this->require_jetpack_authentication();
620
			$this->add_remote_request_handlers();
621
		} else {
622
			if ( Jetpack::is_active() ) {
623
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
624
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
625
			}
626
		}
627
628
		if ( Jetpack::is_active() ) {
629
			Jetpack_Heartbeat::init();
630
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
631
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
632
				Jetpack_Search_Performance_Logger::init();
633
			}
634
		}
635
636
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
637
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
638
639
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
640
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
641
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
642
		}
643
644
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
645
646
		add_action( 'admin_init', array( $this, 'admin_init' ) );
647
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
648
649
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
650
651
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
652
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
653
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
654
655
		// returns HTTPS support status
656
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
657
658
		// JITM AJAX callback function
659
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
660
661
		// Universal ajax callback for all tracking events triggered via js
662
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
663
664
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
665
666
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
667
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
668
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
669
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
670
671
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
672
673
		/**
674
		 * These actions run checks to load additional files.
675
		 * They check for external files or plugins, so they need to run as late as possible.
676
		 */
677
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
678
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
679
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
680
681
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
682
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
683
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
684
685
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
686
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
687
688
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
689
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
690
691
		// A filter to control all just in time messages
692
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
693
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
694
695
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
696
		// We should make sure to only do this for front end links.
697
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
698
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
699
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
700
701
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
702
			//so they point moderation links on emails to Calypso
703
			jetpack_require_lib( 'functions.wp-notify' );
704
		}
705
706
		// Update the Jetpack plan from API on heartbeats
707
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
708
709
		/**
710
		 * This is the hack to concatenate all css files into one.
711
		 * For description and reasoning see the implode_frontend_css method
712
		 *
713
		 * Super late priority so we catch all the registered styles
714
		 */
715
		if( !is_admin() ) {
716
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
717
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
718
		}
719
720
		/**
721
		 * These are sync actions that we need to keep track of for jitms
722
		 */
723
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
724
725
		// Actually push the stats on shutdown.
726
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
727
			add_action( 'shutdown', array( $this, 'push_stats' ) );
728
		}
729
	}
730
731
	/**
732
	 * This is ported over from the manage module, which has been deprecated and baked in here.
733
	 *
734
	 * @param $domains
735
	 */
736
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
737
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
738
	}
739
740
	/**
741
	 * Return $domains, with 'wordpress.com' appended.
742
	 * This is ported over from the manage module, which has been deprecated and baked in here.
743
	 *
744
	 * @param $domains
745
	 * @return array
746
	 */
747
	function allow_wpcom_domain( $domains ) {
748
		if ( empty( $domains ) ) {
749
			$domains = array();
750
		}
751
		$domains[] = 'wordpress.com';
752
		return array_unique( $domains );
753
	}
754
755
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
756
		$post = get_post( $post_id );
757
758
		if ( empty( $post ) ) {
759
			return $default_url;
760
		}
761
762
		$post_type = $post->post_type;
763
764
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
765
		// https://en.support.wordpress.com/custom-post-types/
766
		$allowed_post_types = array(
767
			'post' => 'post',
768
			'page' => 'page',
769
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
770
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
771
		);
772
773
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
774
			return $default_url;
775
		}
776
777
		$path_prefix = $allowed_post_types[ $post_type ];
778
779
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
780
781
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
782
	}
783
784
	function point_edit_comment_links_to_calypso( $url ) {
785
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
786
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
787
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
788
			Jetpack::build_raw_urls( get_home_url() ),
789
			$query_args['amp;c']
790
		) );
791
	}
792
793
	function jetpack_track_last_sync_callback( $params ) {
794
		/**
795
		 * Filter to turn off jitm caching
796
		 *
797
		 * @since 5.4.0
798
		 *
799
		 * @param bool false Whether to cache just in time messages
800
		 */
801
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
802
			return $params;
803
		}
804
805
		if ( is_array( $params ) && isset( $params[0] ) ) {
806
			$option = $params[0];
807
			if ( 'active_plugins' === $option ) {
808
				// use the cache if we can, but not terribly important if it gets evicted
809
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
810
			}
811
		}
812
813
		return $params;
814
	}
815
816
	function jetpack_connection_banner_callback() {
817
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
818
819
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
820
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
821
			wp_send_json_success();
822
		}
823
824
		wp_die();
825
	}
826
827
	/**
828
	 * Removes all XML-RPC methods that are not `jetpack.*`.
829
	 * Only used in our alternate XML-RPC endpoint, where we want to
830
	 * ensure that Core and other plugins' methods are not exposed.
831
	 *
832
	 * @param array $methods
833
	 * @return array filtered $methods
834
	 */
835
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
836
		$jetpack_methods = array();
837
838
		foreach ( $methods as $method => $callback ) {
839
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
840
				$jetpack_methods[ $method ] = $callback;
841
			}
842
		}
843
844
		return $jetpack_methods;
845
	}
846
847
	/**
848
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
849
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
850
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
851
	 * which is accessible via a different URI. Most of the below is copied directly
852
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
853
	 */
854
	function alternate_xmlrpc() {
855
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
856
		global $HTTP_RAW_POST_DATA;
857
858
		// Some browser-embedded clients send cookies. We don't want them.
859
		$_COOKIE = array();
860
861
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
862
		// but we can do it ourself.
863
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
864
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
865
		}
866
867
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
868
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
869
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
870
		}
871
872
		// phpcs:enable
873
874
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
875
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
876
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
877
878
		/**
879
		 * Filters the class used for handling XML-RPC requests.
880
		 *
881
		 * @since 3.1.0
882
		 *
883
		 * @param string $class The name of the XML-RPC server class.
884
		 */
885
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
886
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
887
888
		// Fire off the request
889
		nocache_headers();
890
		$wp_xmlrpc_server->serve_request();
891
892
		exit;
893
	}
894
895
	function jetpack_admin_ajax_tracks_callback() {
896
		// Check for nonce
897
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
898
			wp_die( 'Permissions check failed.' );
899
		}
900
901
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
902
			wp_die( 'No valid event name or type.' );
903
		}
904
905
		$tracks_data = array();
906
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
907
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
908
				$tracks_data = $_REQUEST['tracksEventProp'];
909
			} else {
910
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
911
			}
912
		}
913
914
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
915
		wp_send_json_success();
916
		wp_die();
917
	}
918
919
	/**
920
	 * The callback for the JITM ajax requests.
921
	 */
922
	function jetpack_jitm_ajax_callback() {
923
		// Check for nonce
924
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
925
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
926
		}
927
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
928
			$module_slug = $_REQUEST['jitmModule'];
929
			Jetpack::log( 'activate', $module_slug );
930
			Jetpack::activate_module( $module_slug, false, false );
931
			Jetpack::state( 'message', 'no_message' );
932
933
			//A Jetpack module is being activated through a JITM, track it
934
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
935
			$this->do_stats( 'server_side' );
936
937
			wp_send_json_success();
938
		}
939
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
940
			// get the hide_jitm options array
941
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
942
			$module_slug = $_REQUEST['jitmModule'];
943
944
			if( ! $jetpack_hide_jitm ) {
945
				$jetpack_hide_jitm = array(
946
					$module_slug => 'hide'
947
				);
948
			} else {
949
				$jetpack_hide_jitm[$module_slug] = 'hide';
950
			}
951
952
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
953
954
			//jitm is being dismissed forever, track it
955
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
956
			$this->do_stats( 'server_side' );
957
958
			wp_send_json_success();
959
		}
960 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
961
			$module_slug = $_REQUEST['jitmModule'];
962
963
			// User went to WordPress.com, track this
964
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
965
			$this->do_stats( 'server_side' );
966
967
			wp_send_json_success();
968
		}
969 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
970
			$track = $_REQUEST['jitmModule'];
971
972
			// User is viewing JITM, track it.
973
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
974
			$this->do_stats( 'server_side' );
975
976
			wp_send_json_success();
977
		}
978
	}
979
980
	/**
981
	 * If there are any stats that need to be pushed, but haven't been, push them now.
982
	 */
983
	function push_stats() {
984
		if ( ! empty( $this->stats ) ) {
985
			$this->do_stats( 'server_side' );
986
		}
987
	}
988
989
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
990
		switch( $cap ) {
991
			case 'jetpack_connect' :
992
			case 'jetpack_reconnect' :
993
				if ( Jetpack::is_development_mode() ) {
994
					$caps = array( 'do_not_allow' );
995
					break;
996
				}
997
				/**
998
				 * Pass through. If it's not development mode, these should match disconnect.
999
				 * Let users disconnect if it's development mode, just in case things glitch.
1000
				 */
1001
			case 'jetpack_disconnect' :
1002
				/**
1003
				 * In multisite, can individual site admins manage their own connection?
1004
				 *
1005
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1006
				 */
1007
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1008
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1009
						/**
1010
						 * We need to update the option name -- it's terribly unclear which
1011
						 * direction the override goes.
1012
						 *
1013
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1014
						 */
1015
						$caps = array( 'do_not_allow' );
1016
						break;
1017
					}
1018
				}
1019
1020
				$caps = array( 'manage_options' );
1021
				break;
1022
			case 'jetpack_manage_modules' :
1023
			case 'jetpack_activate_modules' :
1024
			case 'jetpack_deactivate_modules' :
1025
				$caps = array( 'manage_options' );
1026
				break;
1027
			case 'jetpack_configure_modules' :
1028
				$caps = array( 'manage_options' );
1029
				break;
1030
			case 'jetpack_manage_autoupdates' :
1031
				$caps = array(
1032
					'manage_options',
1033
					'update_plugins',
1034
				);
1035
				break;
1036
			case 'jetpack_network_admin_page':
1037
			case 'jetpack_network_settings_page':
1038
				$caps = array( 'manage_network_plugins' );
1039
				break;
1040
			case 'jetpack_network_sites_page':
1041
				$caps = array( 'manage_sites' );
1042
				break;
1043
			case 'jetpack_admin_page' :
1044
				if ( Jetpack::is_development_mode() ) {
1045
					$caps = array( 'manage_options' );
1046
					break;
1047
				} else {
1048
					$caps = array( 'read' );
1049
				}
1050
				break;
1051
			case 'jetpack_connect_user' :
1052
				if ( Jetpack::is_development_mode() ) {
1053
					$caps = array( 'do_not_allow' );
1054
					break;
1055
				}
1056
				$caps = array( 'read' );
1057
				break;
1058
		}
1059
		return $caps;
1060
	}
1061
1062
	function require_jetpack_authentication() {
1063
		// Don't let anyone authenticate
1064
		$_COOKIE = array();
1065
		remove_all_filters( 'authenticate' );
1066
		remove_all_actions( 'wp_login_failed' );
1067
1068
		if ( Jetpack::is_active() ) {
1069
			// Allow Jetpack authentication
1070
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1071
		}
1072
	}
1073
1074
	/**
1075
	 * Load language files
1076
	 * @action plugins_loaded
1077
	 */
1078
	public static function plugin_textdomain() {
1079
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1080
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1081
	}
1082
1083
	/**
1084
	 * Register assets for use in various modules and the Jetpack admin page.
1085
	 *
1086
	 * @uses wp_script_is, wp_register_script, plugins_url
1087
	 * @action wp_loaded
1088
	 * @return null
1089
	 */
1090
	public function register_assets() {
1091
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1092
			wp_register_script(
1093
				'spin',
1094
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1095
				false,
1096
				'1.3'
1097
			);
1098
		}
1099
1100
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1101
			wp_register_script(
1102
				'jquery.spin',
1103
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1104
				array( 'jquery', 'spin' ),
1105
				'1.3'
1106
			);
1107
		}
1108
1109 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1110
			wp_register_script(
1111
				'jetpack-gallery-settings',
1112
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1113
				array( 'media-views' ),
1114
				'20121225'
1115
			);
1116
		}
1117
1118
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1119
			wp_register_script(
1120
				'jetpack-twitter-timeline',
1121
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1122
				array( 'jquery' ),
1123
				'4.0.0',
1124
				true
1125
			);
1126
		}
1127
1128
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1129
			wp_register_script(
1130
				'jetpack-facebook-embed',
1131
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1132
				array( 'jquery' ),
1133
				null,
1134
				true
1135
			);
1136
1137
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1138
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1139
			if ( ! is_numeric( $fb_app_id ) ) {
1140
				$fb_app_id = '';
1141
			}
1142
			wp_localize_script(
1143
				'jetpack-facebook-embed',
1144
				'jpfbembed',
1145
				array(
1146
					'appid' => $fb_app_id,
1147
					'locale' => $this->get_locale(),
1148
				)
1149
			);
1150
		}
1151
1152
		/**
1153
		 * As jetpack_register_genericons is by default fired off a hook,
1154
		 * the hook may have already fired by this point.
1155
		 * So, let's just trigger it manually.
1156
		 */
1157
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1158
		jetpack_register_genericons();
1159
1160
		/**
1161
		 * Register the social logos
1162
		 */
1163
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1164
		jetpack_register_social_logos();
1165
1166 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1167
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1168
	}
1169
1170
	/**
1171
	 * Guess locale from language code.
1172
	 *
1173
	 * @param string $lang Language code.
1174
	 * @return string|bool
1175
	 */
1176 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1177
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1178
			return 'en_US';
1179
		}
1180
1181
		if ( ! class_exists( 'GP_Locales' ) ) {
1182
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1183
				return false;
1184
			}
1185
1186
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1187
		}
1188
1189
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1190
			// WP.com: get_locale() returns 'it'
1191
			$locale = GP_Locales::by_slug( $lang );
1192
		} else {
1193
			// Jetpack: get_locale() returns 'it_IT';
1194
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1195
		}
1196
1197
		if ( ! $locale ) {
1198
			return false;
1199
		}
1200
1201
		if ( empty( $locale->facebook_locale ) ) {
1202
			if ( empty( $locale->wp_locale ) ) {
1203
				return false;
1204
			} else {
1205
				// Facebook SDK is smart enough to fall back to en_US if a
1206
				// locale isn't supported. Since supported Facebook locales
1207
				// can fall out of sync, we'll attempt to use the known
1208
				// wp_locale value and rely on said fallback.
1209
				return $locale->wp_locale;
1210
			}
1211
		}
1212
1213
		return $locale->facebook_locale;
1214
	}
1215
1216
	/**
1217
	 * Get the locale.
1218
	 *
1219
	 * @return string|bool
1220
	 */
1221
	function get_locale() {
1222
		$locale = $this->guess_locale_from_lang( get_locale() );
1223
1224
		if ( ! $locale ) {
1225
			$locale = 'en_US';
1226
		}
1227
1228
		return $locale;
1229
	}
1230
1231
	/**
1232
	 * Device Pixels support
1233
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1234
	 */
1235
	function devicepx() {
1236
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1237
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1238
		}
1239
	}
1240
1241
	/**
1242
	 * Return the network_site_url so that .com knows what network this site is a part of.
1243
	 * @param  bool $option
1244
	 * @return string
1245
	 */
1246
	public function jetpack_main_network_site_option( $option ) {
1247
		return network_site_url();
1248
	}
1249
	/**
1250
	 * Network Name.
1251
	 */
1252
	static function network_name( $option = null ) {
1253
		global $current_site;
1254
		return $current_site->site_name;
1255
	}
1256
	/**
1257
	 * Does the network allow new user and site registrations.
1258
	 * @return string
1259
	 */
1260
	static function network_allow_new_registrations( $option = null ) {
1261
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1262
	}
1263
	/**
1264
	 * Does the network allow admins to add new users.
1265
	 * @return boolian
1266
	 */
1267
	static function network_add_new_users( $option = null ) {
1268
		return (bool) get_site_option( 'add_new_users' );
1269
	}
1270
	/**
1271
	 * File upload psace left per site in MB.
1272
	 *  -1 means NO LIMIT.
1273
	 * @return number
1274
	 */
1275
	static function network_site_upload_space( $option = null ) {
1276
		// value in MB
1277
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1278
	}
1279
1280
	/**
1281
	 * Network allowed file types.
1282
	 * @return string
1283
	 */
1284
	static function network_upload_file_types( $option = null ) {
1285
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1286
	}
1287
1288
	/**
1289
	 * Maximum file upload size set by the network.
1290
	 * @return number
1291
	 */
1292
	static function network_max_upload_file_size( $option = null ) {
1293
		// value in KB
1294
		return get_site_option( 'fileupload_maxk', 300 );
1295
	}
1296
1297
	/**
1298
	 * Lets us know if a site allows admins to manage the network.
1299
	 * @return array
1300
	 */
1301
	static function network_enable_administration_menus( $option = null ) {
1302
		return get_site_option( 'menu_items' );
1303
	}
1304
1305
	/**
1306
	 * If a user has been promoted to or demoted from admin, we need to clear the
1307
	 * jetpack_other_linked_admins transient.
1308
	 *
1309
	 * @since 4.3.2
1310
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1311
	 *
1312
	 * @param int    $user_id   The user ID whose role changed.
1313
	 * @param string $role      The new role.
1314
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1315
	 */
1316
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1317
		if ( 'administrator' == $role
1318
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1319
			|| is_null( $old_roles )
1320
		) {
1321
			delete_transient( 'jetpack_other_linked_admins' );
1322
		}
1323
	}
1324
1325
	/**
1326
	 * Checks to see if there are any other users available to become primary
1327
	 * Users must both:
1328
	 * - Be linked to wpcom
1329
	 * - Be an admin
1330
	 *
1331
	 * @return mixed False if no other users are linked, Int if there are.
1332
	 */
1333
	static function get_other_linked_admins() {
1334
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1335
1336
		if ( false === $other_linked_users ) {
1337
			$admins = get_users( array( 'role' => 'administrator' ) );
1338
			if ( count( $admins ) > 1 ) {
1339
				$available = array();
1340
				foreach ( $admins as $admin ) {
1341
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1342
						$available[] = $admin->ID;
1343
					}
1344
				}
1345
1346
				$count_connected_admins = count( $available );
1347
				if ( count( $available ) > 1 ) {
1348
					$other_linked_users = $count_connected_admins;
1349
				} else {
1350
					$other_linked_users = 0;
1351
				}
1352
			} else {
1353
				$other_linked_users = 0;
1354
			}
1355
1356
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1357
		}
1358
1359
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1360
	}
1361
1362
	/**
1363
	 * Return whether we are dealing with a multi network setup or not.
1364
	 * The reason we are type casting this is because we want to avoid the situation where
1365
	 * the result is false since when is_main_network_option return false it cases
1366
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1367
	 * database which could be set to anything as opposed to what this function returns.
1368
	 * @param  bool  $option
1369
	 *
1370
	 * @return boolean
1371
	 */
1372
	public function is_main_network_option( $option ) {
1373
		// return '1' or ''
1374
		return (string) (bool) Jetpack::is_multi_network();
1375
	}
1376
1377
	/**
1378
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1379
	 *
1380
	 * @param  string  $option
1381
	 * @return boolean
1382
	 */
1383
	public function is_multisite( $option ) {
1384
		return (string) (bool) is_multisite();
1385
	}
1386
1387
	/**
1388
	 * Implemented since there is no core is multi network function
1389
	 * Right now there is no way to tell if we which network is the dominant network on the system
1390
	 *
1391
	 * @since  3.3
1392
	 * @return boolean
1393
	 */
1394
	public static function is_multi_network() {
1395
		global  $wpdb;
1396
1397
		// if we don't have a multi site setup no need to do any more
1398
		if ( ! is_multisite() ) {
1399
			return false;
1400
		}
1401
1402
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1403
		if ( $num_sites > 1 ) {
1404
			return true;
1405
		} else {
1406
			return false;
1407
		}
1408
	}
1409
1410
	/**
1411
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1412
	 * @return null
1413
	 */
1414
	function update_jetpack_main_network_site_option() {
1415
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1416
	}
1417
	/**
1418
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1419
	 *
1420
	 */
1421
	function update_jetpack_network_settings() {
1422
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1423
		// Only sync this info for the main network site.
1424
	}
1425
1426
	/**
1427
	 * Get back if the current site is single user site.
1428
	 *
1429
	 * @return bool
1430
	 */
1431
	public static function is_single_user_site() {
1432
		global $wpdb;
1433
1434 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1435
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1436
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1437
		}
1438
		return 1 === (int) $some_users;
1439
	}
1440
1441
	/**
1442
	 * Returns true if the site has file write access false otherwise.
1443
	 * @return string ( '1' | '0' )
1444
	 **/
1445
	public static function file_system_write_access() {
1446
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1447
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1448
		}
1449
1450
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1451
1452
		$filesystem_method = get_filesystem_method();
1453
		if ( $filesystem_method === 'direct' ) {
1454
			return 1;
1455
		}
1456
1457
		ob_start();
1458
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1459
		ob_end_clean();
1460
		if ( $filesystem_credentials_are_stored ) {
1461
			return 1;
1462
		}
1463
		return 0;
1464
	}
1465
1466
	/**
1467
	 * Finds out if a site is using a version control system.
1468
	 * @return string ( '1' | '0' )
1469
	 **/
1470
	public static function is_version_controlled() {
1471
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1472
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1473
	}
1474
1475
	/**
1476
	 * Determines whether the current theme supports featured images or not.
1477
	 * @return string ( '1' | '0' )
1478
	 */
1479
	public static function featured_images_enabled() {
1480
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1481
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1482
	}
1483
1484
	/**
1485
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1486
	 *
1487
	 * @deprecated 4.7 use get_avatar_url instead.
1488
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1489
	 * @param int $size Size of the avatar image
1490
	 * @param string $default URL to a default image to use if no avatar is available
1491
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1492
	 *
1493
	 * @return array
1494
	 */
1495
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1496
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1497
		return get_avatar_url( $id_or_email, array(
1498
			'size' => $size,
1499
			'default' => $default,
1500
			'force_default' => $force_display,
1501
		) );
1502
	}
1503
1504
	/**
1505
	 * jetpack_updates is saved in the following schema:
1506
	 *
1507
	 * array (
1508
	 *      'plugins'                       => (int) Number of plugin updates available.
1509
	 *      'themes'                        => (int) Number of theme updates available.
1510
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1511
	 *      'translations'                  => (int) Number of translation updates available.
1512
	 *      'total'                         => (int) Total of all available updates.
1513
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1514
	 * )
1515
	 * @return array
1516
	 */
1517
	public static function get_updates() {
1518
		$update_data = wp_get_update_data();
1519
1520
		// Stores the individual update counts as well as the total count.
1521
		if ( isset( $update_data['counts'] ) ) {
1522
			$updates = $update_data['counts'];
1523
		}
1524
1525
		// If we need to update WordPress core, let's find the latest version number.
1526 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1527
			$cur = get_preferred_from_update_core();
1528
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1529
				$updates['wp_update_version'] = $cur->current;
1530
			}
1531
		}
1532
		return isset( $updates ) ? $updates : array();
1533
	}
1534
1535
	public static function get_update_details() {
1536
		$update_details = array(
1537
			'update_core' => get_site_transient( 'update_core' ),
1538
			'update_plugins' => get_site_transient( 'update_plugins' ),
1539
			'update_themes' => get_site_transient( 'update_themes' ),
1540
		);
1541
		return $update_details;
1542
	}
1543
1544
	public static function refresh_update_data() {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1546
1547
	}
1548
1549
	public static function refresh_theme_data() {
1550
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1551
	}
1552
1553
	/**
1554
	 * Is Jetpack active?
1555
	 */
1556
	public static function is_active() {
1557
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Documentation introduced by
JETPACK_MASTER_USER is of type boolean, but the function expects a false|integer.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1778
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1779
	}
1780
1781
	/**
1782
	 * Gets current user IP address.
1783
	 *
1784
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1785
	 *
1786
	 * @return string                  Current user IP address.
1787
	 */
1788
	public static function current_user_ip( $check_all_headers = false ) {
1789
		if ( $check_all_headers ) {
1790
			foreach ( array(
1791
				'HTTP_CF_CONNECTING_IP',
1792
				'HTTP_CLIENT_IP',
1793
				'HTTP_X_FORWARDED_FOR',
1794
				'HTTP_X_FORWARDED',
1795
				'HTTP_X_CLUSTER_CLIENT_IP',
1796
				'HTTP_FORWARDED_FOR',
1797
				'HTTP_FORWARDED',
1798
				'HTTP_VIA',
1799
			) as $key ) {
1800
				if ( ! empty( $_SERVER[ $key ] ) ) {
1801
					return $_SERVER[ $key ];
1802
				}
1803
			}
1804
		}
1805
1806
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1807
	}
1808
1809
	/**
1810
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1811
	 */
1812
	function extra_oembed_providers() {
1813
		// Cloudup: https://dev.cloudup.com/#oembed
1814
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1815
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1816
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1817
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1818
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1819
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1820
	}
1821
1822
	/**
1823
	 * Synchronize connected user role changes
1824
	 */
1825
	function user_role_change( $user_id ) {
1826
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1827
		Jetpack_Sync_Users::user_role_change( $user_id );
1828
	}
1829
1830
	/**
1831
	 * Loads the currently active modules.
1832
	 */
1833
	public static function load_modules() {
1834
		if (
1835
			! self::is_active()
1836
			&& ! self::is_development_mode()
1837
			&& ! self::is_onboarding()
1838
			&& (
1839
				! is_multisite()
1840
				|| ! get_site_option( 'jetpack_protect_active' )
1841
			)
1842
		) {
1843
			return;
1844
		}
1845
1846
		$version = Jetpack_Options::get_option( 'version' );
1847 View Code Duplication
		if ( ! $version ) {
1848
			$version = $old_version = JETPACK__VERSION . ':' . time();
1849
			/** This action is documented in class.jetpack.php */
1850
			do_action( 'updating_jetpack_version', $version, false );
1851
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1852
		}
1853
		list( $version ) = explode( ':', $version );
1854
1855
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1856
1857
		$modules_data = array();
1858
1859
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1860
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1861
			$updated_modules = array();
1862
			foreach ( $modules as $module ) {
1863
				$modules_data[ $module ] = Jetpack::get_module( $module );
1864
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1865
					continue;
1866
				}
1867
1868
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1869
					continue;
1870
				}
1871
1872
				$updated_modules[] = $module;
1873
			}
1874
1875
			$modules = array_diff( $modules, $updated_modules );
1876
		}
1877
1878
		$is_development_mode = Jetpack::is_development_mode();
1879
1880
		foreach ( $modules as $index => $module ) {
1881
			// If we're in dev mode, disable modules requiring a connection
1882
			if ( $is_development_mode ) {
1883
				// Prime the pump if we need to
1884
				if ( empty( $modules_data[ $module ] ) ) {
1885
					$modules_data[ $module ] = Jetpack::get_module( $module );
1886
				}
1887
				// If the module requires a connection, but we're in local mode, don't include it.
1888
				if ( $modules_data[ $module ]['requires_connection'] ) {
1889
					continue;
1890
				}
1891
			}
1892
1893
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1894
				continue;
1895
			}
1896
1897
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1898
				unset( $modules[ $index ] );
1899
				self::update_active_modules( array_values( $modules ) );
1900
				continue;
1901
			}
1902
1903
			/**
1904
			 * Fires when a specific module is loaded.
1905
			 * The dynamic part of the hook, $module, is the module slug.
1906
			 *
1907
			 * @since 1.1.0
1908
			 */
1909
			do_action( 'jetpack_module_loaded_' . $module );
1910
		}
1911
1912
		/**
1913
		 * Fires when all the modules are loaded.
1914
		 *
1915
		 * @since 1.1.0
1916
		 */
1917
		do_action( 'jetpack_modules_loaded' );
1918
1919
		// 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.
1920
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1921
	}
1922
1923
	/**
1924
	 * Check if Jetpack's REST API compat file should be included
1925
	 * @action plugins_loaded
1926
	 * @return null
1927
	 */
1928
	public function check_rest_api_compat() {
1929
		/**
1930
		 * Filters the list of REST API compat files to be included.
1931
		 *
1932
		 * @since 2.2.5
1933
		 *
1934
		 * @param array $args Array of REST API compat files to include.
1935
		 */
1936
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1937
1938
		if ( function_exists( 'bbpress' ) )
1939
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1940
1941
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1942
			require_once $_jetpack_rest_api_compat_include;
1943
	}
1944
1945
	/**
1946
	 * Gets all plugins currently active in values, regardless of whether they're
1947
	 * traditionally activated or network activated.
1948
	 *
1949
	 * @todo Store the result in core's object cache maybe?
1950
	 */
1951
	public static function get_active_plugins() {
1952
		$active_plugins = (array) get_option( 'active_plugins', array() );
1953
1954
		if ( is_multisite() ) {
1955
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1956
			// whereas active_plugins stores them in the values.
1957
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1958
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1959
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1960
			}
1961
		}
1962
1963
		sort( $active_plugins );
1964
1965
		return array_unique( $active_plugins );
1966
	}
1967
1968
	/**
1969
	 * Gets and parses additional plugin data to send with the heartbeat data
1970
	 *
1971
	 * @since 3.8.1
1972
	 *
1973
	 * @return array Array of plugin data
1974
	 */
1975
	public static function get_parsed_plugin_data() {
1976
		if ( ! function_exists( 'get_plugins' ) ) {
1977
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1978
		}
1979
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1980
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1981
		$active_plugins = Jetpack::get_active_plugins();
1982
1983
		$plugins = array();
1984
		foreach ( $all_plugins as $path => $plugin_data ) {
1985
			$plugins[ $path ] = array(
1986
					'is_active' => in_array( $path, $active_plugins ),
1987
					'file'      => $path,
1988
					'name'      => $plugin_data['Name'],
1989
					'version'   => $plugin_data['Version'],
1990
					'author'    => $plugin_data['Author'],
1991
			);
1992
		}
1993
1994
		return $plugins;
1995
	}
1996
1997
	/**
1998
	 * Gets and parses theme data to send with the heartbeat data
1999
	 *
2000
	 * @since 3.8.1
2001
	 *
2002
	 * @return array Array of theme data
2003
	 */
2004
	public static function get_parsed_theme_data() {
2005
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2006
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2007
2008
		$themes = array();
2009
		foreach ( $all_themes as $slug => $theme_data ) {
2010
			$theme_headers = array();
2011
			foreach ( $header_keys as $header_key ) {
2012
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2013
			}
2014
2015
			$themes[ $slug ] = array(
2016
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2017
					'slug' => $slug,
2018
					'theme_root' => $theme_data->get_theme_root_uri(),
2019
					'parent' => $theme_data->parent(),
2020
					'headers' => $theme_headers
2021
			);
2022
		}
2023
2024
		return $themes;
2025
	}
2026
2027
	/**
2028
	 * Checks whether a specific plugin is active.
2029
	 *
2030
	 * We don't want to store these in a static variable, in case
2031
	 * there are switch_to_blog() calls involved.
2032
	 */
2033
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2034
		return in_array( $plugin, self::get_active_plugins() );
2035
	}
2036
2037
	/**
2038
	 * Check if Jetpack's Open Graph tags should be used.
2039
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2040
	 *
2041
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2042
	 * @action plugins_loaded
2043
	 * @return null
2044
	 */
2045
	public function check_open_graph() {
2046
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2047
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2048
		}
2049
2050
		$active_plugins = self::get_active_plugins();
2051
2052
		if ( ! empty( $active_plugins ) ) {
2053
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2054
				if ( in_array( $plugin, $active_plugins ) ) {
2055
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2056
					break;
2057
				}
2058
			}
2059
		}
2060
2061
		/**
2062
		 * Allow the addition of Open Graph Meta Tags to all pages.
2063
		 *
2064
		 * @since 2.0.3
2065
		 *
2066
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2067
		 */
2068
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2069
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2070
		}
2071
	}
2072
2073
	/**
2074
	 * Check if Jetpack's Twitter tags should be used.
2075
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2076
	 *
2077
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2078
	 * @action plugins_loaded
2079
	 * @return null
2080
	 */
2081
	public function check_twitter_tags() {
2082
2083
		$active_plugins = self::get_active_plugins();
2084
2085
		if ( ! empty( $active_plugins ) ) {
2086
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2087
				if ( in_array( $plugin, $active_plugins ) ) {
2088
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2089
					break;
2090
				}
2091
			}
2092
		}
2093
2094
		/**
2095
		 * Allow Twitter Card Meta tags to be disabled.
2096
		 *
2097
		 * @since 2.6.0
2098
		 *
2099
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2100
		 */
2101
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2102
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2103
		}
2104
	}
2105
2106
	/**
2107
	 * Allows plugins to submit security reports.
2108
 	 *
2109
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2110
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2111
	 * @param array   $args         See definitions above
2112
	 */
2113
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2114
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2115
	}
2116
2117
/* Jetpack Options API */
2118
2119
	public static function get_option_names( $type = 'compact' ) {
2120
		return Jetpack_Options::get_option_names( $type );
2121
	}
2122
2123
	/**
2124
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2125
 	 *
2126
	 * @param string $name    Option name
2127
	 * @param mixed  $default (optional)
2128
	 */
2129
	public static function get_option( $name, $default = false ) {
2130
		return Jetpack_Options::get_option( $name, $default );
2131
	}
2132
2133
	/**
2134
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2135
 	 *
2136
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2137
	 * @param string $name  Option name
2138
	 * @param mixed  $value Option value
2139
	 */
2140
	public static function update_option( $name, $value ) {
2141
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2142
		return Jetpack_Options::update_option( $name, $value );
2143
	}
2144
2145
	/**
2146
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2147
 	 *
2148
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2149
	 * @param array $array array( option name => option value, ... )
2150
	 */
2151
	public static function update_options( $array ) {
2152
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2153
		return Jetpack_Options::update_options( $array );
2154
	}
2155
2156
	/**
2157
	 * Deletes the given option.  May be passed multiple option names as an array.
2158
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2159
	 *
2160
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2161
	 * @param string|array $names
2162
	 */
2163
	public static function delete_option( $names ) {
2164
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2165
		return Jetpack_Options::delete_option( $names );
2166
	}
2167
2168
	/**
2169
	 * Enters a user token into the user_tokens option
2170
	 *
2171
	 * @param int $user_id
2172
	 * @param string $token
2173
	 * return bool
2174
	 */
2175
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2176
		// not designed for concurrent updates
2177
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2178
		if ( ! is_array( $user_tokens ) )
2179
			$user_tokens = array();
2180
		$user_tokens[$user_id] = $token;
2181
		if ( $is_master_user ) {
2182
			$master_user = $user_id;
2183
			$options     = compact( 'user_tokens', 'master_user' );
2184
		} else {
2185
			$options = compact( 'user_tokens' );
2186
		}
2187
		return Jetpack_Options::update_options( $options );
2188
	}
2189
2190
	/**
2191
	 * Returns an array of all PHP files in the specified absolute path.
2192
	 * Equivalent to glob( "$absolute_path/*.php" ).
2193
	 *
2194
	 * @param string $absolute_path The absolute path of the directory to search.
2195
	 * @return array Array of absolute paths to the PHP files.
2196
	 */
2197
	public static function glob_php( $absolute_path ) {
2198
		if ( function_exists( 'glob' ) ) {
2199
			return glob( "$absolute_path/*.php" );
2200
		}
2201
2202
		$absolute_path = untrailingslashit( $absolute_path );
2203
		$files = array();
2204
		if ( ! $dir = @opendir( $absolute_path ) ) {
2205
			return $files;
2206
		}
2207
2208
		while ( false !== $file = readdir( $dir ) ) {
2209
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2210
				continue;
2211
			}
2212
2213
			$file = "$absolute_path/$file";
2214
2215
			if ( ! is_file( $file ) ) {
2216
				continue;
2217
			}
2218
2219
			$files[] = $file;
2220
		}
2221
2222
		closedir( $dir );
2223
2224
		return $files;
2225
	}
2226
2227
	public static function activate_new_modules( $redirect = false ) {
2228
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2229
			return;
2230
		}
2231
2232
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2233 View Code Duplication
		if ( ! $jetpack_old_version ) {
2234
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2235
			/** This action is documented in class.jetpack.php */
2236
			do_action( 'updating_jetpack_version', $version, false );
2237
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2238
		}
2239
2240
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2241
2242
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2243
			return;
2244
		}
2245
2246
		$active_modules     = Jetpack::get_active_modules();
2247
		$reactivate_modules = array();
2248
		foreach ( $active_modules as $active_module ) {
2249
			$module = Jetpack::get_module( $active_module );
2250
			if ( ! isset( $module['changed'] ) ) {
2251
				continue;
2252
			}
2253
2254
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2255
				continue;
2256
			}
2257
2258
			$reactivate_modules[] = $active_module;
2259
			Jetpack::deactivate_module( $active_module );
2260
		}
2261
2262
		$new_version = JETPACK__VERSION . ':' . time();
2263
		/** This action is documented in class.jetpack.php */
2264
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2265
		Jetpack_Options::update_options(
2266
			array(
2267
				'version'     => $new_version,
2268
				'old_version' => $jetpack_old_version,
2269
			)
2270
		);
2271
2272
		Jetpack::state( 'message', 'modules_activated' );
2273
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, 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...
2274
2275
		if ( $redirect ) {
2276
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2277
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2278
				$page = $_GET['page'];
2279
			}
2280
2281
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2282
			exit;
2283
		}
2284
	}
2285
2286
	/**
2287
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2288
	 * Make sure to tuck away module "library" files in a sub-directory.
2289
	 */
2290
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2291
		static $modules = null;
2292
2293
		if ( ! isset( $modules ) ) {
2294
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2295
			// Use the cache if we're on the front-end and it's available...
2296
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2297
				$modules = $available_modules_option[ JETPACK__VERSION ];
2298
			} else {
2299
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2300
2301
				$modules = array();
2302
2303
				foreach ( $files as $file ) {
2304
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2305
						continue;
2306
					}
2307
2308
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2309
				}
2310
2311
				Jetpack_Options::update_option( 'available_modules', array(
2312
					JETPACK__VERSION => $modules,
2313
				) );
2314
			}
2315
		}
2316
2317
		/**
2318
		 * Filters the array of modules available to be activated.
2319
		 *
2320
		 * @since 2.4.0
2321
		 *
2322
		 * @param array $modules Array of available modules.
2323
		 * @param string $min_version Minimum version number required to use modules.
2324
		 * @param string $max_version Maximum version number required to use modules.
2325
		 */
2326
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2327
2328
		if ( ! $min_version && ! $max_version ) {
2329
			return array_keys( $mods );
2330
		}
2331
2332
		$r = array();
2333
		foreach ( $mods as $slug => $introduced ) {
2334
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2335
				continue;
2336
			}
2337
2338
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2339
				continue;
2340
			}
2341
2342
			$r[] = $slug;
2343
		}
2344
2345
		return $r;
2346
	}
2347
2348
	/**
2349
	 * Default modules loaded on activation.
2350
	 */
2351
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2352
		$return = array();
2353
2354
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2355
			$module_data = Jetpack::get_module( $module );
2356
2357
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2358
				case 'yes' :
2359
					$return[] = $module;
2360
					break;
2361
				case 'public' :
2362
					if ( Jetpack_Options::get_option( 'public' ) ) {
2363
						$return[] = $module;
2364
					}
2365
					break;
2366
				case 'no' :
2367
				default :
2368
					break;
2369
			}
2370
		}
2371
		/**
2372
		 * Filters the array of default modules.
2373
		 *
2374
		 * @since 2.5.0
2375
		 *
2376
		 * @param array $return Array of default modules.
2377
		 * @param string $min_version Minimum version number required to use modules.
2378
		 * @param string $max_version Maximum version number required to use modules.
2379
		 */
2380
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2381
	}
2382
2383
	/**
2384
	 * Checks activated modules during auto-activation to determine
2385
	 * if any of those modules are being deprecated.  If so, close
2386
	 * them out, and add any replacement modules.
2387
	 *
2388
	 * Runs at priority 99 by default.
2389
	 *
2390
	 * This is run late, so that it can still activate a module if
2391
	 * the new module is a replacement for another that the user
2392
	 * currently has active, even if something at the normal priority
2393
	 * would kibosh everything.
2394
	 *
2395
	 * @since 2.6
2396
	 * @uses jetpack_get_default_modules filter
2397
	 * @param array $modules
2398
	 * @return array
2399
	 */
2400
	function handle_deprecated_modules( $modules ) {
2401
		$deprecated_modules = array(
2402
			'debug'            => null,  // Closed out and moved to the debugger library.
2403
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2404
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2405
		);
2406
2407
		// Don't activate SSO if they never completed activating WPCC.
2408
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2409
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2410
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2411
				$deprecated_modules['wpcc'] = null;
2412
			}
2413
		}
2414
2415
		foreach ( $deprecated_modules as $module => $replacement ) {
2416
			if ( Jetpack::is_module_active( $module ) ) {
2417
				self::deactivate_module( $module );
2418
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2419
					$modules[] = $replacement;
2420
				}
2421
			}
2422
		}
2423
2424
		return array_unique( $modules );
2425
	}
2426
2427
	/**
2428
	 * Checks activated plugins during auto-activation to determine
2429
	 * if any of those plugins are in the list with a corresponding module
2430
	 * that is not compatible with the plugin. The module will not be allowed
2431
	 * to auto-activate.
2432
	 *
2433
	 * @since 2.6
2434
	 * @uses jetpack_get_default_modules filter
2435
	 * @param array $modules
2436
	 * @return array
2437
	 */
2438
	function filter_default_modules( $modules ) {
2439
2440
		$active_plugins = self::get_active_plugins();
2441
2442
		if ( ! empty( $active_plugins ) ) {
2443
2444
			// For each module we'd like to auto-activate...
2445
			foreach ( $modules as $key => $module ) {
2446
				// If there are potential conflicts for it...
2447
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2448
					// For each potential conflict...
2449
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2450
						// If that conflicting plugin is active...
2451
						if ( in_array( $plugin, $active_plugins ) ) {
2452
							// Remove that item from being auto-activated.
2453
							unset( $modules[ $key ] );
2454
						}
2455
					}
2456
				}
2457
			}
2458
		}
2459
2460
		return $modules;
2461
	}
2462
2463
	/**
2464
	 * Extract a module's slug from its full path.
2465
	 */
2466
	public static function get_module_slug( $file ) {
2467
		return str_replace( '.php', '', basename( $file ) );
2468
	}
2469
2470
	/**
2471
	 * Generate a module's path from its slug.
2472
	 */
2473
	public static function get_module_path( $slug ) {
2474
		/**
2475
		 * Filters the path of a modules.
2476
		 *
2477
		 * @since 7.4.0
2478
		 *
2479
		 * @param array $return The absolute path to a module's root php file
2480
		 * @param string $slug The module slug
2481
		 */
2482
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2483
	}
2484
2485
	/**
2486
	 * Load module data from module file. Headers differ from WordPress
2487
	 * plugin headers to avoid them being identified as standalone
2488
	 * plugins on the WordPress plugins page.
2489
	 */
2490
	public static function get_module( $module ) {
2491
		$headers = array(
2492
			'name'                      => 'Module Name',
2493
			'description'               => 'Module Description',
2494
			'jumpstart_desc'            => 'Jumpstart Description',
2495
			'sort'                      => 'Sort Order',
2496
			'recommendation_order'      => 'Recommendation Order',
2497
			'introduced'                => 'First Introduced',
2498
			'changed'                   => 'Major Changes In',
2499
			'deactivate'                => 'Deactivate',
2500
			'free'                      => 'Free',
2501
			'requires_connection'       => 'Requires Connection',
2502
			'auto_activate'             => 'Auto Activate',
2503
			'module_tags'               => 'Module Tags',
2504
			'feature'                   => 'Feature',
2505
			'additional_search_queries' => 'Additional Search Queries',
2506
			'plan_classes'              => 'Plans',
2507
		);
2508
2509
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2510
2511
		$mod = Jetpack::get_file_data( $file, $headers );
2512
		if ( empty( $mod['name'] ) ) {
2513
			return false;
2514
		}
2515
2516
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2517
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2518
		$mod['deactivate']              = empty( $mod['deactivate'] );
2519
		$mod['free']                    = empty( $mod['free'] );
2520
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2521
2522
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2523
			$mod['auto_activate'] = 'No';
2524
		} else {
2525
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2526
		}
2527
2528
		if ( $mod['module_tags'] ) {
2529
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2530
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2531
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2532
		} else {
2533
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2534
		}
2535
2536 View Code Duplication
		if ( $mod['plan_classes'] ) {
2537
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2538
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2539
		} else {
2540
			$mod['plan_classes'] = array( 'free' );
2541
		}
2542
2543 View Code Duplication
		if ( $mod['feature'] ) {
2544
			$mod['feature'] = explode( ',', $mod['feature'] );
2545
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2546
		} else {
2547
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2548
		}
2549
2550
		/**
2551
		 * Filters the feature array on a module.
2552
		 *
2553
		 * This filter allows you to control where each module is filtered: Recommended,
2554
		 * Jumpstart, and the default "Other" listing.
2555
		 *
2556
		 * @since 3.5.0
2557
		 *
2558
		 * @param array   $mod['feature'] The areas to feature this module:
2559
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2560
		 *     'Recommended' shows on the main Jetpack admin screen.
2561
		 *     'Other' should be the default if no other value is in the array.
2562
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2563
		 * @param array   $mod All the currently assembled module data.
2564
		 */
2565
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2566
2567
		/**
2568
		 * Filter the returned data about a module.
2569
		 *
2570
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2571
		 * so please be careful.
2572
		 *
2573
		 * @since 3.6.0
2574
		 *
2575
		 * @param array   $mod    The details of the requested module.
2576
		 * @param string  $module The slug of the module, e.g. sharedaddy
2577
		 * @param string  $file   The path to the module source file.
2578
		 */
2579
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2580
	}
2581
2582
	/**
2583
	 * Like core's get_file_data implementation, but caches the result.
2584
	 */
2585
	public static function get_file_data( $file, $headers ) {
2586
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2587
		$file_name = basename( $file );
2588
2589
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2590
2591
		$file_data_option = get_transient( $cache_key );
2592
2593
		if ( false === $file_data_option ) {
2594
			$file_data_option = array();
2595
		}
2596
2597
		$key           = md5( $file_name . serialize( $headers ) );
2598
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2599
2600
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2601
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2602
			return $file_data_option[ $key ];
2603
		}
2604
2605
		$data = get_file_data( $file, $headers );
2606
2607
		$file_data_option[ $key ] = $data;
2608
2609
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2610
2611
		return $data;
2612
	}
2613
2614
2615
	/**
2616
	 * Return translated module tag.
2617
	 *
2618
	 * @param string $tag Tag as it appears in each module heading.
2619
	 *
2620
	 * @return mixed
2621
	 */
2622
	public static function translate_module_tag( $tag ) {
2623
		return jetpack_get_module_i18n_tag( $tag );
2624
	}
2625
2626
	/**
2627
	 * Get i18n strings as a JSON-encoded string
2628
	 *
2629
	 * @return string The locale as JSON
2630
	 */
2631
	public static function get_i18n_data_json() {
2632
2633
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2634
		// JSON files with the file they should be included for. This is an md5
2635
		// of '_inc/build/admin.js'.
2636
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2637
2638
		$i18n_json =
2639
				   JETPACK__PLUGIN_DIR
2640
				   . 'languages/json/jetpack-'
2641
				   . get_user_locale()
2642
				   . '-'
2643
				   . $path_md5
2644
				   . '.json';
2645
2646
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2647
			$locale_data = @file_get_contents( $i18n_json );
2648
			if ( $locale_data ) {
2649
				return $locale_data;
2650
			}
2651
		}
2652
2653
		// Return valid empty Jed locale
2654
		return '{ "locale_data": { "messages": { "": {} } } }';
2655
	}
2656
2657
	/**
2658
	 * Add locale data setup to wp-i18n
2659
	 *
2660
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2661
	 *
2662
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2663
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2664
	 *
2665
	 * This method provides a safe way to request the setup multiple times but add the script at
2666
	 * most once.
2667
	 *
2668
	 * @since 6.7.0
2669
	 *
2670
	 * @return void
2671
	 */
2672
	public static function setup_wp_i18n_locale_data() {
2673
		static $script_added = false;
2674
		if ( ! $script_added ) {
2675
			$script_added = true;
2676
			wp_add_inline_script(
2677
				'wp-i18n',
2678
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2679
			);
2680
		}
2681
	}
2682
2683
	/**
2684
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2685
	 *
2686
	 * @since 3.9.2
2687
	 *
2688
	 * @param array $modules
2689
	 *
2690
	 * @return string|void
2691
	 */
2692
	public static function get_translated_modules( $modules ) {
2693
		foreach ( $modules as $index => $module ) {
2694
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2695
			if ( isset( $module['name'] ) ) {
2696
				$modules[ $index ]['name'] = $i18n_module['name'];
2697
			}
2698
			if ( isset( $module['description'] ) ) {
2699
				$modules[ $index ]['description'] = $i18n_module['description'];
2700
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2701
			}
2702
		}
2703
		return $modules;
2704
	}
2705
2706
	/**
2707
	 * Get a list of activated modules as an array of module slugs.
2708
	 */
2709
	public static function get_active_modules() {
2710
		$active = Jetpack_Options::get_option( 'active_modules' );
2711
2712
		if ( ! is_array( $active ) ) {
2713
			$active = array();
2714
		}
2715
2716
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2717
			$active[] = 'vaultpress';
2718
		} else {
2719
			$active = array_diff( $active, array( 'vaultpress' ) );
2720
		}
2721
2722
		//If protect is active on the main site of a multisite, it should be active on all sites.
2723
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2724
			$active[] = 'protect';
2725
		}
2726
2727
		/**
2728
		 * Allow filtering of the active modules.
2729
		 *
2730
		 * Gives theme and plugin developers the power to alter the modules that
2731
		 * are activated on the fly.
2732
		 *
2733
		 * @since 5.8.0
2734
		 *
2735
		 * @param array $active Array of active module slugs.
2736
		 */
2737
		$active = apply_filters( 'jetpack_active_modules', $active );
2738
2739
		return array_unique( $active );
2740
	}
2741
2742
	/**
2743
	 * Check whether or not a Jetpack module is active.
2744
	 *
2745
	 * @param string $module The slug of a Jetpack module.
2746
	 * @return bool
2747
	 *
2748
	 * @static
2749
	 */
2750
	public static function is_module_active( $module ) {
2751
		return in_array( $module, self::get_active_modules() );
2752
	}
2753
2754
	public static function is_module( $module ) {
2755
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2756
	}
2757
2758
	/**
2759
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2760
	 *
2761
	 * @param bool $catch True to start catching, False to stop.
2762
	 *
2763
	 * @static
2764
	 */
2765
	public static function catch_errors( $catch ) {
2766
		static $display_errors, $error_reporting;
2767
2768
		if ( $catch ) {
2769
			$display_errors  = @ini_set( 'display_errors', 1 );
2770
			$error_reporting = @error_reporting( E_ALL );
2771
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2772
		} else {
2773
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2774
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2775
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2776
		}
2777
	}
2778
2779
	/**
2780
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2781
	 */
2782
	public static function catch_errors_on_shutdown() {
2783
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2784
	}
2785
2786
	/**
2787
	 * Rewrite any string to make paths easier to read.
2788
	 *
2789
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2790
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2791
	 *
2792
	 * @param $string
2793
	 * @return mixed
2794
	 */
2795
	public static function alias_directories( $string ) {
2796
		// ABSPATH has a trailing slash.
2797
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2798
		// WP_CONTENT_DIR does not have a trailing slash.
2799
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2800
2801
		return $string;
2802
	}
2803
2804
	public static function activate_default_modules(
2805
		$min_version = false,
2806
		$max_version = false,
2807
		$other_modules = array(),
2808
		$redirect = true,
2809
		$send_state_messages = true
2810
	) {
2811
		$jetpack = Jetpack::init();
2812
2813
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2814
		$modules = array_merge( $other_modules, $modules );
2815
2816
		// Look for standalone plugins and disable if active.
2817
2818
		$to_deactivate = array();
2819
		foreach ( $modules as $module ) {
2820
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2821
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2822
			}
2823
		}
2824
2825
		$deactivated = array();
2826
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2827
			list( $probable_file, $probable_title ) = $deactivate_me;
2828
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2829
				$deactivated[] = $module;
2830
			}
2831
		}
2832
2833
		if ( $deactivated && $redirect ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2834
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2835
2836
			$url = add_query_arg(
2837
				array(
2838
					'action'   => 'activate_default_modules',
2839
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2840
				),
2841
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2842
			);
2843
			wp_safe_redirect( $url );
2844
			exit;
2845
		}
2846
2847
		/**
2848
		 * Fires before default modules are activated.
2849
		 *
2850
		 * @since 1.9.0
2851
		 *
2852
		 * @param string $min_version Minimum version number required to use modules.
2853
		 * @param string $max_version Maximum version number required to use modules.
2854
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2855
		 */
2856
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2857
2858
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2859
		if ( $send_state_messages ) {
2860
			Jetpack::restate();
2861
			Jetpack::catch_errors( true );
2862
		}
2863
2864
		$active = Jetpack::get_active_modules();
2865
2866
		foreach ( $modules as $module ) {
2867
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2868
				$active[] = $module;
2869
				self::update_active_modules( $active );
2870
				continue;
2871
			}
2872
2873
			if ( $send_state_messages && in_array( $module, $active ) ) {
2874
				$module_info = Jetpack::get_module( $module );
2875 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2876
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2877
					if ( $active_state = Jetpack::state( $state ) ) {
2878
						$active_state = explode( ',', $active_state );
2879
					} else {
2880
						$active_state = array();
2881
					}
2882
					$active_state[] = $module;
2883
					Jetpack::state( $state, implode( ',', $active_state ) );
2884
				}
2885
				continue;
2886
			}
2887
2888
			$file = Jetpack::get_module_path( $module );
2889
			if ( ! file_exists( $file ) ) {
2890
				continue;
2891
			}
2892
2893
			// we'll override this later if the plugin can be included without fatal error
2894
			if ( $redirect ) {
2895
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2896
			}
2897
2898
			if ( $send_state_messages ) {
2899
				Jetpack::state( 'error', 'module_activation_failed' );
2900
				Jetpack::state( 'module', $module );
2901
			}
2902
2903
			ob_start();
2904
			require_once $file;
2905
2906
			$active[] = $module;
2907
2908 View Code Duplication
			if ( $send_state_messages ) {
2909
2910
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2911
				if ( $active_state = Jetpack::state( $state ) ) {
2912
					$active_state = explode( ',', $active_state );
2913
				} else {
2914
					$active_state = array();
2915
				}
2916
				$active_state[] = $module;
2917
				Jetpack::state( $state, implode( ',', $active_state ) );
2918
			}
2919
2920
			Jetpack::update_active_modules( $active );
2921
2922
			ob_end_clean();
2923
		}
2924
2925
		if ( $send_state_messages ) {
2926
			Jetpack::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2927
			Jetpack::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2928
		}
2929
2930
		Jetpack::catch_errors( false );
2931
		/**
2932
		 * Fires when default modules are activated.
2933
		 *
2934
		 * @since 1.9.0
2935
		 *
2936
		 * @param string $min_version Minimum version number required to use modules.
2937
		 * @param string $max_version Maximum version number required to use modules.
2938
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2939
		 */
2940
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2941
	}
2942
2943
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2944
		/**
2945
		 * Fires before a module is activated.
2946
		 *
2947
		 * @since 2.6.0
2948
		 *
2949
		 * @param string $module Module slug.
2950
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2951
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2952
		 */
2953
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2954
2955
		$jetpack = Jetpack::init();
2956
2957
		if ( ! strlen( $module ) )
2958
			return false;
2959
2960
		if ( ! Jetpack::is_module( $module ) )
2961
			return false;
2962
2963
		// If it's already active, then don't do it again
2964
		$active = Jetpack::get_active_modules();
2965
		foreach ( $active as $act ) {
2966
			if ( $act == $module )
2967
				return true;
2968
		}
2969
2970
		$module_data = Jetpack::get_module( $module );
2971
2972
		if ( ! Jetpack::is_active() ) {
2973
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2974
				return false;
2975
2976
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2977
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2978
				return false;
2979
		}
2980
2981
		// Check and see if the old plugin is active
2982
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2983
			// Deactivate the old plugin
2984
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2985
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2986
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2987
				Jetpack::state( 'deactivated_plugins', $module );
2988
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2989
				exit;
2990
			}
2991
		}
2992
2993
		// Protect won't work with mis-configured IPs
2994
		if ( 'protect' === $module ) {
2995
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2996
			if ( ! jetpack_protect_get_ip() ) {
2997
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2998
				return false;
2999
			}
3000
		}
3001
3002
		if ( ! Jetpack_Plan::supports( $module ) ) {
3003
			return false;
3004
		}
3005
3006
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3007
		Jetpack::state( 'module', $module );
3008
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3009
3010
		Jetpack::catch_errors( true );
3011
		ob_start();
3012
		require Jetpack::get_module_path( $module );
3013
		/** This action is documented in class.jetpack.php */
3014
		do_action( 'jetpack_activate_module', $module );
3015
		$active[] = $module;
3016
		Jetpack::update_active_modules( $active );
3017
3018
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3019
		ob_end_clean();
3020
		Jetpack::catch_errors( false );
3021
3022
		if ( $redirect ) {
3023
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3024
		}
3025
		if ( $exit ) {
3026
			exit;
3027
		}
3028
		return true;
3029
	}
3030
3031
	function activate_module_actions( $module ) {
3032
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3033
	}
3034
3035
	public static function deactivate_module( $module ) {
3036
		/**
3037
		 * Fires when a module is deactivated.
3038
		 *
3039
		 * @since 1.9.0
3040
		 *
3041
		 * @param string $module Module slug.
3042
		 */
3043
		do_action( 'jetpack_pre_deactivate_module', $module );
3044
3045
		$jetpack = Jetpack::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3046
3047
		$active = Jetpack::get_active_modules();
3048
		$new    = array_filter( array_diff( $active, (array) $module ) );
3049
3050
		return self::update_active_modules( $new );
3051
	}
3052
3053
	public static function enable_module_configurable( $module ) {
3054
		$module = Jetpack::get_module_slug( $module );
3055
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3056
	}
3057
3058
	/**
3059
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3060
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3061
	 *
3062
	 * @param string $module Module slug
3063
	 * @return string $url module configuration URL
3064
	 */
3065
	public static function module_configuration_url( $module ) {
3066
		$module = Jetpack::get_module_slug( $module );
3067
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3068
		/**
3069
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3070
		 *
3071
		 * @since 6.9.0
3072
		 *
3073
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3074
		 */
3075
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3076
3077
		return $url;
3078
	}
3079
3080
/* Installation */
3081
	public static function bail_on_activation( $message, $deactivate = true ) {
3082
?>
3083
<!doctype html>
3084
<html>
3085
<head>
3086
<meta charset="<?php bloginfo( 'charset' ); ?>">
3087
<style>
3088
* {
3089
	text-align: center;
3090
	margin: 0;
3091
	padding: 0;
3092
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3093
}
3094
p {
3095
	margin-top: 1em;
3096
	font-size: 18px;
3097
}
3098
</style>
3099
<body>
3100
<p><?php echo esc_html( $message ); ?></p>
3101
</body>
3102
</html>
3103
<?php
3104
		if ( $deactivate ) {
3105
			$plugins = get_option( 'active_plugins' );
3106
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3107
			$update  = false;
3108
			foreach ( $plugins as $i => $plugin ) {
3109
				if ( $plugin === $jetpack ) {
3110
					$plugins[$i] = false;
3111
					$update = true;
3112
				}
3113
			}
3114
3115
			if ( $update ) {
3116
				update_option( 'active_plugins', array_filter( $plugins ) );
3117
			}
3118
		}
3119
		exit;
3120
	}
3121
3122
	/**
3123
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3124
	 * @static
3125
	 */
3126
	public static function plugin_activation( $network_wide ) {
3127
		Jetpack_Options::update_option( 'activated', 1 );
3128
3129
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3130
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3131
		}
3132
3133
		if ( $network_wide )
3134
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3135
3136
		// For firing one-off events (notices) immediately after activation
3137
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3138
3139
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3140
3141
		Jetpack::plugin_initialize();
3142
	}
3143
3144
	public static function get_activation_source( $referer_url ) {
3145
3146
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3147
			return array( 'wp-cli', null );
3148
		}
3149
3150
		$referer = parse_url( $referer_url );
3151
3152
		$source_type = 'unknown';
3153
		$source_query = null;
3154
3155
		if ( ! is_array( $referer ) ) {
3156
			return array( $source_type, $source_query );
3157
		}
3158
3159
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3160
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3161
3162
		if ( isset( $referer['query'] ) ) {
3163
			parse_str( $referer['query'], $query_parts );
3164
		} else {
3165
			$query_parts = array();
3166
		}
3167
3168
		if ( $plugins_path === $referer['path'] ) {
3169
			$source_type = 'list';
3170
		} elseif ( $plugins_install_path === $referer['path'] ) {
3171
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3172
			switch( $tab ) {
3173
				case 'popular':
3174
					$source_type = 'popular';
3175
					break;
3176
				case 'recommended':
3177
					$source_type = 'recommended';
3178
					break;
3179
				case 'favorites':
3180
					$source_type = 'favorites';
3181
					break;
3182
				case 'search':
3183
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3184
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3185
					break;
3186
				default:
3187
					$source_type = 'featured';
3188
			}
3189
		}
3190
3191
		return array( $source_type, $source_query );
3192
	}
3193
3194
	/**
3195
	 * Runs before bumping version numbers up to a new version
3196
	 * @param  string $version    Version:timestamp
3197
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3198
	 * @return null              [description]
3199
	 */
3200
	public static function do_version_bump( $version, $old_version ) {
3201
		if ( ! $old_version ) { // For new sites
3202
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3203
		}
3204
	}
3205
3206
	/**
3207
	 * Sets the internal version number and activation state.
3208
	 * @static
3209
	 */
3210
	public static function plugin_initialize() {
3211
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3212
			Jetpack_Options::update_option( 'activated', 2 );
3213
		}
3214
3215 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3216
			$version = $old_version = JETPACK__VERSION . ':' . time();
3217
			/** This action is documented in class.jetpack.php */
3218
			do_action( 'updating_jetpack_version', $version, false );
3219
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3220
		}
3221
3222
		Jetpack::load_modules();
3223
3224
		Jetpack_Options::delete_option( 'do_activate' );
3225
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3226
	}
3227
3228
	/**
3229
	 * Removes all connection options
3230
	 * @static
3231
	 */
3232
	public static function plugin_deactivation( ) {
3233
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3234
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3235
			Jetpack_Network::init()->deactivate();
3236
		} else {
3237
			Jetpack::disconnect( false );
3238
			//Jetpack_Heartbeat::init()->deactivate();
3239
		}
3240
	}
3241
3242
	/**
3243
	 * Disconnects from the Jetpack servers.
3244
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3245
	 * @static
3246
	 */
3247
	public static function disconnect( $update_activated_state = true ) {
3248
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3249
		Jetpack::clean_nonces( true );
3250
3251
		// If the site is in an IDC because sync is not allowed,
3252
		// let's make sure to not disconnect the production site.
3253
		if ( ! self::validate_sync_error_idc_option() ) {
3254
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3255
			Jetpack::load_xml_rpc_client();
3256
			$xml = new Jetpack_IXR_Client();
3257
			$xml->query( 'jetpack.deregister' );
3258
		}
3259
3260
		Jetpack_Options::delete_option(
3261
			array(
3262
				'blog_token',
3263
				'user_token',
3264
				'user_tokens',
3265
				'master_user',
3266
				'time_diff',
3267
				'fallback_no_verify_ssl_certs',
3268
			)
3269
		);
3270
3271
		Jetpack_IDC::clear_all_idc_options();
3272
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3273
3274
		if ( $update_activated_state ) {
3275
			Jetpack_Options::update_option( 'activated', 4 );
3276
		}
3277
3278
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3279
			// Check then record unique disconnection if site has never been disconnected previously
3280
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3281
				$jetpack_unique_connection['disconnected'] = 1;
3282
			} else {
3283
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3284
					//track unique disconnect
3285
					$jetpack = Jetpack::init();
3286
3287
					$jetpack->stat( 'connections', 'unique-disconnect' );
3288
					$jetpack->do_stats( 'server_side' );
3289
				}
3290
				// increment number of times disconnected
3291
				$jetpack_unique_connection['disconnected'] += 1;
3292
			}
3293
3294
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3295
		}
3296
3297
		// Delete cached connected user data
3298
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3299
		delete_transient( $transient_key );
3300
3301
		// Delete all the sync related data. Since it could be taking up space.
3302
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3303
		Jetpack_Sync_Sender::get_instance()->uninstall();
3304
3305
		// Disable the Heartbeat cron
3306
		Jetpack_Heartbeat::init()->deactivate();
3307
	}
3308
3309
	/**
3310
	 * Unlinks the current user from the linked WordPress.com user
3311
	 */
3312
	public static function unlink_user( $user_id = null ) {
3313
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3314
			return false;
3315
3316
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3317
3318
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3319
			return false;
3320
3321
		if ( ! isset( $tokens[ $user_id ] ) )
3322
			return false;
3323
3324
		Jetpack::load_xml_rpc_client();
3325
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3326
		$xml->query( 'jetpack.unlink_user', $user_id );
3327
3328
		unset( $tokens[ $user_id ] );
3329
3330
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3331
3332
		/**
3333
		 * Fires after the current user has been unlinked from WordPress.com.
3334
		 *
3335
		 * @since 4.1.0
3336
		 *
3337
		 * @param int $user_id The current user's ID.
3338
		 */
3339
		do_action( 'jetpack_unlinked_user', $user_id );
3340
3341
		return true;
3342
	}
3343
3344
	/**
3345
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3346
	 */
3347
	public static function try_registration() {
3348
		// The user has agreed to the TOS at some point by now.
3349
		Jetpack_Options::update_option( 'tos_agreed', true );
3350
3351
		// Let's get some testing in beta versions and such.
3352
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3353
			// Before attempting to connect, let's make sure that the domains are viable.
3354
			$domains_to_check = array_unique( array(
3355
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3356
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3357
			) );
3358
			foreach ( $domains_to_check as $domain ) {
3359
				$result = Jetpack_Data::is_usable_domain( $domain );
3360
				if ( is_wp_error( $result ) ) {
3361
					return $result;
3362
				}
3363
			}
3364
		}
3365
3366
		$result = Jetpack::register();
3367
3368
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3369
		if ( ! $result || is_wp_error( $result ) ) {
3370
			return $result;
3371
		} else {
3372
			return true;
3373
		}
3374
	}
3375
3376
	/**
3377
	 * Tracking an internal event log. Try not to put too much chaff in here.
3378
	 *
3379
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3380
	 */
3381
	public static function log( $code, $data = null ) {
3382
		// only grab the latest 200 entries
3383
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3384
3385
		// Append our event to the log
3386
		$log_entry = array(
3387
			'time'    => time(),
3388
			'user_id' => get_current_user_id(),
3389
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3390
			'code'    => $code,
3391
		);
3392
		// Don't bother storing it unless we've got some.
3393
		if ( ! is_null( $data ) ) {
3394
			$log_entry['data'] = $data;
3395
		}
3396
		$log[] = $log_entry;
3397
3398
		// Try add_option first, to make sure it's not autoloaded.
3399
		// @todo: Add an add_option method to Jetpack_Options
3400
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3401
			Jetpack_Options::update_option( 'log', $log );
3402
		}
3403
3404
		/**
3405
		 * Fires when Jetpack logs an internal event.
3406
		 *
3407
		 * @since 3.0.0
3408
		 *
3409
		 * @param array $log_entry {
3410
		 *	Array of details about the log entry.
3411
		 *
3412
		 *	@param string time Time of the event.
3413
		 *	@param int user_id ID of the user who trigerred the event.
3414
		 *	@param int blog_id Jetpack Blog ID.
3415
		 *	@param string code Unique name for the event.
3416
		 *	@param string data Data about the event.
3417
		 * }
3418
		 */
3419
		do_action( 'jetpack_log_entry', $log_entry );
3420
	}
3421
3422
	/**
3423
	 * Get the internal event log.
3424
	 *
3425
	 * @param $event (string) - only return the specific log events
3426
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3427
	 *
3428
	 * @return array of log events || WP_Error for invalid params
3429
	 */
3430
	public static function get_log( $event = false, $num = false ) {
3431
		if ( $event && ! is_string( $event ) ) {
3432
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3433
		}
3434
3435
		if ( $num && ! is_numeric( $num ) ) {
3436
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3437
		}
3438
3439
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3440
3441
		// If nothing set - act as it did before, otherwise let's start customizing the output
3442
		if ( ! $num && ! $event ) {
3443
			return $entire_log;
3444
		} else {
3445
			$entire_log = array_reverse( $entire_log );
3446
		}
3447
3448
		$custom_log_output = array();
3449
3450
		if ( $event ) {
3451
			foreach ( $entire_log as $log_event ) {
3452
				if ( $event == $log_event[ 'code' ] ) {
3453
					$custom_log_output[] = $log_event;
3454
				}
3455
			}
3456
		} else {
3457
			$custom_log_output = $entire_log;
3458
		}
3459
3460
		if ( $num ) {
3461
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3462
		}
3463
3464
		return $custom_log_output;
3465
	}
3466
3467
	/**
3468
	 * Log modification of important settings.
3469
	 */
3470
	public static function log_settings_change( $option, $old_value, $value ) {
3471
		switch( $option ) {
3472
			case 'jetpack_sync_non_public_post_stati':
3473
				self::log( $option, $value );
3474
				break;
3475
		}
3476
	}
3477
3478
	/**
3479
	 * Return stat data for WPCOM sync
3480
	 */
3481
	public static function get_stat_data( $encode = true, $extended = true ) {
3482
		$data = Jetpack_Heartbeat::generate_stats_array();
3483
3484
		if ( $extended ) {
3485
			$additional_data = self::get_additional_stat_data();
3486
			$data = array_merge( $data, $additional_data );
3487
		}
3488
3489
		if ( $encode ) {
3490
			return json_encode( $data );
3491
		}
3492
3493
		return $data;
3494
	}
3495
3496
	/**
3497
	 * Get additional stat data to sync to WPCOM
3498
	 */
3499
	public static function get_additional_stat_data( $prefix = '' ) {
3500
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3501
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3502
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3503
		$return["{$prefix}site-count"]     = 0;
3504
3505
		if ( function_exists( 'get_blog_count' ) ) {
3506
			$return["{$prefix}site-count"] = get_blog_count();
3507
		}
3508
		return $return;
3509
	}
3510
3511
	private static function get_site_user_count() {
3512
		global $wpdb;
3513
3514
		if ( function_exists( 'wp_is_large_network' ) ) {
3515
			if ( wp_is_large_network( 'users' ) ) {
3516
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3517
			}
3518
		}
3519 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3520
			// It wasn't there, so regenerate the data and save the transient
3521
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3522
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3523
		}
3524
		return $user_count;
3525
	}
3526
3527
	/* Admin Pages */
3528
3529
	function admin_init() {
3530
		// If the plugin is not connected, display a connect message.
3531
		if (
3532
			// the plugin was auto-activated and needs its candy
3533
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3534
		||
3535
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3536
			! Jetpack_Options::get_option( 'activated' )
3537
		) {
3538
			Jetpack::plugin_initialize();
3539
		}
3540
3541
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3542
			Jetpack_Connection_Banner::init();
3543
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3544
			// Upgrade: 1.1 -> 1.1.1
3545
			// Check and see if host can verify the Jetpack servers' SSL certificate
3546
			$args = array();
3547
			Jetpack_Client::_wp_remote_request(
3548
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3549
				$args,
3550
				true
3551
			);
3552
		}
3553
3554
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3555
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3556
		}
3557
3558
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3559
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3560
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3561
3562
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3563
			// Artificially throw errors in certain whitelisted cases during plugin activation
3564
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3565
		}
3566
3567
		// Add custom column in wp-admin/users.php to show whether user is linked.
3568
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3569
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3570
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3571
	}
3572
3573
	function admin_body_class( $admin_body_class = '' ) {
3574
		$classes = explode( ' ', trim( $admin_body_class ) );
3575
3576
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3577
3578
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3579
		return " $admin_body_class ";
3580
	}
3581
3582
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3583
		return $admin_body_class . ' jetpack-pagestyles ';
3584
	}
3585
3586
	/**
3587
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3588
	 * This function artificially throws errors for such cases (whitelisted).
3589
	 *
3590
	 * @param string $plugin The activated plugin.
3591
	 */
3592
	function throw_error_on_activate_plugin( $plugin ) {
3593
		$active_modules = Jetpack::get_active_modules();
3594
3595
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3596
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3597
			$throw = false;
3598
3599
			// Try and make sure it really was the stats plugin
3600
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3601
				if ( 'stats.php' == basename( $plugin ) ) {
3602
					$throw = true;
3603
				}
3604
			} else {
3605
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3606
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3607
					$throw = true;
3608
				}
3609
			}
3610
3611
			if ( $throw ) {
3612
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3613
			}
3614
		}
3615
	}
3616
3617
	function intercept_plugin_error_scrape_init() {
3618
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3619
	}
3620
3621
	function intercept_plugin_error_scrape( $action, $result ) {
3622
		if ( ! $result ) {
3623
			return;
3624
		}
3625
3626
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3627
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3628
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3629
			}
3630
		}
3631
	}
3632
3633
	function add_remote_request_handlers() {
3634
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3635
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3636
	}
3637
3638
	function remote_request_handlers() {
3639
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3640
3641
		switch ( current_filter() ) {
3642
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3643
			$response = $this->upload_handler();
3644
			break;
3645
3646
		case 'wp_ajax_nopriv_jetpack_update_file' :
3647
			$response = $this->upload_handler( true );
3648
			break;
3649
		default :
3650
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3651
			break;
3652
		}
3653
3654
		if ( ! $response ) {
3655
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3656
		}
3657
3658
		if ( is_wp_error( $response ) ) {
3659
			$status_code       = $response->get_error_data();
3660
			$error             = $response->get_error_code();
3661
			$error_description = $response->get_error_message();
3662
3663
			if ( ! is_int( $status_code ) ) {
3664
				$status_code = 400;
3665
			}
3666
3667
			status_header( $status_code );
3668
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3669
		}
3670
3671
		status_header( 200 );
3672
		if ( true === $response ) {
3673
			exit;
3674
		}
3675
3676
		die( json_encode( (object) $response ) );
3677
	}
3678
3679
	/**
3680
	 * Uploads a file gotten from the global $_FILES.
3681
	 * If `$update_media_item` is true and `post_id` is defined
3682
	 * the attachment file of the media item (gotten through of the post_id)
3683
	 * will be updated instead of add a new one.
3684
	 *
3685
	 * @param  boolean $update_media_item - update media attachment
3686
	 * @return array - An array describing the uploadind files process
3687
	 */
3688
	function upload_handler( $update_media_item = false ) {
3689
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3690
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3691
		}
3692
3693
		$user = wp_authenticate( '', '' );
3694
		if ( ! $user || is_wp_error( $user ) ) {
3695
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3696
		}
3697
3698
		wp_set_current_user( $user->ID );
3699
3700
		if ( ! current_user_can( 'upload_files' ) ) {
3701
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3702
		}
3703
3704
		if ( empty( $_FILES ) ) {
3705
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3706
		}
3707
3708
		foreach ( array_keys( $_FILES ) as $files_key ) {
3709
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3710
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3711
			}
3712
		}
3713
3714
		$media_keys = array_keys( $_FILES['media'] );
3715
3716
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3717
		if ( ! $token || is_wp_error( $token ) ) {
3718
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3719
		}
3720
3721
		$uploaded_files = array();
3722
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3723
		unset( $GLOBALS['post'] );
3724
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3725
			$file = array();
3726
			foreach ( $media_keys as $media_key ) {
3727
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3728
			}
3729
3730
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3731
3732
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3733
			if ( $hmac_provided !== $hmac_file ) {
3734
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3735
				continue;
3736
			}
3737
3738
			$_FILES['.jetpack.upload.'] = $file;
3739
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3740
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3741
				$post_id = 0;
3742
			}
3743
3744
			if ( $update_media_item ) {
3745
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3746
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3747
				}
3748
3749
				$media_array = $_FILES['media'];
3750
3751
				$file_array['name'] = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3752
				$file_array['type'] = $media_array['type'][0];
3753
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3754
				$file_array['error'] = $media_array['error'][0];
3755
				$file_array['size'] = $media_array['size'][0];
3756
3757
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3758
3759
				if ( is_wp_error( $edited_media_item ) ) {
3760
					return $edited_media_item;
3761
				}
3762
3763
				$response = (object) array(
3764
					'id'   => (string) $post_id,
3765
					'file' => (string) $edited_media_item->post_title,
3766
					'url'  => (string) wp_get_attachment_url( $post_id ),
3767
					'type' => (string) $edited_media_item->post_mime_type,
3768
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3769
				);
3770
3771
				return (array) array( $response );
3772
			}
3773
3774
			$attachment_id = media_handle_upload(
3775
				'.jetpack.upload.',
3776
				$post_id,
3777
				array(),
3778
				array(
3779
					'action' => 'jetpack_upload_file',
3780
				)
3781
			);
3782
3783
			if ( ! $attachment_id ) {
3784
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3785
			} elseif ( is_wp_error( $attachment_id ) ) {
3786
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3787
			} else {
3788
				$attachment = get_post( $attachment_id );
3789
				$uploaded_files[$index] = (object) array(
3790
					'id'   => (string) $attachment_id,
3791
					'file' => $attachment->post_title,
3792
					'url'  => wp_get_attachment_url( $attachment_id ),
3793
					'type' => $attachment->post_mime_type,
3794
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3795
				);
3796
				// Zip files uploads are not supported unless they are done for installation purposed
3797
				// lets delete them in case something goes wrong in this whole process
3798
				if ( 'application/zip' === $attachment->post_mime_type ) {
3799
					// Schedule a cleanup for 2 hours from now in case of failed install.
3800
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3801
				}
3802
			}
3803
		}
3804
		if ( ! is_null( $global_post ) ) {
3805
			$GLOBALS['post'] = $global_post;
3806
		}
3807
3808
		return $uploaded_files;
3809
	}
3810
3811
	/**
3812
	 * Add help to the Jetpack page
3813
	 *
3814
	 * @since Jetpack (1.2.3)
3815
	 * @return false if not the Jetpack page
3816
	 */
3817
	function admin_help() {
3818
		$current_screen = get_current_screen();
3819
3820
		// Overview
3821
		$current_screen->add_help_tab(
3822
			array(
3823
				'id'		=> 'home',
3824
				'title'		=> __( 'Home', 'jetpack' ),
3825
				'content'	=>
3826
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3827
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3828
					'<p>' . __( 'On this page, you are able to view the modules available within Jetpack, learn more about them, and activate or deactivate them as needed.', 'jetpack' ) . '</p>',
3829
			)
3830
		);
3831
3832
		// Screen Content
3833
		if ( current_user_can( 'manage_options' ) ) {
3834
			$current_screen->add_help_tab(
3835
				array(
3836
					'id'		=> 'settings',
3837
					'title'		=> __( 'Settings', 'jetpack' ),
3838
					'content'	=>
3839
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3840
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3841
						'<ol>' .
3842
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3843
							'<li>' . __( 'Using the checkboxes next to each module, you can select multiple modules to toggle via the Bulk Actions menu at the top of the list.',	'jetpack' ) . '</li>' .
3844
						'</ol>' .
3845
						'<p>' . __( 'Using the tools on the right, you can search for specific modules, filter by module categories or which are active, or change the sorting order.', 'jetpack' ) . '</p>'
3846
				)
3847
			);
3848
		}
3849
3850
		// Help Sidebar
3851
		$current_screen->set_help_sidebar(
3852
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3853
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3854
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3855
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3856
		);
3857
	}
3858
3859
	function admin_menu_css() {
3860
		wp_enqueue_style( 'jetpack-icons' );
3861
	}
3862
3863
	function admin_menu_order() {
3864
		return true;
3865
	}
3866
3867 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3868
		$jp_menu_order = array();
3869
3870
		foreach ( $menu_order as $index => $item ) {
3871
			if ( $item != 'jetpack' ) {
3872
				$jp_menu_order[] = $item;
3873
			}
3874
3875
			if ( $index == 0 ) {
3876
				$jp_menu_order[] = 'jetpack';
3877
			}
3878
		}
3879
3880
		return $jp_menu_order;
3881
	}
3882
3883
	function admin_banner_styles() {
3884
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3885
3886 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3887
			wp_register_style(
3888
				'jetpack-dops-style',
3889
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3890
				array(),
3891
				JETPACK__VERSION
3892
			);
3893
		}
3894
3895
		wp_enqueue_style(
3896
			'jetpack',
3897
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3898
			array( 'jetpack-dops-style' ),
3899
			 JETPACK__VERSION . '-20121016'
3900
		);
3901
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3902
		wp_style_add_data( 'jetpack', 'suffix', $min );
3903
	}
3904
3905
	function plugin_action_links( $actions ) {
3906
3907
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3908
3909
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3910
			return array_merge(
3911
				$jetpack_home,
3912
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3913
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3914
				$actions
3915
				);
3916
			}
3917
3918
		return array_merge( $jetpack_home, $actions );
3919
	}
3920
3921
	/*
3922
	 * Registration flow:
3923
	 * 1 - ::admin_page_load() action=register
3924
	 * 2 - ::try_registration()
3925
	 * 3 - ::register()
3926
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3927
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3928
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3929
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3930
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3931
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3932
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3933
	 *       jetpack_id, jetpack_secret, jetpack_public
3934
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3935
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3936
	 * 5 - user logs in with WP.com account
3937
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3938
	 *		- Jetpack_Client_Server::authorize()
3939
	 *		- Jetpack_Client_Server::get_token()
3940
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3941
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3942
	 *			- which responds with access_token, token_type, scope
3943
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3944
	 *		- Jetpack::activate_default_modules()
3945
	 *     		- Deactivates deprecated plugins
3946
	 *     		- Activates all default modules
3947
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3948
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3949
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3950
	 *     Done!
3951
	 */
3952
3953
	/**
3954
	 * Handles the page load events for the Jetpack admin page
3955
	 */
3956
	function admin_page_load() {
3957
		$error = false;
3958
3959
		// Make sure we have the right body class to hook stylings for subpages off of.
3960
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3961
3962
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3963
			// Should only be used in intermediate redirects to preserve state across redirects
3964
			Jetpack::restate();
3965
		}
3966
3967
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3968
			// @todo: Add validation against a known whitelist
3969
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3970
			// User clicked in the iframe to link their accounts
3971
			if ( ! Jetpack::is_user_connected() ) {
3972
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3973
3974
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3975
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3976
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3977
3978
				if ( isset( $_GET['notes_iframe'] ) )
3979
					$connect_url .= '&notes_iframe';
3980
				wp_redirect( $connect_url );
3981
				exit;
3982
			} else {
3983
				if ( ! isset( $_GET['calypso_env'] ) ) {
3984
					Jetpack::state( 'message', 'already_authorized' );
3985
					wp_safe_redirect( Jetpack::admin_url() );
3986
					exit;
3987
				} else {
3988
					$connect_url = $this->build_connect_url( true, false, $from );
3989
					$connect_url .= '&already_authorized=true';
3990
					wp_redirect( $connect_url );
3991
					exit;
3992
				}
3993
			}
3994
		}
3995
3996
3997
		if ( isset( $_GET['action'] ) ) {
3998
			switch ( $_GET['action'] ) {
3999
			case 'authorize':
4000
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4001
					Jetpack::state( 'message', 'already_authorized' );
4002
					wp_safe_redirect( Jetpack::admin_url() );
4003
					exit;
4004
				}
4005
				Jetpack::log( 'authorize' );
4006
				$client_server = new Jetpack_Client_Server;
4007
				$client_server->client_authorize();
4008
				exit;
4009
			case 'register' :
4010
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4011
					$error = 'cheatin';
4012
					break;
4013
				}
4014
				check_admin_referer( 'jetpack-register' );
4015
				Jetpack::log( 'register' );
4016
				Jetpack::maybe_set_version_option();
4017
				$registered = Jetpack::try_registration();
4018
				if ( is_wp_error( $registered ) ) {
4019
					$error = $registered->get_error_code();
4020
					Jetpack::state( 'error', $error );
4021
					Jetpack::state( 'error', $registered->get_error_message() );
4022
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4023
						'error_code' => $error,
4024
						'error_message' => $registered->get_error_message()
4025
					) );
4026
					break;
4027
				}
4028
4029
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4030
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4031
4032
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4033
					'from' => $from
4034
				) );
4035
4036
				$url = $this->build_connect_url( true, $redirect, $from );
4037
4038
				if ( ! empty( $_GET['onboarding'] ) ) {
4039
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4040
				}
4041
4042
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4043
					$url = add_query_arg( 'auth_approved', 'true', $url );
4044
				}
4045
4046
				wp_redirect( $url );
4047
				exit;
4048
			case 'activate' :
4049
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4050
					$error = 'cheatin';
4051
					break;
4052
				}
4053
4054
				$module = stripslashes( $_GET['module'] );
4055
				check_admin_referer( "jetpack_activate-$module" );
4056
				Jetpack::log( 'activate', $module );
4057
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4058
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4059
				}
4060
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4061
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4062
				exit;
4063
			case 'activate_default_modules' :
4064
				check_admin_referer( 'activate_default_modules' );
4065
				Jetpack::log( 'activate_default_modules' );
4066
				Jetpack::restate();
4067
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4068
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4069
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4070
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4071
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4072
				exit;
4073
			case 'disconnect' :
4074
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4075
					$error = 'cheatin';
4076
					break;
4077
				}
4078
4079
				check_admin_referer( 'jetpack-disconnect' );
4080
				Jetpack::log( 'disconnect' );
4081
				Jetpack::disconnect();
4082
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4083
				exit;
4084
			case 'reconnect' :
4085
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4086
					$error = 'cheatin';
4087
					break;
4088
				}
4089
4090
				check_admin_referer( 'jetpack-reconnect' );
4091
				Jetpack::log( 'reconnect' );
4092
				$this->disconnect();
4093
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4094
				exit;
4095 View Code Duplication
			case 'deactivate' :
4096
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4097
					$error = 'cheatin';
4098
					break;
4099
				}
4100
4101
				$modules = stripslashes( $_GET['module'] );
4102
				check_admin_referer( "jetpack_deactivate-$modules" );
4103
				foreach ( explode( ',', $modules ) as $module ) {
4104
					Jetpack::log( 'deactivate', $module );
4105
					Jetpack::deactivate_module( $module );
4106
					Jetpack::state( 'message', 'module_deactivated' );
4107
				}
4108
				Jetpack::state( 'module', $modules );
4109
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4110
				exit;
4111
			case 'unlink' :
4112
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4113
				check_admin_referer( 'jetpack-unlink' );
4114
				Jetpack::log( 'unlink' );
4115
				$this->unlink_user();
4116
				Jetpack::state( 'message', 'unlinked' );
4117
				if ( 'sub-unlink' == $redirect ) {
4118
					wp_safe_redirect( admin_url() );
4119
				} else {
4120
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4121
				}
4122
				exit;
4123
			case 'onboard' :
4124
				if ( ! current_user_can( 'manage_options' ) ) {
4125
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4126
				} else {
4127
					Jetpack::create_onboarding_token();
4128
					$url = $this->build_connect_url( true );
4129
4130
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4131
						$url = add_query_arg( 'onboarding', $token, $url );
4132
					}
4133
4134
					$calypso_env = $this->get_calypso_env();
4135
					if ( ! empty( $calypso_env ) ) {
4136
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4137
					}
4138
4139
					wp_redirect( $url );
4140
					exit;
4141
				}
4142
				exit;
4143
			default:
4144
				/**
4145
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4146
				 *
4147
				 * @since 2.6.0
4148
				 *
4149
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4150
				 */
4151
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4152
			}
4153
		}
4154
4155
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4156
			self::activate_new_modules( true );
4157
		}
4158
4159
		$message_code = Jetpack::state( 'message' );
4160
		if ( Jetpack::state( 'optin-manage' ) ) {
4161
			$activated_manage = $message_code;
4162
			$message_code = 'jetpack-manage';
4163
		}
4164
4165
		switch ( $message_code ) {
4166
		case 'jetpack-manage':
4167
			$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
4168
			if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4169
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4170
			}
4171
			break;
4172
4173
		}
4174
4175
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4176
4177
		if ( ! empty( $deactivated_plugins ) ) {
4178
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4179
			$deactivated_titles  = array();
4180
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4181
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4182
					continue;
4183
				}
4184
4185
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4186
			}
4187
4188
			if ( $deactivated_titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4189
				if ( $this->message ) {
4190
					$this->message .= "<br /><br />\n";
4191
				}
4192
4193
				$this->message .= wp_sprintf(
4194
					_n(
4195
						'Jetpack contains the most recent version of the old %l plugin.',
4196
						'Jetpack contains the most recent versions of the old %l plugins.',
4197
						count( $deactivated_titles ),
4198
						'jetpack'
4199
					),
4200
					$deactivated_titles
4201
				);
4202
4203
				$this->message .= "<br />\n";
4204
4205
				$this->message .= _n(
4206
					'The old version has been deactivated and can be removed from your site.',
4207
					'The old versions have been deactivated and can be removed from your site.',
4208
					count( $deactivated_titles ),
4209
					'jetpack'
4210
				);
4211
			}
4212
		}
4213
4214
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4215
4216
		if ( $this->message || $this->error || $this->privacy_checks ) {
4217
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4218
		}
4219
4220
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4221
	}
4222
4223
	function admin_notices() {
4224
4225
		if ( $this->error ) {
4226
?>
4227
<div id="message" class="jetpack-message jetpack-err">
4228
	<div class="squeezer">
4229
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4230
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4231
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4232
<?php	endif; ?>
4233
	</div>
4234
</div>
4235
<?php
4236
		}
4237
4238
		if ( $this->message ) {
4239
?>
4240
<div id="message" class="jetpack-message">
4241
	<div class="squeezer">
4242
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4243
	</div>
4244
</div>
4245
<?php
4246
		}
4247
4248
		if ( $this->privacy_checks ) :
4249
			$module_names = $module_slugs = array();
4250
4251
			$privacy_checks = explode( ',', $this->privacy_checks );
4252
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4253
			foreach ( $privacy_checks as $module_slug ) {
4254
				$module = Jetpack::get_module( $module_slug );
4255
				if ( ! $module ) {
4256
					continue;
4257
				}
4258
4259
				$module_slugs[] = $module_slug;
4260
				$module_names[] = "<strong>{$module['name']}</strong>";
4261
			}
4262
4263
			$module_slugs = join( ',', $module_slugs );
4264
?>
4265
<div id="message" class="jetpack-message jetpack-err">
4266
	<div class="squeezer">
4267
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4268
		<p><?php
4269
			echo wp_kses(
4270
				wptexturize(
4271
					wp_sprintf(
4272
						_nx(
4273
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4274
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4275
							count( $privacy_checks ),
4276
							'%l = list of Jetpack module/feature names',
4277
							'jetpack'
4278
						),
4279
						$module_names
4280
					)
4281
				),
4282
				array( 'strong' => true )
4283
			);
4284
4285
			echo "\n<br />\n";
4286
4287
			echo wp_kses(
4288
				sprintf(
4289
					_nx(
4290
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4291
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4292
						count( $privacy_checks ),
4293
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4294
						'jetpack'
4295
					),
4296
					wp_nonce_url(
4297
						Jetpack::admin_url(
4298
							array(
4299
								'page'   => 'jetpack',
4300
								'action' => 'deactivate',
4301
								'module' => urlencode( $module_slugs ),
4302
							)
4303
						),
4304
						"jetpack_deactivate-$module_slugs"
4305
					),
4306
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4307
				),
4308
				array( 'a' => array( 'href' => true, 'title' => true ) )
4309
			);
4310
		?></p>
4311
	</div>
4312
</div>
4313
<?php endif;
4314
	}
4315
4316
	/**
4317
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4318
	 */
4319
	function stat( $group, $detail ) {
4320
		if ( ! isset( $this->stats[ $group ] ) )
4321
			$this->stats[ $group ] = array();
4322
		$this->stats[ $group ][] = $detail;
4323
	}
4324
4325
	/**
4326
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4327
	 */
4328
	function do_stats( $method = '' ) {
4329
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4330
			foreach ( $this->stats as $group => $stats ) {
4331
				if ( is_array( $stats ) && count( $stats ) ) {
4332
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4333
					if ( 'server_side' === $method ) {
4334
						self::do_server_side_stat( $args );
4335
					} else {
4336
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4337
					}
4338
				}
4339
				unset( $this->stats[ $group ] );
4340
			}
4341
		}
4342
	}
4343
4344
	/**
4345
	 * Runs stats code for a one-off, server-side.
4346
	 *
4347
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4348
	 *
4349
	 * @return bool If it worked.
4350
	 */
4351
	static function do_server_side_stat( $args ) {
4352
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4353
		if ( is_wp_error( $response ) )
4354
			return false;
4355
4356
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4357
			return false;
4358
4359
		return true;
4360
	}
4361
4362
	/**
4363
	 * Builds the stats url.
4364
	 *
4365
	 * @param $args array|string The arguments to append to the URL.
4366
	 *
4367
	 * @return string The URL to be pinged.
4368
	 */
4369
	static function build_stats_url( $args ) {
4370
		$defaults = array(
4371
			'v'    => 'wpcom2',
4372
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4373
		);
4374
		$args     = wp_parse_args( $args, $defaults );
4375
		/**
4376
		 * Filter the URL used as the Stats tracking pixel.
4377
		 *
4378
		 * @since 2.3.2
4379
		 *
4380
		 * @param string $url Base URL used as the Stats tracking pixel.
4381
		 */
4382
		$base_url = apply_filters(
4383
			'jetpack_stats_base_url',
4384
			'https://pixel.wp.com/g.gif'
4385
		);
4386
		$url      = add_query_arg( $args, $base_url );
4387
		return $url;
4388
	}
4389
4390
	static function translate_current_user_to_role() {
4391
		foreach ( self::$capability_translations as $role => $cap ) {
4392
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4393
				return $role;
4394
			}
4395
		}
4396
4397
		return false;
4398
	}
4399
4400
	static function translate_user_to_role( $user ) {
4401
		foreach ( self::$capability_translations as $role => $cap ) {
4402
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4403
				return $role;
4404
			}
4405
		}
4406
4407
		return false;
4408
    }
4409
4410
	static function translate_role_to_cap( $role ) {
4411
		if ( ! isset( self::$capability_translations[$role] ) ) {
4412
			return false;
4413
		}
4414
4415
		return self::$capability_translations[$role];
4416
	}
4417
4418
	static function sign_role( $role, $user_id = null ) {
4419
		if ( empty( $user_id ) ) {
4420
			$user_id = (int) get_current_user_id();
4421
		}
4422
4423
		if ( ! $user_id  ) {
4424
			return false;
4425
		}
4426
4427
		$token = Jetpack_Data::get_access_token();
4428
		if ( ! $token || is_wp_error( $token ) ) {
4429
			return false;
4430
		}
4431
4432
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4433
	}
4434
4435
4436
	/**
4437
	 * Builds a URL to the Jetpack connection auth page
4438
	 *
4439
	 * @since 3.9.5
4440
	 *
4441
	 * @param bool $raw If true, URL will not be escaped.
4442
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4443
	 *                              If string, will be a custom redirect.
4444
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4445
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4446
	 *
4447
	 * @return string Connect URL
4448
	 */
4449
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4450
		$site_id = Jetpack_Options::get_option( 'id' );
4451
		$blog_token = Jetpack_Data::get_access_token();
4452
4453
		if ( $register || ! $blog_token || ! $site_id ) {
4454
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4455
4456
			if ( ! empty( $redirect ) ) {
4457
				$url = add_query_arg(
4458
					'redirect',
4459
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4460
					$url
4461
				);
4462
			}
4463
4464
			if( is_network_admin() ) {
4465
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4466
			}
4467
		} else {
4468
4469
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4470
			// because otherwise this logic can get us in to a loop.
4471
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4472
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4473
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4474
4475
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4476
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4477
					'1.1'
4478
				);
4479
4480
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4481
4482
					// Generating a register URL instead to refresh the existing token
4483
					return $this->build_connect_url( $raw, $redirect, $from, true );
4484
				}
4485
			}
4486
4487
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4488
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4489
			}
4490
4491
			$role = self::translate_current_user_to_role();
4492
			$signed_role = self::sign_role( $role );
4493
4494
			$user = wp_get_current_user();
4495
4496
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4497
			$redirect = $redirect
4498
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4499
				: $jetpack_admin_page;
4500
4501
			if( isset( $_REQUEST['is_multisite'] ) ) {
4502
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4503
			}
4504
4505
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4506
4507
			/**
4508
			 * Filter the type of authorization.
4509
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4510
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4511
			 *
4512
			 * @since 4.3.3
4513
			 *
4514
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4515
			 */
4516
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4517
4518
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4519
4520
			$args = urlencode_deep(
4521
				array(
4522
					'response_type' => 'code',
4523
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4524
					'redirect_uri'  => add_query_arg(
4525
						array(
4526
							'action'   => 'authorize',
4527
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4528
							'redirect' => urlencode( $redirect ),
4529
						),
4530
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4531
					),
4532
					'state'         => $user->ID,
4533
					'scope'         => $signed_role,
4534
					'user_email'    => $user->user_email,
4535
					'user_login'    => $user->user_login,
4536
					'is_active'     => Jetpack::is_active(),
4537
					'jp_version'    => JETPACK__VERSION,
4538
					'auth_type'     => $auth_type,
4539
					'secret'        => $secrets['secret_1'],
4540
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4541
					'blogname'      => get_option( 'blogname' ),
4542
					'site_url'      => site_url(),
4543
					'home_url'      => home_url(),
4544
					'site_icon'     => get_site_icon_url(),
4545
					'site_lang'     => get_locale(),
4546
					'_ui'           => $tracks_identity['_ui'],
4547
					'_ut'           => $tracks_identity['_ut'],
4548
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4549
				)
4550
			);
4551
4552
			self::apply_activation_source_to_args( $args );
4553
4554
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4555
		}
4556
4557
		if ( $from ) {
4558
			$url = add_query_arg( 'from', $from, $url );
4559
		}
4560
4561
		// Ensure that class to get the affiliate code is loaded
4562
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4563
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4564
		}
4565
		// Get affiliate code and add it to the URL
4566
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4567
4568
		$calypso_env = $this->get_calypso_env();
4569
4570
		if ( ! empty( $calypso_env ) ) {
4571
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4572
		}
4573
4574
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4575
	}
4576
4577
	/**
4578
	 * Get our assumed site creation date.
4579
	 * Calculated based on the earlier date of either:
4580
	 * - Earliest admin user registration date.
4581
	 * - Earliest date of post of any post type.
4582
	 *
4583
	 * @since 7.2.0
4584
	 *
4585
	 * @return string Assumed site creation date and time.
4586
	 */
4587
	public static function get_assumed_site_creation_date() {
4588
		$earliest_registered_users = get_users( array(
4589
			'role'    => 'administrator',
4590
			'orderby' => 'user_registered',
4591
			'order'   => 'ASC',
4592
			'fields'  => array( 'user_registered' ),
4593
			'number'  => 1,
4594
		) );
4595
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4596
4597
		$earliest_posts = get_posts( array(
4598
			'posts_per_page' => 1,
4599
			'post_type'      => 'any',
4600
			'post_status'    => 'any',
4601
			'orderby'        => 'date',
4602
			'order'          => 'ASC',
4603
		) );
4604
4605
		// If there are no posts at all, we'll count only on user registration date.
4606
		if ( $earliest_posts ) {
4607
			$earliest_post_date = $earliest_posts[0]->post_date;
4608
		} else {
4609
			$earliest_post_date = PHP_INT_MAX;
4610
		}
4611
4612
		return min( $earliest_registration_date, $earliest_post_date );
4613
	}
4614
4615
	public static function apply_activation_source_to_args( &$args ) {
4616
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4617
4618
		if ( $activation_source_name ) {
4619
			$args['_as'] = urlencode( $activation_source_name );
4620
		}
4621
4622
		if ( $activation_source_keyword ) {
4623
			$args['_ak'] = urlencode( $activation_source_keyword );
4624
		}
4625
	}
4626
4627
	function build_reconnect_url( $raw = false ) {
4628
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4629
		return $raw ? $url : esc_url( $url );
4630
	}
4631
4632
	public static function admin_url( $args = null ) {
4633
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4634
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4635
		return $url;
4636
	}
4637
4638
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4639
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4640
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4641
	}
4642
4643
	function dismiss_jetpack_notice() {
4644
4645
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4646
			return;
4647
		}
4648
4649
		switch( $_GET['jetpack-notice'] ) {
4650
			case 'dismiss':
4651
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4652
4653
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4654
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4655
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4656
				}
4657
				break;
4658
			case 'jetpack-protect-multisite-opt-out':
4659
4660
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4661
					// Don't show the banner again
4662
4663
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4664
					// redirect back to the page that had the notice
4665
					if ( wp_get_referer() ) {
4666
						wp_safe_redirect( wp_get_referer() );
4667
					} else {
4668
						// Take me to Jetpack
4669
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4670
					}
4671
				}
4672
				break;
4673
		}
4674
	}
4675
4676
	public static function sort_modules( $a, $b ) {
4677
		if ( $a['sort'] == $b['sort'] )
4678
			return 0;
4679
4680
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4681
	}
4682
4683
	function ajax_recheck_ssl() {
4684
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4685
		$result = Jetpack::permit_ssl( true );
4686
		wp_send_json( array(
4687
			'enabled' => $result,
4688
			'message' => get_transient( 'jetpack_https_test_message' )
4689
		) );
4690
	}
4691
4692
/* Client API */
4693
4694
	/**
4695
	 * Returns the requested Jetpack API URL
4696
	 *
4697
	 * @return string
4698
	 */
4699
	public static function api_url( $relative_url ) {
4700
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4701
	}
4702
4703
	/**
4704
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4705
	 */
4706
	public static function fix_url_for_bad_hosts( $url ) {
4707
		if ( 0 !== strpos( $url, 'https://' ) ) {
4708
			return $url;
4709
		}
4710
4711
		switch ( JETPACK_CLIENT__HTTPS ) {
4712
			case 'ALWAYS' :
4713
				return $url;
4714
			case 'NEVER' :
4715
				return set_url_scheme( $url, 'http' );
4716
			// default : case 'AUTO' :
4717
		}
4718
4719
		// we now return the unmodified SSL URL by default, as a security precaution
4720
		return $url;
4721
	}
4722
4723
	/**
4724
	 * Create a random secret for validating onboarding payload
4725
	 *
4726
	 * @return string Secret token
4727
	 */
4728
	public static function create_onboarding_token() {
4729
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4730
			$token = wp_generate_password( 32, false );
4731
			Jetpack_Options::update_option( 'onboarding', $token );
4732
		}
4733
4734
		return $token;
4735
	}
4736
4737
	/**
4738
	 * Remove the onboarding token
4739
	 *
4740
	 * @return bool True on success, false on failure
4741
	 */
4742
	public static function invalidate_onboarding_token() {
4743
		return Jetpack_Options::delete_option( 'onboarding' );
4744
	}
4745
4746
	/**
4747
	 * Validate an onboarding token for a specific action
4748
	 *
4749
	 * @return boolean True if token/action pair is accepted, false if not
4750
	 */
4751
	public static function validate_onboarding_token_action( $token, $action ) {
4752
		// Compare tokens, bail if tokens do not match
4753
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4754
			return false;
4755
		}
4756
4757
		// List of valid actions we can take
4758
		$valid_actions = array(
4759
			'/jetpack/v4/settings',
4760
		);
4761
4762
		// Whitelist the action
4763
		if ( ! in_array( $action, $valid_actions ) ) {
4764
			return false;
4765
		}
4766
4767
		return true;
4768
	}
4769
4770
	/**
4771
	 * Checks to see if the URL is using SSL to connect with Jetpack
4772
	 *
4773
	 * @since 2.3.3
4774
	 * @return boolean
4775
	 */
4776
	public static function permit_ssl( $force_recheck = false ) {
4777
		// Do some fancy tests to see if ssl is being supported
4778
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4779
			$message = '';
4780
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4781
				$ssl = 0;
4782
			} else {
4783
				switch ( JETPACK_CLIENT__HTTPS ) {
4784
					case 'NEVER':
4785
						$ssl = 0;
4786
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4787
						break;
4788
					case 'ALWAYS':
4789
					case 'AUTO':
4790
					default:
4791
						$ssl = 1;
4792
						break;
4793
				}
4794
4795
				// If it's not 'NEVER', test to see
4796
				if ( $ssl ) {
4797
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4798
						$ssl = 0;
4799
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4800
					} else {
4801
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4802
						if ( is_wp_error( $response ) ) {
4803
							$ssl = 0;
4804
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4805
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4806
							$ssl = 0;
4807
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4808
						}
4809
					}
4810
				}
4811
			}
4812
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4813
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4814
		}
4815
4816
		return (bool) $ssl;
4817
	}
4818
4819
	/*
4820
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4821
	 */
4822
	public function alert_auto_ssl_fail() {
4823
		if ( ! current_user_can( 'manage_options' ) )
4824
			return;
4825
4826
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4827
		?>
4828
4829
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4830
			<div class="jp-banner__content">
4831
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4832
				<p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
4833
				<p>
4834
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4835
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4836
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4837
				</p>
4838
				<p>
4839
					<?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4840
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4841
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4842
				</p>
4843
			</div>
4844
		</div>
4845
		<style>
4846
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4847
		</style>
4848
		<script type="text/javascript">
4849
			jQuery( document ).ready( function( $ ) {
4850
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4851
					var $this = $( this );
4852
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4853
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4854
					e.preventDefault();
4855
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4856
					$.post( ajaxurl, data )
4857
					  .done( function( response ) {
4858
					  	if ( response.enabled ) {
4859
					  		$( '#jetpack-ssl-warning' ).hide();
4860
					  	} else {
4861
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4862
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4863
					  	}
4864
					  }.bind( $this ) );
4865
				} );
4866
			} );
4867
		</script>
4868
4869
		<?php
4870
	}
4871
4872
	/**
4873
	 * Returns the Jetpack XML-RPC API
4874
	 *
4875
	 * @return string
4876
	 */
4877
	public static function xmlrpc_api_url() {
4878
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4879
		return untrailingslashit( $base ) . '/xmlrpc.php';
4880
	}
4881
4882
	/**
4883
	 * Creates two secret tokens and the end of life timestamp for them.
4884
	 *
4885
	 * Note these tokens are unique per call, NOT static per site for connecting.
4886
	 *
4887
	 * @since 2.6
4888
	 * @return array
4889
	 */
4890
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4891
		if ( false === $user_id ) {
4892
			$user_id = get_current_user_id();
4893
		}
4894
4895
		return self::init()->connection_manager->generate_secrets( $action, $user_id, $exp );
4896
	}
4897
4898
	public static function get_secrets( $action, $user_id ) {
4899
		$secrets = self::init()->connection_manager->get_secrets( $action, $user_id );
4900
4901
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4902
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4903
		}
4904
4905
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4906
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4907
		}
4908
4909
		return $secrets;
4910
	}
4911
4912
	public static function delete_secrets( $action, $user_id ) {
4913
		return self::init()->connection_manager->delete_secrets( $action, $user_id );
4914
	}
4915
4916
	/**
4917
	 * Builds the timeout limit for queries talking with the wpcom servers.
4918
	 *
4919
	 * Based on local php max_execution_time in php.ini
4920
	 *
4921
	 * @since 2.6
4922
	 * @return int
4923
	 * @deprecated
4924
	 **/
4925
	public function get_remote_query_timeout_limit() {
4926
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4927
		return Jetpack::get_max_execution_time();
4928
	}
4929
4930
	/**
4931
	 * Builds the timeout limit for queries talking with the wpcom servers.
4932
	 *
4933
	 * Based on local php max_execution_time in php.ini
4934
	 *
4935
	 * @since 5.4
4936
	 * @return int
4937
	 **/
4938
	public static function get_max_execution_time() {
4939
		$timeout = (int) ini_get( 'max_execution_time' );
4940
4941
		// Ensure exec time set in php.ini
4942
		if ( ! $timeout ) {
4943
			$timeout = 30;
4944
		}
4945
		return $timeout;
4946
	}
4947
4948
	/**
4949
	 * Sets a minimum request timeout, and returns the current timeout
4950
	 *
4951
	 * @since 5.4
4952
	 **/
4953
	public static function set_min_time_limit( $min_timeout ) {
4954
		$timeout = self::get_max_execution_time();
4955
		if ( $timeout < $min_timeout ) {
4956
			$timeout = $min_timeout;
4957
			set_time_limit( $timeout );
4958
		}
4959
		return $timeout;
4960
	}
4961
4962
4963
	/**
4964
	 * Takes the response from the Jetpack register new site endpoint and
4965
	 * verifies it worked properly.
4966
	 *
4967
	 * @since 2.6
4968
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4969
	 **/
4970
	public function validate_remote_register_response( $response ) {
4971
	  if ( is_wp_error( $response ) ) {
4972
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4973
		}
4974
4975
		$code   = wp_remote_retrieve_response_code( $response );
4976
		$entity = wp_remote_retrieve_body( $response );
4977
		if ( $entity )
4978
			$registration_response = json_decode( $entity );
4979
		else
4980
			$registration_response = false;
4981
4982
		$code_type = intval( $code / 100 );
4983
		if ( 5 == $code_type ) {
4984
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4985
		} elseif ( 408 == $code ) {
4986
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4987
		} elseif ( ! empty( $registration_response->error ) ) {
4988
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4989
				$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' );
4990
			} else {
4991
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4992
			}
4993
4994
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4995
		} elseif ( 200 != $code ) {
4996
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4997
		}
4998
4999
		// Jetpack ID error block
5000
		if ( empty( $registration_response->jetpack_id ) ) {
5001
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5002
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5003
			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 );
5004
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5005
			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 );
5006
		}
5007
5008
	    return $registration_response;
5009
	}
5010
	/**
5011
	 * @return bool|WP_Error
5012
	 */
5013
	public static function register() {
5014
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5015
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5016
		$secrets = Jetpack::generate_secrets( 'register' );
5017
5018 View Code Duplication
		if (
5019
			empty( $secrets['secret_1'] ) ||
5020
			empty( $secrets['secret_2'] ) ||
5021
			empty( $secrets['exp'] )
5022
		) {
5023
			return new Jetpack_Error( 'missing_secrets' );
5024
		}
5025
5026
		// better to try (and fail) to set a higher timeout than this system
5027
		// supports than to have register fail for more users than it should
5028
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5029
5030
		$gmt_offset = get_option( 'gmt_offset' );
5031
		if ( ! $gmt_offset ) {
5032
			$gmt_offset = 0;
5033
		}
5034
5035
		$stats_options = get_option( 'stats_options' );
5036
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5037
5038
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5039
5040
		$args = array(
5041
			'method'  => 'POST',
5042
			'body'    => array(
5043
				'siteurl'         => site_url(),
5044
				'home'            => home_url(),
5045
				'gmt_offset'      => $gmt_offset,
5046
				'timezone_string' => (string) get_option( 'timezone_string' ),
5047
				'site_name'       => (string) get_option( 'blogname' ),
5048
				'secret_1'        => $secrets['secret_1'],
5049
				'secret_2'        => $secrets['secret_2'],
5050
				'site_lang'       => get_locale(),
5051
				'timeout'         => $timeout,
5052
				'stats_id'        => $stats_id,
5053
				'state'           => get_current_user_id(),
5054
				'_ui'             => $tracks_identity['_ui'],
5055
				'_ut'             => $tracks_identity['_ut'],
5056
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5057
				'jetpack_version' => JETPACK__VERSION
5058
			),
5059
			'headers' => array(
5060
				'Accept' => 'application/json',
5061
			),
5062
			'timeout' => $timeout,
5063
		);
5064
5065
		self::apply_activation_source_to_args( $args['body'] );
5066
5067
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5068
5069
		// Make sure the response is valid and does not contain any Jetpack errors
5070
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5071
		if ( is_wp_error( $registration_details ) ) {
5072
			return $registration_details;
5073
		} elseif ( ! $registration_details ) {
5074
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5075
		}
5076
5077 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5078
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5079
		}
5080
5081
		if ( isset( $registration_details->jetpack_public ) ) {
5082
			$jetpack_public = (int) $registration_details->jetpack_public;
5083
		} else {
5084
			$jetpack_public = false;
5085
		}
5086
5087
		Jetpack_Options::update_options(
5088
			array(
5089
				'id'         => (int)    $registration_details->jetpack_id,
5090
				'blog_token' => (string) $registration_details->jetpack_secret,
5091
				'public'     => $jetpack_public,
5092
			)
5093
		);
5094
5095
		/**
5096
		 * Fires when a site is registered on WordPress.com.
5097
		 *
5098
		 * @since 3.7.0
5099
		 *
5100
		 * @param int $json->jetpack_id Jetpack Blog ID.
5101
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5102
		 * @param int|bool $jetpack_public Is the site public.
5103
		 */
5104
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5105
5106
		// Initialize Jump Start for the first and only time.
5107
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5108
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5109
5110
			$jetpack = Jetpack::init();
5111
5112
			$jetpack->stat( 'jumpstart', 'unique-views' );
5113
			$jetpack->do_stats( 'server_side' );
5114
		};
5115
5116
		return true;
5117
	}
5118
5119
	/**
5120
	 * If the db version is showing something other that what we've got now, bump it to current.
5121
	 *
5122
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5123
	 */
5124
	public static function maybe_set_version_option() {
5125
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5126
		if ( JETPACK__VERSION != $version ) {
5127
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5128
5129
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5130
				/** This action is documented in class.jetpack.php */
5131
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5132
			}
5133
5134
			return true;
5135
		}
5136
		return false;
5137
	}
5138
5139
/* Client Server API */
5140
5141
	/**
5142
	 * Loads the Jetpack XML-RPC client
5143
	 */
5144
	public static function load_xml_rpc_client() {
5145
		require_once ABSPATH . WPINC . '/class-IXR.php';
5146
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5147
	}
5148
5149
	/**
5150
	 * Resets the saved authentication state in between testing requests.
5151
	 */
5152
	public function reset_saved_auth_state() {
5153
		$this->xmlrpc_verification = null;
5154
		$this->rest_authentication_status = null;
5155
	}
5156
5157
	function verify_xml_rpc_signature() {
5158
		if ( $this->xmlrpc_verification ) {
5159
			return $this->xmlrpc_verification;
5160
		}
5161
5162
		// It's not for us
5163
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5164
			return false;
5165
		}
5166
5167
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5168
		if (
5169
			empty( $token_key )
5170
		||
5171
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5172
		) {
5173
			return false;
5174
		}
5175
5176
		if ( '0' === $user_id ) {
5177
			$token_type = 'blog';
5178
			$user_id = 0;
5179
		} else {
5180
			$token_type = 'user';
5181
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5182
				return false;
5183
			}
5184
			$user_id = (int) $user_id;
5185
5186
			$user = new WP_User( $user_id );
5187
			if ( ! $user || ! $user->exists() ) {
5188
				return false;
5189
			}
5190
		}
5191
5192
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
5193
		if ( ! $token ) {
5194
			return false;
5195
		}
5196
5197
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5198
5199
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5200
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5201
			$post_data   = $_POST;
5202
			$file_hashes = array();
5203
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5204
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5205
					continue;
5206
				}
5207
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5208
				$file_hashes[$post_data_key] = $post_data_value;
5209
			}
5210
5211
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5212
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5213
				$post_data[$post_data_key] = $post_data_value;
5214
			}
5215
5216
			ksort( $post_data );
5217
5218
			$body = http_build_query( stripslashes_deep( $post_data ) );
5219
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5220
			$body = file_get_contents( 'php://input' );
5221
		} else {
5222
			$body = null;
5223
		}
5224
5225
		$signature = $jetpack_signature->sign_current_request(
5226
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5227
		);
5228
5229
		if ( ! $signature ) {
5230
			return false;
5231
		} else if ( is_wp_error( $signature ) ) {
5232
			return $signature;
5233
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5234
			return false;
5235
		}
5236
5237
		$timestamp = (int) $_GET['timestamp'];
5238
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5239
5240
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5241
			return false;
5242
		}
5243
5244
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5245
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5246
			if ( ! empty( $_GET['onboarding'] ) ) {
5247
				$jpo = $_GET;
5248
			} else {
5249
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5250
			}
5251
5252
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5253
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5254
5255
			if (
5256
				isset( $jpo_user ) && isset( $jpo_token ) &&
5257
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5258
				isset( $_GET['rest_route'] ) &&
5259
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5260
			) {
5261
				$jpUser = get_user_by( 'email', $jpo_user );
5262
				if ( is_a( $jpUser, 'WP_User' ) ) {
5263
					wp_set_current_user( $jpUser->ID );
5264
					$user_can = is_multisite()
5265
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5266
						: current_user_can( 'manage_options' );
5267
					if ( $user_can ) {
5268
						$token_type = 'user';
5269
						$token->external_user_id = $jpUser->ID;
5270
					}
5271
				}
5272
			}
5273
		}
5274
5275
		$this->xmlrpc_verification = array(
5276
			'type'      => $token_type,
5277
			'token_key' => $token_key,
5278
			'user_id'   => $token->external_user_id,
5279
		);
5280
5281
		return $this->xmlrpc_verification;
5282
	}
5283
5284
	/**
5285
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5286
	 */
5287
	function authenticate_jetpack( $user, $username, $password ) {
5288
		if ( is_a( $user, 'WP_User' ) ) {
5289
			return $user;
5290
		}
5291
5292
		$token_details = $this->verify_xml_rpc_signature();
5293
5294
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5295
			return $user;
5296
		}
5297
5298
		if ( 'user' !== $token_details['type'] ) {
5299
			return $user;
5300
		}
5301
5302
		if ( ! $token_details['user_id'] ) {
5303
			return $user;
5304
		}
5305
5306
		nocache_headers();
5307
5308
		return new WP_User( $token_details['user_id'] );
5309
	}
5310
5311
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5312
	// Uses the existing XMLRPC request signing implementation.
5313
	function wp_rest_authenticate( $user ) {
5314
		if ( ! empty( $user ) ) {
5315
			// Another authentication method is in effect.
5316
			return $user;
5317
		}
5318
5319
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5320
			// Nothing to do for this authentication method.
5321
			return null;
5322
		}
5323
5324
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5325
			// Nothing to do for this authentication method.
5326
			return null;
5327
		}
5328
5329
		// Ensure that we always have the request body available.  At this
5330
		// point, the WP REST API code to determine the request body has not
5331
		// run yet.  That code may try to read from 'php://input' later, but
5332
		// this can only be done once per request in PHP versions prior to 5.6.
5333
		// So we will go ahead and perform this read now if needed, and save
5334
		// the request body where both the Jetpack signature verification code
5335
		// and the WP REST API code can see it.
5336
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5337
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5338
		}
5339
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5340
5341
		// Only support specific request parameters that have been tested and
5342
		// are known to work with signature verification.  A different method
5343
		// can be passed to the WP REST API via the '?_method=' parameter if
5344
		// needed.
5345
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5346
			$this->rest_authentication_status = new WP_Error(
5347
				'rest_invalid_request',
5348
				__( 'This request method is not supported.', 'jetpack' ),
5349
				array( 'status' => 400 )
5350
			);
5351
			return null;
5352
		}
5353
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5354
			$this->rest_authentication_status = new WP_Error(
5355
				'rest_invalid_request',
5356
				__( 'This request method does not support body parameters.', 'jetpack' ),
5357
				array( 'status' => 400 )
5358
			);
5359
			return null;
5360
		}
5361
5362
		$verified = $this->verify_xml_rpc_signature();
5363
5364
		if ( is_wp_error( $verified ) ) {
5365
			$this->rest_authentication_status = $verified;
5366
			return null;
5367
		}
5368
5369
		if (
5370
			$verified &&
5371
			isset( $verified['type'] ) &&
5372
			'user' === $verified['type'] &&
5373
			! empty( $verified['user_id'] )
5374
		) {
5375
			// Authentication successful.
5376
			$this->rest_authentication_status = true;
5377
			return $verified['user_id'];
5378
		}
5379
5380
		// Something else went wrong.  Probably a signature error.
5381
		$this->rest_authentication_status = new WP_Error(
5382
			'rest_invalid_signature',
5383
			__( 'The request is not signed correctly.', 'jetpack' ),
5384
			array( 'status' => 400 )
5385
		);
5386
		return null;
5387
	}
5388
5389
	/**
5390
	 * Report authentication status to the WP REST API.
5391
	 *
5392
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5393
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5394
	 */
5395
	public function wp_rest_authentication_errors( $value ) {
5396
		if ( $value !== null ) {
5397
			return $value;
5398
		}
5399
		return $this->rest_authentication_status;
5400
	}
5401
5402
	function add_nonce( $timestamp, $nonce ) {
5403
		global $wpdb;
5404
		static $nonces_used_this_request = array();
5405
5406
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5407
			return $nonces_used_this_request["$timestamp:$nonce"];
5408
		}
5409
5410
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5411
		$timestamp = (int) $timestamp;
5412
		$nonce     = esc_sql( $nonce );
5413
5414
		// Raw query so we can avoid races: add_option will also update
5415
		$show_errors = $wpdb->show_errors( false );
5416
5417
		$old_nonce = $wpdb->get_row(
5418
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5419
		);
5420
5421
		if ( is_null( $old_nonce ) ) {
5422
			$return = $wpdb->query(
5423
				$wpdb->prepare(
5424
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5425
					"jetpack_nonce_{$timestamp}_{$nonce}",
5426
					time(),
5427
					'no'
5428
				)
5429
			);
5430
		} else {
5431
			$return = false;
5432
		}
5433
5434
		$wpdb->show_errors( $show_errors );
5435
5436
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5437
5438
		return $return;
5439
	}
5440
5441
	/**
5442
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5443
	 * Capture it here so we can verify the signature later.
5444
	 */
5445
	function xmlrpc_methods( $methods ) {
5446
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5447
		return $methods;
5448
	}
5449
5450
	function public_xmlrpc_methods( $methods ) {
5451
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5452
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5453
		}
5454
		return $methods;
5455
	}
5456
5457
	function jetpack_getOptions( $args ) {
5458
		global $wp_xmlrpc_server;
5459
5460
		$wp_xmlrpc_server->escape( $args );
5461
5462
		$username	= $args[1];
5463
		$password	= $args[2];
5464
5465
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5466
			return $wp_xmlrpc_server->error;
5467
		}
5468
5469
		$options = array();
5470
		$user_data = $this->get_connected_user_data();
5471
		if ( is_array( $user_data ) ) {
5472
			$options['jetpack_user_id'] = array(
5473
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5474
				'readonly'      => true,
5475
				'value'         => $user_data['ID'],
5476
			);
5477
			$options['jetpack_user_login'] = array(
5478
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5479
				'readonly'      => true,
5480
				'value'         => $user_data['login'],
5481
			);
5482
			$options['jetpack_user_email'] = array(
5483
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5484
				'readonly'      => true,
5485
				'value'         => $user_data['email'],
5486
			);
5487
			$options['jetpack_user_site_count'] = array(
5488
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5489
				'readonly'      => true,
5490
				'value'         => $user_data['site_count'],
5491
			);
5492
		}
5493
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5494
		$args = stripslashes_deep( $args );
5495
		return $wp_xmlrpc_server->wp_getOptions( $args );
5496
	}
5497
5498
	function xmlrpc_options( $options ) {
5499
		$jetpack_client_id = false;
5500
		if ( self::is_active() ) {
5501
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5502
		}
5503
		$options['jetpack_version'] = array(
5504
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5505
				'readonly'      => true,
5506
				'value'         => JETPACK__VERSION,
5507
		);
5508
5509
		$options['jetpack_client_id'] = array(
5510
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5511
				'readonly'      => true,
5512
				'value'         => $jetpack_client_id,
5513
		);
5514
		return $options;
5515
	}
5516
5517
	public static function clean_nonces( $all = false ) {
5518
		global $wpdb;
5519
5520
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5521
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5522
5523
		if ( true !== $all ) {
5524
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5525
			$sql_args[] = time() - 3600;
5526
		}
5527
5528
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5529
5530
		$sql = $wpdb->prepare( $sql, $sql_args );
5531
5532
		for ( $i = 0; $i < 1000; $i++ ) {
5533
			if ( ! $wpdb->query( $sql ) ) {
5534
				break;
5535
			}
5536
		}
5537
	}
5538
5539
	/**
5540
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5541
	 * SET: state( $key, $value );
5542
	 * GET: $value = state( $key );
5543
	 *
5544
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5545
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5546
	 * @param bool $restate private
5547
	 */
5548
	public static function state( $key = null, $value = null, $restate = false ) {
5549
		static $state = array();
5550
		static $path, $domain;
5551
		if ( ! isset( $path ) ) {
5552
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5553
			$admin_url = Jetpack::admin_url();
5554
			$bits      = wp_parse_url( $admin_url );
5555
5556
			if ( is_array( $bits ) ) {
5557
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5558
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5559
			} else {
5560
				$path = $domain = null;
5561
			}
5562
		}
5563
5564
		// Extract state from cookies and delete cookies
5565
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5566
			$yum = $_COOKIE[ 'jetpackState' ];
5567
			unset( $_COOKIE[ 'jetpackState' ] );
5568
			foreach ( $yum as $k => $v ) {
5569
				if ( strlen( $v ) )
5570
					$state[ $k ] = $v;
5571
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5572
			}
5573
		}
5574
5575
		if ( $restate ) {
5576
			foreach ( $state as $k => $v ) {
5577
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5578
			}
5579
			return;
5580
		}
5581
5582
		// Get a state variable
5583
		if ( isset( $key ) && ! isset( $value ) ) {
5584
			if ( array_key_exists( $key, $state ) )
5585
				return $state[ $key ];
5586
			return null;
5587
		}
5588
5589
		// Set a state variable
5590
		if ( isset ( $key ) && isset( $value ) ) {
5591
			if( is_array( $value ) && isset( $value[0] ) ) {
5592
				$value = $value[0];
5593
			}
5594
			$state[ $key ] = $value;
5595
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5596
		}
5597
	}
5598
5599
	public static function restate() {
5600
		Jetpack::state( null, null, true );
5601
	}
5602
5603
	public static function check_privacy( $file ) {
5604
		static $is_site_publicly_accessible = null;
5605
5606
		if ( is_null( $is_site_publicly_accessible ) ) {
5607
			$is_site_publicly_accessible = false;
5608
5609
			Jetpack::load_xml_rpc_client();
5610
			$rpc = new Jetpack_IXR_Client();
5611
5612
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5613
			if ( $success ) {
5614
				$response = $rpc->getResponse();
5615
				if ( $response ) {
5616
					$is_site_publicly_accessible = true;
5617
				}
5618
			}
5619
5620
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5621
		}
5622
5623
		if ( $is_site_publicly_accessible ) {
5624
			return;
5625
		}
5626
5627
		$module_slug = self::get_module_slug( $file );
5628
5629
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5630
		if ( ! $privacy_checks ) {
5631
			$privacy_checks = $module_slug;
5632
		} else {
5633
			$privacy_checks .= ",$module_slug";
5634
		}
5635
5636
		Jetpack::state( 'privacy_checks', $privacy_checks );
5637
	}
5638
5639
	/**
5640
	 * Helper method for multicall XMLRPC.
5641
	 */
5642
	public static function xmlrpc_async_call() {
5643
		global $blog_id;
5644
		static $clients = array();
5645
5646
		$client_blog_id = is_multisite() ? $blog_id : 0;
5647
5648
		if ( ! isset( $clients[$client_blog_id] ) ) {
5649
			Jetpack::load_xml_rpc_client();
5650
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5651
			if ( function_exists( 'ignore_user_abort' ) ) {
5652
				ignore_user_abort( true );
5653
			}
5654
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5655
		}
5656
5657
		$args = func_get_args();
5658
5659
		if ( ! empty( $args[0] ) ) {
5660
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5661
		} elseif ( is_multisite() ) {
5662
			foreach ( $clients as $client_blog_id => $client ) {
5663
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5664
					continue;
5665
				}
5666
5667
				$switch_success = switch_to_blog( $client_blog_id, true );
5668
				if ( ! $switch_success ) {
5669
					continue;
5670
				}
5671
5672
				flush();
5673
				$client->query();
5674
5675
				restore_current_blog();
5676
			}
5677
		} else {
5678
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5679
				flush();
5680
				$clients[0]->query();
5681
			}
5682
		}
5683
	}
5684
5685
	public static function staticize_subdomain( $url ) {
5686
5687
		// Extract hostname from URL
5688
		$host = parse_url( $url, PHP_URL_HOST );
5689
5690
		// Explode hostname on '.'
5691
		$exploded_host = explode( '.', $host );
5692
5693
		// Retrieve the name and TLD
5694
		if ( count( $exploded_host ) > 1 ) {
5695
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5696
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5697
			// Rebuild domain excluding subdomains
5698
			$domain = $name . '.' . $tld;
5699
		} else {
5700
			$domain = $host;
5701
		}
5702
		// Array of Automattic domains
5703
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5704
5705
		// Return $url if not an Automattic domain
5706
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5707
			return $url;
5708
		}
5709
5710
		if ( is_ssl() ) {
5711
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5712
		}
5713
5714
		srand( crc32( basename( $url ) ) );
5715
		$static_counter = rand( 0, 2 );
5716
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5717
5718
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5719
	}
5720
5721
/* JSON API Authorization */
5722
5723
	/**
5724
	 * Handles the login action for Authorizing the JSON API
5725
	 */
5726
	function login_form_json_api_authorization() {
5727
		$this->verify_json_api_authorization_request();
5728
5729
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5730
5731
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5732
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5733
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5734
	}
5735
5736
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5737
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5738
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5739
			return $url;
5740
		}
5741
5742
		$parsed_url = parse_url( $url );
5743
		$url = strtok( $url, '?' );
5744
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5745
		if ( ! empty( $parsed_url['query'] ) )
5746
			$url .= "&{$parsed_url['query']}";
5747
5748
		return $url;
5749
	}
5750
5751
	// Make sure the POSTed request is handled by the same action
5752
	function preserve_action_in_login_form_for_json_api_authorization() {
5753
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5754
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5755
	}
5756
5757
	// If someone logs in to approve API access, store the Access Code in usermeta
5758
	function store_json_api_authorization_token( $user_login, $user ) {
5759
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5760
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5761
		$token = wp_generate_password( 32, false );
5762
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5763
	}
5764
5765
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5766
	function allow_wpcom_public_api_domain( $domains ) {
5767
		$domains[] = 'public-api.wordpress.com';
5768
		return $domains;
5769
	}
5770
5771
	static function is_redirect_encoded( $redirect_url ) {
5772
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5773
	}
5774
5775
	// Add all wordpress.com environments to the safe redirect whitelist
5776
	function allow_wpcom_environments( $domains ) {
5777
		$domains[] = 'wordpress.com';
5778
		$domains[] = 'wpcalypso.wordpress.com';
5779
		$domains[] = 'horizon.wordpress.com';
5780
		$domains[] = 'calypso.localhost';
5781
		return $domains;
5782
	}
5783
5784
	// Add the Access Code details to the public-api.wordpress.com redirect
5785
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5786
		return add_query_arg(
5787
			urlencode_deep(
5788
				array(
5789
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5790
					'jetpack-user-id' => (int) $user->ID,
5791
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5792
				)
5793
			),
5794
			$redirect_to
5795
		);
5796
	}
5797
5798
5799
	/**
5800
	 * Verifies the request by checking the signature
5801
	 *
5802
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5803
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5804
	 *
5805
	 * @param null|array $environment
5806
	 */
5807
	function verify_json_api_authorization_request( $environment = null ) {
5808
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5809
5810
		$environment = is_null( $environment )
5811
			? $_REQUEST
5812
			: $environment;
5813
5814
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5815
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5816
		if ( ! $token || empty( $token->secret ) ) {
5817
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5818
		}
5819
5820
		$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' );
5821
5822
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5823
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5824
			JetpackTracking::record_user_event( 'error_double_encode' );
5825
5826
			$die_error = sprintf(
5827
				/* translators: %s is a URL */
5828
				__( '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' ),
5829
				'https://jetpack.com/support/double-encoding/'
5830
			);
5831
		}
5832
5833
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5834
5835
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5836
			$signature = $jetpack_signature->sign_request(
5837
				$environment['token'],
5838
				$environment['timestamp'],
5839
				$environment['nonce'],
5840
				'',
5841
				'GET',
5842
				$environment['jetpack_json_api_original_query'],
5843
				null,
5844
				true
5845
			);
5846
		} else {
5847
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5848
		}
5849
5850
		if ( ! $signature ) {
5851
			wp_die( $die_error );
5852
		} else if ( is_wp_error( $signature ) ) {
5853
			wp_die( $die_error );
5854
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5855
			if ( is_ssl() ) {
5856
				// 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
5857
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5858
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5859
					wp_die( $die_error );
5860
				}
5861
			} else {
5862
				wp_die( $die_error );
5863
			}
5864
		}
5865
5866
		$timestamp = (int) $environment['timestamp'];
5867
		$nonce     = stripslashes( (string) $environment['nonce'] );
5868
5869
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5870
			// De-nonce the nonce, at least for 5 minutes.
5871
			// 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)
5872
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5873
			if ( $old_nonce_time < time() - 300 ) {
5874
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5875
			}
5876
		}
5877
5878
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5879
		$data_filters = array(
5880
			'state'        => 'opaque',
5881
			'client_id'    => 'int',
5882
			'client_title' => 'string',
5883
			'client_image' => 'url',
5884
		);
5885
5886
		foreach ( $data_filters as $key => $sanitation ) {
5887
			if ( ! isset( $data->$key ) ) {
5888
				wp_die( $die_error );
5889
			}
5890
5891
			switch ( $sanitation ) {
5892
			case 'int' :
5893
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5894
				break;
5895
			case 'opaque' :
5896
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5897
				break;
5898
			case 'string' :
5899
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5900
				break;
5901
			case 'url' :
5902
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5903
				break;
5904
			}
5905
		}
5906
5907
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5908
			wp_die( $die_error );
5909
		}
5910
	}
5911
5912
	function login_message_json_api_authorization( $message ) {
5913
		return '<p class="message">' . sprintf(
5914
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5915
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5916
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5917
	}
5918
5919
	/**
5920
	 * Get $content_width, but with a <s>twist</s> filter.
5921
	 */
5922
	public static function get_content_width() {
5923
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5924
			? $GLOBALS['content_width']
5925
			: false;
5926
		/**
5927
		 * Filter the Content Width value.
5928
		 *
5929
		 * @since 2.2.3
5930
		 *
5931
		 * @param string $content_width Content Width value.
5932
		 */
5933
		return apply_filters( 'jetpack_content_width', $content_width );
5934
	}
5935
5936
	/**
5937
	 * Pings the WordPress.com Mirror Site for the specified options.
5938
	 *
5939
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5940
	 *
5941
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5942
	 */
5943
	public function get_cloud_site_options( $option_names ) {
5944
		$option_names = array_filter( (array) $option_names, 'is_string' );
5945
5946
		Jetpack::load_xml_rpc_client();
5947
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5948
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5949
		if ( $xml->isError() ) {
5950
			return array(
5951
				'error_code' => $xml->getErrorCode(),
5952
				'error_msg'  => $xml->getErrorMessage(),
5953
			);
5954
		}
5955
		$cloud_site_options = $xml->getResponse();
5956
5957
		return $cloud_site_options;
5958
	}
5959
5960
	/**
5961
	 * Checks if the site is currently in an identity crisis.
5962
	 *
5963
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5964
	 */
5965
	public static function check_identity_crisis() {
5966
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5967
			return false;
5968
		}
5969
5970
		return Jetpack_Options::get_option( 'sync_error_idc' );
5971
	}
5972
5973
	/**
5974
	 * Checks whether the home and siteurl specifically are whitelisted
5975
	 * Written so that we don't have re-check $key and $value params every time
5976
	 * we want to check if this site is whitelisted, for example in footer.php
5977
	 *
5978
	 * @since  3.8.0
5979
	 * @return bool True = already whitelisted False = not whitelisted
5980
	 */
5981
	public static function is_staging_site() {
5982
		$is_staging = false;
5983
5984
		$known_staging = array(
5985
			'urls' => array(
5986
				'#\.staging\.wpengine\.com$#i', // WP Engine
5987
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5988
				),
5989
			'constants' => array(
5990
				'IS_WPE_SNAPSHOT',      // WP Engine
5991
				'KINSTA_DEV_ENV',       // Kinsta.com
5992
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5993
				'JETPACK_STAGING_MODE', // Generic
5994
				)
5995
			);
5996
		/**
5997
		 * Filters the flags of known staging sites.
5998
		 *
5999
		 * @since 3.9.0
6000
		 *
6001
		 * @param array $known_staging {
6002
		 *     An array of arrays that each are used to check if the current site is staging.
6003
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6004
		 *     @type array $constants PHP constants of known staging/developement environments.
6005
		 *  }
6006
		 */
6007
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6008
6009
		if ( isset( $known_staging['urls'] ) ) {
6010
			foreach ( $known_staging['urls'] as $url ){
6011
				if ( preg_match( $url, site_url() ) ) {
6012
					$is_staging = true;
6013
					break;
6014
				}
6015
			}
6016
		}
6017
6018
		if ( isset( $known_staging['constants'] ) ) {
6019
			foreach ( $known_staging['constants'] as $constant ) {
6020
				if ( defined( $constant ) && constant( $constant ) ) {
6021
					$is_staging = true;
6022
				}
6023
			}
6024
		}
6025
6026
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6027
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6028
			$is_staging = true;
6029
		}
6030
6031
		/**
6032
		 * Filters is_staging_site check.
6033
		 *
6034
		 * @since 3.9.0
6035
		 *
6036
		 * @param bool $is_staging If the current site is a staging site.
6037
		 */
6038
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6039
	}
6040
6041
	/**
6042
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6043
	 *
6044
	 * @since 4.4.0
6045
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6046
	 *
6047
	 * @return bool
6048
	 */
6049
	public static function validate_sync_error_idc_option() {
6050
		$is_valid = false;
6051
6052
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6053
		if ( false === $idc_allowed ) {
6054
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6055
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6056
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6057
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6058
				$transient_duration = HOUR_IN_SECONDS;
6059
			} else {
6060
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6061
				$idc_allowed = '1';
6062
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6063
			}
6064
6065
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6066
		}
6067
6068
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6069
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6070
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6071
			$local_options = self::get_sync_error_idc_option();
6072
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6073
				$is_valid = true;
6074
			}
6075
		}
6076
6077
		/**
6078
		 * Filters whether the sync_error_idc option is valid.
6079
		 *
6080
		 * @since 4.4.0
6081
		 *
6082
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6083
		 */
6084
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6085
6086
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6087
			// Since the option exists, and did not validate, delete it
6088
			Jetpack_Options::delete_option( 'sync_error_idc' );
6089
		}
6090
6091
		return $is_valid;
6092
	}
6093
6094
	/**
6095
	 * Normalizes a url by doing three things:
6096
	 *  - Strips protocol
6097
	 *  - Strips www
6098
	 *  - Adds a trailing slash
6099
	 *
6100
	 * @since 4.4.0
6101
	 * @param string $url
6102
	 * @return WP_Error|string
6103
	 */
6104
	public static function normalize_url_protocol_agnostic( $url ) {
6105
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6106
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6107
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6108
		}
6109
6110
		// Strip www and protocols
6111
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6112
		return $url;
6113
	}
6114
6115
	/**
6116
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6117
	 *
6118
	 * @since 4.4.0
6119
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6120
	 *
6121
	 * @param array $response
6122
	 * @return array Array of the local urls, wpcom urls, and error code
6123
	 */
6124
	public static function get_sync_error_idc_option( $response = array() ) {
6125
		// Since the local options will hit the database directly, store the values
6126
		// in a transient to allow for autoloading and caching on subsequent views.
6127
		$local_options = get_transient( 'jetpack_idc_local' );
6128
		if ( false === $local_options ) {
6129
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6130
			$local_options = array(
6131
				'home'    => Jetpack_Sync_Functions::home_url(),
6132
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6133
			);
6134
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6135
		}
6136
6137
		$options = array_merge( $local_options, $response );
6138
6139
		$returned_values = array();
6140
		foreach( $options as $key => $option ) {
6141
			if ( 'error_code' === $key ) {
6142
				$returned_values[ $key ] = $option;
6143
				continue;
6144
			}
6145
6146
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6147
				continue;
6148
			}
6149
6150
			$returned_values[ $key ] = $normalized_url;
6151
		}
6152
6153
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6154
6155
		return $returned_values;
6156
	}
6157
6158
	/**
6159
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6160
	 * If set to true, the site will be put into staging mode.
6161
	 *
6162
	 * @since 4.3.2
6163
	 * @return bool
6164
	 */
6165
	public static function sync_idc_optin() {
6166
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6167
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6168
		} else {
6169
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6170
		}
6171
6172
		/**
6173
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6174
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6175
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6176
		 *
6177
		 * @since 4.3.2
6178
		 *
6179
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6180
		 */
6181
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6182
	}
6183
6184
	/**
6185
	 * Maybe Use a .min.css stylesheet, maybe not.
6186
	 *
6187
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6188
	 */
6189
	public static function maybe_min_asset( $url, $path, $plugin ) {
6190
		// Short out on things trying to find actual paths.
6191
		if ( ! $path || empty( $plugin ) ) {
6192
			return $url;
6193
		}
6194
6195
		$path = ltrim( $path, '/' );
6196
6197
		// Strip out the abspath.
6198
		$base = dirname( plugin_basename( $plugin ) );
6199
6200
		// Short out on non-Jetpack assets.
6201
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6202
			return $url;
6203
		}
6204
6205
		// File name parsing.
6206
		$file              = "{$base}/{$path}";
6207
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6208
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6209
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6210
		$extension         = array_shift( $file_name_parts_r );
6211
6212
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6213
			// Already pointing at the minified version.
6214
			if ( 'min' === $file_name_parts_r[0] ) {
6215
				return $url;
6216
			}
6217
6218
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6219
			if ( file_exists( $min_full_path ) ) {
6220
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6221
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6222
				if ( 'css' === $extension ) {
6223
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6224
					self::$min_assets[ $key ] = $path;
6225
				}
6226
			}
6227
		}
6228
6229
		return $url;
6230
	}
6231
6232
	/**
6233
	 * If the asset is minified, let's flag .min as the suffix.
6234
	 *
6235
	 * Attached to `style_loader_src` filter.
6236
	 *
6237
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6238
	 * @param string $handle The registered handle of the script in question.
6239
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6240
	 */
6241
	public static function set_suffix_on_min( $src, $handle ) {
6242
		if ( false === strpos( $src, '.min.css' ) ) {
6243
			return $src;
6244
		}
6245
6246
		if ( ! empty( self::$min_assets ) ) {
6247
			foreach ( self::$min_assets as $file => $path ) {
6248
				if ( false !== strpos( $src, $file ) ) {
6249
					wp_style_add_data( $handle, 'suffix', '.min' );
6250
					return $src;
6251
				}
6252
			}
6253
		}
6254
6255
		return $src;
6256
	}
6257
6258
	/**
6259
	 * Maybe inlines a stylesheet.
6260
	 *
6261
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6262
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6263
	 *
6264
	 * Attached to `style_loader_tag` filter.
6265
	 *
6266
	 * @param string $tag The tag that would link to the external asset.
6267
	 * @param string $handle The registered handle of the script in question.
6268
	 *
6269
	 * @return string
6270
	 */
6271
	public static function maybe_inline_style( $tag, $handle ) {
6272
		global $wp_styles;
6273
		$item = $wp_styles->registered[ $handle ];
6274
6275
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6276
			return $tag;
6277
		}
6278
6279
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6280
			$href = $matches[1];
6281
			// Strip off query string
6282
			if ( $pos = strpos( $href, '?' ) ) {
6283
				$href = substr( $href, 0, $pos );
6284
			}
6285
			// Strip off fragment
6286
			if ( $pos = strpos( $href, '#' ) ) {
6287
				$href = substr( $href, 0, $pos );
6288
			}
6289
		} else {
6290
			return $tag;
6291
		}
6292
6293
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6294
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6295
			return $tag;
6296
		}
6297
6298
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6299
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6300
			// And this isn't the pass that actually deals with the RTL version...
6301
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6302
				// Short out, as the RTL version will deal with it in a moment.
6303
				return $tag;
6304
			}
6305
		}
6306
6307
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6308
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6309
		if ( $css ) {
6310
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6311
			if ( empty( $item->extra['after'] ) ) {
6312
				wp_add_inline_style( $handle, $css );
6313
			} else {
6314
				array_unshift( $item->extra['after'], $css );
6315
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6316
			}
6317
		}
6318
6319
		return $tag;
6320
	}
6321
6322
	/**
6323
	 * Loads a view file from the views
6324
	 *
6325
	 * Data passed in with the $data parameter will be available in the
6326
	 * template file as $data['value']
6327
	 *
6328
	 * @param string $template - Template file to load
6329
	 * @param array $data - Any data to pass along to the template
6330
	 * @return boolean - If template file was found
6331
	 **/
6332
	public function load_view( $template, $data = array() ) {
6333
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6334
6335
		if( file_exists( $views_dir . $template ) ) {
6336
			require_once( $views_dir . $template );
6337
			return true;
6338
		}
6339
6340
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6341
		return false;
6342
	}
6343
6344
	/**
6345
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6346
	 */
6347
	public function deprecated_hooks() {
6348
		global $wp_filter;
6349
6350
		/*
6351
		 * Format:
6352
		 * deprecated_filter_name => replacement_name
6353
		 *
6354
		 * If there is no replacement, use null for replacement_name
6355
		 */
6356
		$deprecated_list = array(
6357
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6358
			'wpl_sharing_2014_1'                                     => null,
6359
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6360
			'jetpack_identity_crisis_options_to_check'               => null,
6361
			'update_option_jetpack_single_user_site'                 => null,
6362
			'audio_player_default_colors'                            => null,
6363
			'add_option_jetpack_featured_images_enabled'             => null,
6364
			'add_option_jetpack_update_details'                      => null,
6365
			'add_option_jetpack_updates'                             => null,
6366
			'add_option_jetpack_network_name'                        => null,
6367
			'add_option_jetpack_network_allow_new_registrations'     => null,
6368
			'add_option_jetpack_network_add_new_users'               => null,
6369
			'add_option_jetpack_network_site_upload_space'           => null,
6370
			'add_option_jetpack_network_upload_file_types'           => null,
6371
			'add_option_jetpack_network_enable_administration_menus' => null,
6372
			'add_option_jetpack_is_multi_site'                       => null,
6373
			'add_option_jetpack_is_main_network'                     => null,
6374
			'add_option_jetpack_main_network_site'                   => null,
6375
			'jetpack_sync_all_registered_options'                    => null,
6376
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6377
			'jetpack_is_post_mailable'                               => null,
6378
			'jetpack_seo_site_host'                                  => null,
6379
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6380
			'jetpack_holiday_snow_option_name'                       => null,
6381
			'jetpack_holiday_chance_of_snow'                         => null,
6382
			'jetpack_holiday_snow_js_url'                            => null,
6383
			'jetpack_is_holiday_snow_season'                         => null,
6384
			'jetpack_holiday_snow_option_updated'                    => null,
6385
			'jetpack_holiday_snowing'                                => null,
6386
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6387
			'jetpack_cache_plans'                                    => null,
6388
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6389
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6390
			'jetpack_enable_site_verification'                       => null,
6391
			'can_display_jetpack_manage_notice'                      => null,
6392
			// Removed in Jetpack 7.3.0
6393
			'atd_load_scripts'                                       => null,
6394
			'atd_http_post_timeout'                                  => null,
6395
			'atd_http_post_error'                                    => null,
6396
			'atd_service_domain'                                     => null,
6397
		);
6398
6399
		// This is a silly loop depth. Better way?
6400
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6401
			if ( has_action( $hook ) ) {
6402
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6403
					foreach( $values AS $hooked ) {
6404
						if ( is_callable( $hooked['function'] ) ) {
6405
							$function_name = 'an anonymous function';
6406
						} else {
6407
							$function_name = $hooked['function'];
6408
						}
6409
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6410
					}
6411
				}
6412
			}
6413
		}
6414
	}
6415
6416
	/**
6417
	 * Converts any url in a stylesheet, to the correct absolute url.
6418
	 *
6419
	 * Considerations:
6420
	 *  - Normal, relative URLs     `feh.png`
6421
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6422
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6423
	 *  - Absolute URLs             `http://domain.com/feh.png`
6424
	 *  - Domain root relative URLs `/feh.png`
6425
	 *
6426
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6427
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6428
	 *
6429
	 * @return mixed|string
6430
	 */
6431
	public static function absolutize_css_urls( $css, $css_file_url ) {
6432
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6433
		$css_dir = dirname( $css_file_url );
6434
		$p       = parse_url( $css_dir );
6435
		$domain  = sprintf(
6436
					'%1$s//%2$s%3$s%4$s',
6437
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6438
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6439
					$p['host'],
6440
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6441
				);
6442
6443
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6444
			$find = $replace = array();
6445
			foreach ( $matches as $match ) {
6446
				$url = trim( $match['path'], "'\" \t" );
6447
6448
				// If this is a data url, we don't want to mess with it.
6449
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6450
					continue;
6451
				}
6452
6453
				// If this is an absolute or protocol-agnostic url,
6454
				// we don't want to mess with it.
6455
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6456
					continue;
6457
				}
6458
6459
				switch ( substr( $url, 0, 1 ) ) {
6460
					case '/':
6461
						$absolute = $domain . $url;
6462
						break;
6463
					default:
6464
						$absolute = $css_dir . '/' . $url;
6465
				}
6466
6467
				$find[]    = $match[0];
6468
				$replace[] = sprintf( 'url("%s")', $absolute );
6469
			}
6470
			$css = str_replace( $find, $replace, $css );
6471
		}
6472
6473
		return $css;
6474
	}
6475
6476
	/**
6477
	 * This methods removes all of the registered css files on the front end
6478
	 * from Jetpack in favor of using a single file. In effect "imploding"
6479
	 * all the files into one file.
6480
	 *
6481
	 * Pros:
6482
	 * - Uses only ONE css asset connection instead of 15
6483
	 * - Saves a minimum of 56k
6484
	 * - Reduces server load
6485
	 * - Reduces time to first painted byte
6486
	 *
6487
	 * Cons:
6488
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6489
	 *		should not cause any issues with themes.
6490
	 * - Plugins/themes dequeuing styles no longer do anything. See
6491
	 *		jetpack_implode_frontend_css filter for a workaround
6492
	 *
6493
	 * For some situations developers may wish to disable css imploding and
6494
	 * instead operate in legacy mode where each file loads seperately and
6495
	 * can be edited individually or dequeued. This can be accomplished with
6496
	 * the following line:
6497
	 *
6498
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6499
	 *
6500
	 * @since 3.2
6501
	 **/
6502
	public function implode_frontend_css( $travis_test = false ) {
6503
		$do_implode = true;
6504
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6505
			$do_implode = false;
6506
		}
6507
6508
		// Do not implode CSS when the page loads via the AMP plugin.
6509
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6510
			$do_implode = false;
6511
		}
6512
6513
		/**
6514
		 * Allow CSS to be concatenated into a single jetpack.css file.
6515
		 *
6516
		 * @since 3.2.0
6517
		 *
6518
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6519
		 */
6520
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6521
6522
		// Do not use the imploded file when default behavior was altered through the filter
6523
		if ( ! $do_implode ) {
6524
			return;
6525
		}
6526
6527
		// We do not want to use the imploded file in dev mode, or if not connected
6528
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6529
			if ( ! $travis_test ) {
6530
				return;
6531
			}
6532
		}
6533
6534
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6535
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6536
			return;
6537
		}
6538
6539
		/*
6540
		 * Now we assume Jetpack is connected and able to serve the single
6541
		 * file.
6542
		 *
6543
		 * In the future there will be a check here to serve the file locally
6544
		 * or potentially from the Jetpack CDN
6545
		 *
6546
		 * For now:
6547
		 * - Enqueue a single imploded css file
6548
		 * - Zero out the style_loader_tag for the bundled ones
6549
		 * - Be happy, drink scotch
6550
		 */
6551
6552
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6553
6554
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6555
6556
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6557
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6558
	}
6559
6560
	function concat_remove_style_loader_tag( $tag, $handle ) {
6561
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6562
			$tag = '';
6563
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6564
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6565
			}
6566
		}
6567
6568
		return $tag;
6569
	}
6570
6571
	/*
6572
	 * Check the heartbeat data
6573
	 *
6574
	 * Organizes the heartbeat data by severity.  For example, if the site
6575
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6576
	 *
6577
	 * Data will be added to "caution" array, if it either:
6578
	 *  - Out of date Jetpack version
6579
	 *  - Out of date WP version
6580
	 *  - Out of date PHP version
6581
	 *
6582
	 * $return array $filtered_data
6583
	 */
6584
	public static function jetpack_check_heartbeat_data() {
6585
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6586
6587
		$good    = array();
6588
		$caution = array();
6589
		$bad     = array();
6590
6591
		foreach ( $raw_data as $stat => $value ) {
6592
6593
			// Check jetpack version
6594
			if ( 'version' == $stat ) {
6595
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6596
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6597
					continue;
6598
				}
6599
			}
6600
6601
			// Check WP version
6602
			if ( 'wp-version' == $stat ) {
6603
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6604
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6605
					continue;
6606
				}
6607
			}
6608
6609
			// Check PHP version
6610
			if ( 'php-version' == $stat ) {
6611
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6612
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6613
					continue;
6614
				}
6615
			}
6616
6617
			// Check ID crisis
6618
			if ( 'identitycrisis' == $stat ) {
6619
				if ( 'yes' == $value ) {
6620
					$bad[ $stat ] = $value;
6621
					continue;
6622
				}
6623
			}
6624
6625
			// The rest are good :)
6626
			$good[ $stat ] = $value;
6627
		}
6628
6629
		$filtered_data = array(
6630
			'good'    => $good,
6631
			'caution' => $caution,
6632
			'bad'     => $bad
6633
		);
6634
6635
		return $filtered_data;
6636
	}
6637
6638
6639
	/*
6640
	 * This method is used to organize all options that can be reset
6641
	 * without disconnecting Jetpack.
6642
	 *
6643
	 * It is used in class.jetpack-cli.php to reset options
6644
	 *
6645
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6646
	 *
6647
	 * @return array of options to delete.
6648
	 */
6649
	public static function get_jetpack_options_for_reset() {
6650
		return Jetpack_Options::get_options_for_reset();
6651
	}
6652
6653
	/*
6654
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6655
	 * so we can bring them directly to their site in calypso.
6656
	 *
6657
	 * @param string | url
6658
	 * @return string | url without the guff
6659
	 */
6660
	public static function build_raw_urls( $url ) {
6661
		$strip_http = '/.*?:\/\//i';
6662
		$url = preg_replace( $strip_http, '', $url  );
6663
		$url = str_replace( '/', '::', $url );
6664
		return $url;
6665
	}
6666
6667
	/**
6668
	 * Stores and prints out domains to prefetch for page speed optimization.
6669
	 *
6670
	 * @param mixed $new_urls
6671
	 */
6672
	public static function dns_prefetch( $new_urls = null ) {
6673
		static $prefetch_urls = array();
6674
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6675
			echo "\r\n";
6676
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6677
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6678
			}
6679
		} elseif ( ! empty( $new_urls ) ) {
6680
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6681
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6682
			}
6683
			foreach ( (array) $new_urls as $this_new_url ) {
6684
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6685
			}
6686
			$prefetch_urls = array_unique( $prefetch_urls );
6687
		}
6688
	}
6689
6690
	public function wp_dashboard_setup() {
6691
		if ( self::is_active() ) {
6692
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6693
		}
6694
6695
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6696
			$widget_title = sprintf(
6697
				wp_kses(
6698
					/* translators: Placeholder is a Jetpack logo. */
6699
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6700
					array( 'span' => array() )
6701
				),
6702
				Jetpack::get_jp_emblem( true )
6703
			);
6704
6705
			wp_add_dashboard_widget(
6706
				'jetpack_summary_widget',
6707
				$widget_title,
6708
				array( __CLASS__, 'dashboard_widget' )
6709
			);
6710
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6711
6712
			// If we're inactive and not in development mode, sort our box to the top.
6713
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6714
				global $wp_meta_boxes;
6715
6716
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6717
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6718
6719
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6720
			}
6721
		}
6722
	}
6723
6724
	/**
6725
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6726
	 * @return mixed
6727
	 */
6728
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6729
		if ( ! is_array( $sorted ) ) {
6730
			return $sorted;
6731
		}
6732
6733
		foreach ( $sorted as $box_context => $ids ) {
6734
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6735
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6736
				continue;
6737
			}
6738
6739
			$ids_array = explode( ',', $ids );
6740
			$key = array_search( 'dashboard_stats', $ids_array );
6741
6742
			if ( false !== $key ) {
6743
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6744
				$ids_array[ $key ] = 'jetpack_summary_widget';
6745
				$sorted[ $box_context ] = implode( ',', $ids_array );
6746
				// We've found it, stop searching, and just return.
6747
				break;
6748
			}
6749
		}
6750
6751
		return $sorted;
6752
	}
6753
6754
	public static function dashboard_widget() {
6755
		/**
6756
		 * Fires when the dashboard is loaded.
6757
		 *
6758
		 * @since 3.4.0
6759
		 */
6760
		do_action( 'jetpack_dashboard_widget' );
6761
	}
6762
6763
	public static function dashboard_widget_footer() {
6764
		?>
6765
		<footer>
6766
6767
		<div class="protect">
6768
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6769
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6770
				<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>
6771
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6772
				<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' ); ?>">
6773
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6774
				</a>
6775
			<?php else : ?>
6776
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6777
			<?php endif; ?>
6778
		</div>
6779
6780
		<div class="akismet">
6781
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6782
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6783
				<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>
6784
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6785
				<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">
6786
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6787
				</a>
6788
			<?php else : ?>
6789
				<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>
6790
			<?php endif; ?>
6791
		</div>
6792
6793
		</footer>
6794
		<?php
6795
	}
6796
6797
	/**
6798
	 * Return string containing the Jetpack logo.
6799
	 *
6800
	 * @since 3.9.0
6801
	 *
6802
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6803
	 *
6804
	 * @return string
6805
	 */
6806
	public static function get_jp_emblem( $logotype = false ) {
6807
		$logo = '<path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/>';
6808
		$text = '
6809
<path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" />
6810
<path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" />
6811
<path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" />
6812
<path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" />
6813
<path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" />
6814
<path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" />
6815
<path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" />
6816
		';
6817
6818
		return sprintf(
6819
			'<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 %1$s 32">%2$s</svg>',
6820
			( true === $logotype ? '118' : '32' ),
6821
			( true === $logotype ? $logo . $text : $logo )
6822
		);
6823
	}
6824
6825
	/*
6826
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6827
	 */
6828
	function jetpack_icon_user_connected( $columns ) {
6829
		$columns['user_jetpack'] = '';
6830
		return $columns;
6831
	}
6832
6833
	/*
6834
	 * Show Jetpack icon if the user is linked.
6835
	 */
6836
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6837
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6838
			$emblem_html = sprintf(
6839
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6840
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6841
				Jetpack::get_jp_emblem()
6842
			);
6843
			return $emblem_html;
6844
		}
6845
6846
		return $val;
6847
	}
6848
6849
	/*
6850
	 * Style the Jetpack user column
6851
	 */
6852
	function jetpack_user_col_style() {
6853
		global $current_screen;
6854
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6855
			<style>
6856
				.fixed .column-user_jetpack {
6857
					width: 21px;
6858
				}
6859
				.jp-emblem-user-admin svg {
6860
					width: 20px;
6861
					height: 20px;
6862
				}
6863
				.jp-emblem-user-admin path {
6864
					fill: #00BE28;
6865
				}
6866
			</style>
6867
		<?php }
6868
	}
6869
6870
	/**
6871
	 * Checks if Akismet is active and working.
6872
	 *
6873
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6874
	 * that implied usage of methods present since more recent version.
6875
	 * See https://github.com/Automattic/jetpack/pull/9585
6876
	 *
6877
	 * @since  5.1.0
6878
	 *
6879
	 * @return bool True = Akismet available. False = Aksimet not available.
6880
	 */
6881
	public static function is_akismet_active() {
6882
		static $status = null;
6883
6884
		if ( ! is_null( $status ) ) {
6885
			return $status;
6886
		}
6887
6888
		// Check if a modern version of Akismet is active.
6889
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6890
			$status = false;
6891
			return $status;
6892
		}
6893
6894
		// Make sure there is a key known to Akismet at all before verifying key.
6895
		$akismet_key = Akismet::get_api_key();
6896
		if ( ! $akismet_key ) {
6897
			$status = false;
6898
			return $status;
6899
		}
6900
6901
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6902
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6903
6904
		// 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.
6905
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6906
		// We cache the result of the Akismet key verification for ten minutes.
6907
		if ( ! $akismet_key_state || $recheck ) {
6908
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6909
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6910
		}
6911
6912
		$status = 'valid' === $akismet_key_state;
6913
6914
		return $status;
6915
	}
6916
6917
	/**
6918
	 * Checks if one or more function names is in debug_backtrace
6919
	 *
6920
	 * @param $names Mixed string name of function or array of string names of functions
6921
	 *
6922
	 * @return bool
6923
	 */
6924
	public static function is_function_in_backtrace( $names ) {
6925
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6926
		if ( ! is_array( $names ) ) {
6927
			$names = array( $names );
6928
		}
6929
		$names_as_keys = array_flip( $names );
6930
6931
		//Do check in constant O(1) time for PHP5.5+
6932
		if ( function_exists( 'array_column' ) ) {
6933
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6934
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6935
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6936
			return ! empty ( $intersection );
6937
		}
6938
6939
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6940
		foreach ( $backtrace as $call ) {
6941
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6942
				return true;
6943
			}
6944
		}
6945
		return false;
6946
	}
6947
6948
	/**
6949
	 * Given a minified path, and a non-minified path, will return
6950
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6951
	 *
6952
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6953
	 * root Jetpack directory.
6954
	 *
6955
	 * @since 5.6.0
6956
	 *
6957
	 * @param string $min_path
6958
	 * @param string $non_min_path
6959
	 * @return string The URL to the file
6960
	 */
6961
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6962
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
6963
			? $non_min_path
6964
			: $min_path;
6965
6966
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6967
	}
6968
6969
	/**
6970
	 * Checks for whether Jetpack Backup & Scan is enabled.
6971
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6972
	 * @return bool|int|mixed
6973
	 */
6974
	public static function is_rewind_enabled() {
6975
		if ( ! Jetpack::is_active() ) {
6976
			return false;
6977
		}
6978
6979
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6980
		if ( false === $rewind_enabled ) {
6981
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6982
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6983
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6984
				&& ! empty( $rewind_data['state'] )
6985
				&& 'active' === $rewind_data['state'] )
6986
				? 1
6987
				: 0;
6988
6989
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6990
		}
6991
		return $rewind_enabled;
6992
	}
6993
6994
	/**
6995
	 * Return Calypso environment value; used for developing Jetpack and pairing
6996
	 * it with different Calypso enrionments, such as localhost.
6997
	 *
6998
	 * @since 7.4.0
6999
	 *
7000
	 * @return string Calypso environment
7001
	 */
7002
	public static function get_calypso_env() {
7003
		if ( isset( $_GET['calypso_env'] ) ) {
7004
			return sanitize_key( $_GET['calypso_env'] );
7005
		}
7006
7007
		if ( getenv( 'CALYPSO_ENV' ) ) {
7008
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7009
		}
7010
7011
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7012
			return sanitize_key( CALYPSO_ENV );
7013
		}
7014
7015
		return '';
7016
	}
7017
7018
	/**
7019
	 * Checks whether or not TOS has been agreed upon.
7020
	 * Will return true if a user has clicked to register, or is already connected.
7021
	 */
7022
	public static function jetpack_tos_agreed() {
7023
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7024
	}
7025
7026
	/**
7027
	 * Handles activating default modules as well general cleanup for the new connection.
7028
	 *
7029
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7030
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7031
	 * @param boolean $send_state_messages          Whether to send state messages.
7032
	 * @return void
7033
	 */
7034
	public static function handle_post_authorization_actions(
7035
		$activate_sso = false,
7036
		$redirect_on_activation_error = false,
7037
		$send_state_messages = true
7038
	) {
7039
		$other_modules = $activate_sso
7040
			? array( 'sso' )
7041
			: array();
7042
7043
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7044
			Jetpack::delete_active_modules();
7045
7046
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 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...
7047
		} else {
7048
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7049
		}
7050
7051
		// Since this is a fresh connection, be sure to clear out IDC options
7052
		Jetpack_IDC::clear_all_idc_options();
7053
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7054
7055
		// Start nonce cleaner
7056
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7057
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7058
7059
		if ( $send_state_messages ) {
7060
			Jetpack::state( 'message', 'authorized' );
7061
		}
7062
	}
7063
7064
	/**
7065
	 * Returns a boolean for whether backups UI should be displayed or not.
7066
	 *
7067
	 * @return bool Should backups UI be displayed?
7068
	 */
7069
	public static function show_backups_ui() {
7070
		/**
7071
		 * Whether UI for backups should be displayed.
7072
		 *
7073
		 * @since 6.5.0
7074
		 *
7075
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7076
		 */
7077
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7078
	}
7079
7080
	/*
7081
	 * Deprecated manage functions
7082
	 */
7083
	function prepare_manage_jetpack_notice() {
7084
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7085
	}
7086
	function manage_activate_screen() {
7087
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7088
	}
7089
	function admin_jetpack_manage_notice() {
7090
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7091
	}
7092
	function opt_out_jetpack_manage_url() {
7093
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7094
	}
7095
	function opt_in_jetpack_manage_url() {
7096
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7097
	}
7098
	function opt_in_jetpack_manage_notice() {
7099
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7100
	}
7101
	function can_display_jetpack_manage_notice() {
7102
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7103
	}
7104
7105
	/**
7106
	 * Clean leftoveruser meta.
7107
	 *
7108
	 * Delete Jetpack-related user meta when it is no longer needed.
7109
	 *
7110
	 * @since 7.3.0
7111
	 *
7112
	 * @param int $user_id User ID being updated.
7113
	 */
7114
	public static function user_meta_cleanup( $user_id ) {
7115
		$meta_keys = array(
7116
			// AtD removed from Jetpack 7.3
7117
			'AtD_options',
7118
			'AtD_check_when',
7119
			'AtD_guess_lang',
7120
			'AtD_ignored_phrases',
7121
		);
7122
7123
		foreach ( $meta_keys as $meta_key ) {
7124
			if ( get_user_meta( $user_id, $meta_key ) ) {
7125
				delete_user_meta( $user_id, $meta_key );
7126
			}
7127
		}
7128
	}
7129
}
7130