Completed
Push — fix/prevent-modules-overwrite ( aad3f4 )
by
unknown
15:52 queued 02:54
created

Jetpack::get_other_linked_admins()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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