Completed
Push — sync/georgestephanis/r157268-w... ( bcd58f...5817c6 )
by George
11:00
created

Jetpack::disconnect()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 61
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 16
nop 1
dl 0
loc 61
rs 8.6806
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
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
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
		'eu-cookie-law-style',
60
		'flickr-widget-style',
61
	);
62
63
	/**
64
	 * Contains all assets that have had their URL rewritten to minified versions.
65
	 *
66
	 * @var array
67
	 */
68
	static $min_assets = array();
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $min_assets.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
69
70
	public $plugins_to_deactivate = array(
71
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
72
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
73
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
74
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
75
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
76
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
77
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
78
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
79
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
80
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
81
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
82
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
83
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
84
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
85
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
86
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
87
	);
88
89
	static $capability_translations = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $capability_translations.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
90
		'administrator' => 'manage_options',
91
		'editor'        => 'edit_others_posts',
92
		'author'        => 'publish_posts',
93
		'contributor'   => 'edit_posts',
94
		'subscriber'    => 'read',
95
	);
96
97
	/**
98
	 * Map of modules that have conflicts with plugins and should not be auto-activated
99
	 * if the plugins are active.  Used by filter_default_modules
100
	 *
101
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
102
	 * change `module-slug` and add this to your plugin:
103
	 *
104
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
105
	 * function my_jetpack_get_default_modules( $modules ) {
106
	 *     return array_diff( $modules, array( 'module-slug' ) );
107
	 * }
108
	 *
109
	 * @var array
110
	 */
111
	private $conflicting_plugins = array(
112
		'comments'          => array(
113
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
114
			'Disqus'                               => 'disqus-comment-system/disqus.php',
115
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
116
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
117
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
118
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
119
		),
120
		'contact-form'      => array(
121
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
122
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
123
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
124
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
125
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
126
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
127
		),
128
		'minileven'         => array(
129
			'WPtouch'                              => 'wptouch/wptouch.php',
130
		),
131
		'latex'             => array(
132
			'LaTeX for WordPress'                  => 'latex/latex.php',
133
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
134
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
135
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
136
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
137
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
138
		),
139
		'protect'           => array(
140
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
141
			'Captcha'                              => 'captcha/captcha.php',
142
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
143
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
144
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
145
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
146
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
147
			'Security-protection'                  => 'security-protection/security-protection.php',
148
			'Login Security'                       => 'login-security/login-security.php',
149
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
150
			'Wordfence Security'                   => 'wordfence/wordfence.php',
151
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
152
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
153
		),
154
		'random-redirect'   => array(
155
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
156
		),
157
		'related-posts'     => array(
158
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
159
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
160
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
161
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
162
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
163
			'outbrain'                             => 'outbrain/outbrain.php',
164
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
165
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
166
		),
167
		'sharedaddy'        => array(
168
			'AddThis'                              => 'addthis/addthis_social_widget.php',
169
			'Add To Any'                           => 'add-to-any/add-to-any.php',
170
			'ShareThis'                            => 'share-this/sharethis.php',
171
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
172
		),
173
		'seo-tools' => array(
174
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
175
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
176
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
177
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
178
		),
179
		'verification-tools' => array(
180
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
181
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
182
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
183
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
184
		),
185
		'widget-visibility' => array(
186
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
187
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
188
		),
189
		'sitemaps' => array(
190
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
191
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
192
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
193
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
194
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
195
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
196
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
197
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
198
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
199
			'Sitemap'                              => 'sitemap/sitemap.php',
200
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
201
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
202
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
203
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
204
		),
205
	);
206
207
	/**
208
	 * Plugins for which we turn off our Facebook OG Tags implementation.
209
	 *
210
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
211
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
212
	 *
213
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
214
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
215
	 */
216
	private $open_graph_conflicting_plugins = array(
217
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
218
		                                                         // 2 Click Social Media Buttons
219
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
220
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
221
		'autodescription/autodescription.php',                   // The SEO Framework
222
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
223
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
224
		                                                         // Open Graph Meta Tags by Heateor
225
		'facebook/facebook.php',                                 // Facebook (official plugin)
226
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
227
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
228
		                                                         // Facebook Featured Image & OG Meta Tags
229
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
230
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
231
		                                                         // Facebook Open Graph Meta Tags for WordPress
232
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
233
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
234
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
235
		                                                         // Fedmich's Facebook Open Graph Meta
236
		'network-publisher/networkpub.php',                      // Network Publisher
237
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
238
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
239
		                                                         // NextScripts SNAP
240
		'og-tags/og-tags.php',                                   // OG Tags
241
		'opengraph/opengraph.php',                               // Open Graph
242
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
243
		                                                         // Open Graph Protocol Framework
244
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
245
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
246
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
247
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
248
		'sharepress/sharepress.php',                             // SharePress
249
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
250
		'social-discussions/social-discussions.php',             // Social Discussions
251
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
252
		'socialize/socialize.php',                               // Socialize
253
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
254
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
255
		                                                         // Tweet, Like, Google +1 and Share
256
		'wordbooker/wordbooker.php',                             // Wordbooker
257
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
258
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
259
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
260
		                                                         // WP Facebook Like Send & Open Graph Meta
261
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
262
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
263
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
264
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
265
	);
266
267
	/**
268
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
269
	 */
270
	private $twitter_cards_conflicting_plugins = array(
271
	//	'twitter/twitter.php',                       // The official one handles this on its own.
272
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
273
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
274
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
275
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
276
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
277
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
278
		'twitter-cards/twitter-cards.php',           // Twitter Cards
279
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
280
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
281
	);
282
283
	/**
284
	 * Message to display in admin_notice
285
	 * @var string
286
	 */
287
	public $message = '';
288
289
	/**
290
	 * Error to display in admin_notice
291
	 * @var string
292
	 */
293
	public $error = '';
294
295
	/**
296
	 * Modules that need more privacy description.
297
	 * @var string
298
	 */
299
	public $privacy_checks = '';
300
301
	/**
302
	 * Stats to record once the page loads
303
	 *
304
	 * @var array
305
	 */
306
	public $stats = array();
307
308
	/**
309
	 * Jetpack_Sync object
310
	 */
311
	public $sync;
312
313
	/**
314
	 * Verified data for JSON authorization request
315
	 */
316
	public $json_api_authorization_request = array();
317
318
	/**
319
	 * Holds the singleton instance of this class
320
	 * @since 2.3.3
321
	 * @var Jetpack
322
	 */
323
	static $instance = false;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $instance.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
324
325
	/**
326
	 * Singleton
327
	 * @static
328
	 */
329
	public static function init() {
330
		if ( ! self::$instance ) {
331
			self::$instance = new Jetpack;
332
333
			self::$instance->plugin_upgrade();
334
		}
335
336
		return self::$instance;
337
	}
338
339
	/**
340
	 * Must never be called statically
341
	 */
342
	function plugin_upgrade() {
343
		if ( Jetpack::is_active() ) {
344
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
345
			if ( JETPACK__VERSION != $version ) {
346
347
				// check which active modules actually exist and remove others from active_modules list
348
				$unfiltered_modules = Jetpack::get_active_modules();
349
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
350
				if ( array_diff( $unfiltered_modules, $modules ) ) {
351
					Jetpack::update_active_modules( $modules );
352
				}
353
354
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
355
356
				// Upgrade to 4.3.0
357
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
358
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
359
				}
360
361
				// Make sure Markdown for posts gets turned back on
362
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
363
					update_option( 'wpcom_publish_posts_with_markdown', true );
364
				}
365
366
				if ( did_action( 'wp_loaded' ) ) {
367
					self::upgrade_on_load();
368
				} else {
369
					add_action(
370
						'wp_loaded',
371
						array( __CLASS__, 'upgrade_on_load' )
372
					);
373
				}
374
			}
375
		}
376
	}
377
378
	/**
379
	 * Runs upgrade routines that need to have modules loaded.
380
	 */
381
	static function upgrade_on_load() {
382
383
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
384
		// This can happen in case Jetpack has been just upgraded and is
385
		// being initialized late during the page load. In this case we wait
386
		// until the next proper admin page load with Jetpack active.
387
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
388
			return;
389
		}
390
391
		Jetpack::maybe_set_version_option();
392
393
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
394
			Jetpack_Widget_Conditions::migrate_post_type_rules();
395
		}
396
	}
397
398
	static function activate_manage( ) {
399
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
400
			self::activate_module( 'manage', false, false );
401
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
402
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
403
		}
404
	}
405
406
	static function update_active_modules( $modules ) {
407
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
408
409
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
410
411
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
412
			$new_active_modules = array_diff( $modules, $current_modules );
413
			foreach( $new_active_modules as $module ) {
414
				/**
415
				 * Fires when a specific module is activated.
416
				 *
417
				 * @since 1.9.0
418
				 *
419
				 * @param string $module Module slug.
420
				 * @param boolean $success whether the module was activated. @since 4.2
421
				 */
422
				do_action( 'jetpack_activate_module', $module, $success );
423
424
				/**
425
				 * Fires when a module is activated.
426
				 * The dynamic part of the filter, $module, is the module slug.
427
				 *
428
				 * @since 1.9.0
429
				 *
430
				 * @param string $module Module slug.
431
				 */
432
				do_action( "jetpack_activate_module_$module", $module );
433
			}
434
435
			$new_deactive_modules = array_diff( $current_modules, $modules );
436
			foreach( $new_deactive_modules as $module ) {
437
				/**
438
				 * Fired after a module has been deactivated.
439
				 *
440
				 * @since 4.2.0
441
				 *
442
				 * @param string $module Module slug.
443
				 * @param boolean $success whether the module was deactivated.
444
				 */
445
				do_action( 'jetpack_deactivate_module', $module, $success );
446
				/**
447
				 * Fires when a module is deactivated.
448
				 * The dynamic part of the filter, $module, is the module slug.
449
				 *
450
				 * @since 1.9.0
451
				 *
452
				 * @param string $module Module slug.
453
				 */
454
				do_action( "jetpack_deactivate_module_$module", $module );
455
			}
456
		}
457
458
		return $success;
459
	}
460
461
	static function delete_active_modules() {
462
		self::update_active_modules( array() );
463
	}
464
465
	/**
466
	 * Constructor.  Initializes WordPress hooks
467
	 */
468
	private function __construct() {
469
		/*
470
		 * Check for and alert any deprecated hooks
471
		 */
472
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
473
474
		/*
475
		 * Load things that should only be in Network Admin.
476
		 *
477
		 * For now blow away everything else until a more full
478
		 * understanding of what is needed at the network level is
479
		 * available
480
		 */
481
		if( is_multisite() ) {
482
			Jetpack_Network::init();
483
		}
484
485
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
486
487
		// Unlink user before deleting the user from .com
488
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
489
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
490
491
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
492
			@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...
493
494
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
495
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
496
497
			$this->require_jetpack_authentication();
498
499
			if ( Jetpack::is_active() ) {
500
				// Hack to preserve $HTTP_RAW_POST_DATA
501
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
502
503
				$signed = $this->verify_xml_rpc_signature();
504
				if ( $signed && ! is_wp_error( $signed ) ) {
505
					// The actual API methods.
506
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
507
				} else {
508
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
509
					// active Jetpack connection, so that additional users can link their account.
510
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
511
				}
512
			} else {
513
				// The bootstrap API methods.
514
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
515
			}
516
517
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
518
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
519
		} elseif (
520
			is_admin() &&
521
			isset( $_POST['action'] ) && (
522
				'jetpack_upload_file' == $_POST['action'] ||
523
				'jetpack_update_file' == $_POST['action']
524
			)
525
		) {
526
			$this->require_jetpack_authentication();
527
			$this->add_remote_request_handlers();
528
		} else {
529
			if ( Jetpack::is_active() ) {
530
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
531
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
532
			}
533
		}
534
535
		if ( Jetpack::is_active() ) {
536
			Jetpack_Heartbeat::init();
537
		}
538
539
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
540
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
541
542
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
543
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
544
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
545
		}
546
547
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
548
549
		add_action( 'admin_init', array( $this, 'admin_init' ) );
550
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
551
552
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
553
554
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
555
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
556
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
557
558
		// returns HTTPS support status
559
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
560
561
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
562
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
563
564
		// JITM AJAX callback function
565
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
566
567
		// Universal ajax callback for all tracking events triggered via js
568
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
569
570
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
571
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
572
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
573
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
574
575
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
576
577
		/**
578
		 * These actions run checks to load additional files.
579
		 * They check for external files or plugins, so they need to run as late as possible.
580
		 */
581
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
582
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
583
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
584
585
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
586
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
587
588
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
589
590
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
591
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
592
593
		// A filter to control all just in time messages
594
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
595
596
		// Update the Jetpack plan from API on heartbeats
597
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
598
599
		/**
600
		 * This is the hack to concatinate all css files into one.
601
		 * For description and reasoning see the implode_frontend_css method
602
		 *
603
		 * Super late priority so we catch all the registered styles
604
		 */
605
		if( !is_admin() ) {
606
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
607
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
608
		}
609
	}
610
611
	function jetpack_admin_ajax_tracks_callback() {
612
		// Check for nonce
613
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
614
			wp_die( 'Permissions check failed.' );
615
		}
616
617
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
618
			wp_die( 'No valid event name or type.' );
619
		}
620
621
		$tracks_data = array();
622
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
623
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
624
		}
625
626
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
627
		wp_send_json_success();
628
		wp_die();
629
	}
630
631
	/**
632
	 * The callback for the JITM ajax requests.
633
	 */
634
	function jetpack_jitm_ajax_callback() {
635
		// Check for nonce
636
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
637
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
638
		}
639
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
640
			$module_slug = $_REQUEST['jitmModule'];
641
			Jetpack::log( 'activate', $module_slug );
642
			Jetpack::activate_module( $module_slug, false, false );
643
			Jetpack::state( 'message', 'no_message' );
644
645
			//A Jetpack module is being activated through a JITM, track it
646
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
647
			$this->do_stats( 'server_side' );
648
649
			wp_send_json_success();
650
		}
651
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
652
			// get the hide_jitm options array
653
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
654
			$module_slug = $_REQUEST['jitmModule'];
655
656
			if( ! $jetpack_hide_jitm ) {
657
				$jetpack_hide_jitm = array(
658
					$module_slug => 'hide'
659
				);
660
			} else {
661
				$jetpack_hide_jitm[$module_slug] = 'hide';
662
			}
663
664
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
665
666
			//jitm is being dismissed forever, track it
667
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
668
			$this->do_stats( 'server_side' );
669
670
			wp_send_json_success();
671
		}
672 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
673
			$module_slug = $_REQUEST['jitmModule'];
674
675
			// User went to WordPress.com, track this
676
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
677
			$this->do_stats( 'server_side' );
678
679
			wp_send_json_success();
680
		}
681 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
682
			$track = $_REQUEST['jitmModule'];
683
684
			// User is viewing JITM, track it.
685
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
686
			$this->do_stats( 'server_side' );
687
688
			wp_send_json_success();
689
		}
690
	}
691
692
	/**
693
	 * If there are any stats that need to be pushed, but haven't been, push them now.
694
	 */
695
	function __destruct() {
696
		if ( ! empty( $this->stats ) ) {
697
			$this->do_stats( 'server_side' );
698
		}
699
	}
700
701
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
702
		switch( $cap ) {
703
			case 'jetpack_connect' :
704
			case 'jetpack_reconnect' :
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
705
				if ( Jetpack::is_development_mode() ) {
706
					$caps = array( 'do_not_allow' );
707
					break;
708
				}
709
				/**
710
				 * Pass through. If it's not development mode, these should match disconnect.
711
				 * Let users disconnect if it's development mode, just in case things glitch.
712
				 */
713
			case 'jetpack_disconnect' :
714
				/**
715
				 * In multisite, can individual site admins manage their own connection?
716
				 *
717
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
718
				 */
719
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
720
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
721
						/**
722
						 * We need to update the option name -- it's terribly unclear which
723
						 * direction the override goes.
724
						 *
725
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
726
						 */
727
						$caps = array( 'do_not_allow' );
728
						break;
729
					}
730
				}
731
732
				$caps = array( 'manage_options' );
733
				break;
734
			case 'jetpack_manage_modules' :
735
			case 'jetpack_activate_modules' :
736
			case 'jetpack_deactivate_modules' :
737
				$caps = array( 'manage_options' );
738
				break;
739
			case 'jetpack_configure_modules' :
740
				$caps = array( 'manage_options' );
741
				break;
742
			case 'jetpack_network_admin_page':
743
			case 'jetpack_network_settings_page':
744
				$caps = array( 'manage_network_plugins' );
745
				break;
746
			case 'jetpack_network_sites_page':
747
				$caps = array( 'manage_sites' );
748
				break;
749
			case 'jetpack_admin_page' :
750
				if ( Jetpack::is_development_mode() ) {
751
					$caps = array( 'manage_options' );
752
					break;
753
				} else {
754
					$caps = array( 'read' );
755
				}
756
				break;
757
			case 'jetpack_connect_user' :
758
				if ( Jetpack::is_development_mode() ) {
759
					$caps = array( 'do_not_allow' );
760
					break;
761
				}
762
				$caps = array( 'read' );
763
				break;
764
		}
765
		return $caps;
766
	}
767
768
	function require_jetpack_authentication() {
769
		// Don't let anyone authenticate
770
		$_COOKIE = array();
771
		remove_all_filters( 'authenticate' );
772
		remove_all_actions( 'wp_login_failed' );
773
774
		if ( Jetpack::is_active() ) {
775
			// Allow Jetpack authentication
776
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
777
		}
778
	}
779
780
	/**
781
	 * Load language files
782
	 * @action plugins_loaded
783
	 */
784
	public static function plugin_textdomain() {
785
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
786
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
787
	}
788
789
	/**
790
	 * Register assets for use in various modules and the Jetpack admin page.
791
	 *
792
	 * @uses wp_script_is, wp_register_script, plugins_url
793
	 * @action wp_loaded
794
	 * @return null
795
	 */
796
	public function register_assets() {
797
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
798
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
799
		}
800
801 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
802
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
803
		}
804
805 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
806
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
807
		}
808
809 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
810
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
811
		}
812
813
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
814
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
815
816
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
817
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
818
			if ( ! is_numeric( $fb_app_id ) ) {
819
				$fb_app_id = '';
820
			}
821
			wp_localize_script(
822
				'jetpack-facebook-embed',
823
				'jpfbembed',
824
				array(
825
					'appid' => $fb_app_id,
826
					'locale' => $this->get_locale(),
827
				)
828
			);
829
		}
830
831
		/**
832
		 * As jetpack_register_genericons is by default fired off a hook,
833
		 * the hook may have already fired by this point.
834
		 * So, let's just trigger it manually.
835
		 */
836
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
837
		jetpack_register_genericons();
838
839
		/**
840
		 * Register the social logos
841
		 */
842
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
843
		jetpack_register_social_logos();
844
845 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
846
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
847
	}
848
849
	/**
850
	 * Guess locale from language code.
851
	 *
852
	 * @param string $lang Language code.
853
	 * @return string|bool
854
	 */
855 View Code Duplication
	function guess_locale_from_lang( $lang ) {
856
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
857
			return 'en_US';
858
		}
859
860
		if ( ! class_exists( 'GP_Locales' ) ) {
861
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
862
				return false;
863
			}
864
865
			require JETPACK__GLOTPRESS_LOCALES_PATH;
866
		}
867
868
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
869
			// WP.com: get_locale() returns 'it'
870
			$locale = GP_Locales::by_slug( $lang );
871
		} else {
872
			// Jetpack: get_locale() returns 'it_IT';
873
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
874
		}
875
876
		if ( ! $locale ) {
877
			return false;
878
		}
879
880
		if ( empty( $locale->facebook_locale ) ) {
881
			if ( empty( $locale->wp_locale ) ) {
882
				return false;
883
			} else {
884
				// Facebook SDK is smart enough to fall back to en_US if a
885
				// locale isn't supported. Since supported Facebook locales
886
				// can fall out of sync, we'll attempt to use the known
887
				// wp_locale value and rely on said fallback.
888
				return $locale->wp_locale;
889
			}
890
		}
891
892
		return $locale->facebook_locale;
893
	}
894
895
	/**
896
	 * Get the locale.
897
	 *
898
	 * @return string|bool
899
	 */
900
	function get_locale() {
901
		$locale = $this->guess_locale_from_lang( get_locale() );
902
903
		if ( ! $locale ) {
904
			$locale = 'en_US';
905
		}
906
907
		return $locale;
908
	}
909
910
	/**
911
	 * Device Pixels support
912
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
913
	 */
914
	function devicepx() {
915
		if ( Jetpack::is_active() ) {
916
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
917
		}
918
	}
919
920
	/**
921
	 * Return the network_site_url so that .com knows what network this site is a part of.
922
	 * @param  bool $option
923
	 * @return string
924
	 */
925
	public function jetpack_main_network_site_option( $option ) {
926
		return network_site_url();
927
	}
928
	/**
929
	 * Network Name.
930
	 */
931
	static function network_name( $option = null ) {
932
		global $current_site;
933
		return $current_site->site_name;
934
	}
935
	/**
936
	 * Does the network allow new user and site registrations.
937
	 * @return string
938
	 */
939
	static function network_allow_new_registrations( $option = null ) {
940
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
941
	}
942
	/**
943
	 * Does the network allow admins to add new users.
944
	 * @return boolian
945
	 */
946
	static function network_add_new_users( $option = null ) {
947
		return (bool) get_site_option( 'add_new_users' );
948
	}
949
	/**
950
	 * File upload psace left per site in MB.
951
	 *  -1 means NO LIMIT.
952
	 * @return number
953
	 */
954
	static function network_site_upload_space( $option = null ) {
955
		// value in MB
956
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
957
	}
958
959
	/**
960
	 * Network allowed file types.
961
	 * @return string
962
	 */
963
	static function network_upload_file_types( $option = null ) {
964
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
965
	}
966
967
	/**
968
	 * Maximum file upload size set by the network.
969
	 * @return number
970
	 */
971
	static function network_max_upload_file_size( $option = null ) {
972
		// value in KB
973
		return get_site_option( 'fileupload_maxk', 300 );
974
	}
975
976
	/**
977
	 * Lets us know if a site allows admins to manage the network.
978
	 * @return array
979
	 */
980
	static function network_enable_administration_menus( $option = null ) {
981
		return get_site_option( 'menu_items' );
982
	}
983
984
	/**
985
	 * If a user has been promoted to or demoted from admin, we need to clear the
986
	 * jetpack_other_linked_admins transient.
987
	 *
988
	 * @since 4.3.2
989
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
990
	 *
991
	 * @param int    $user_id   The user ID whose role changed.
992
	 * @param string $role      The new role.
993
	 * @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...
994
	 */
995
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
996
		if ( 'administrator' == $role
997
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
998
			|| is_null( $old_roles )
999
		) {
1000
			delete_transient( 'jetpack_other_linked_admins' );
1001
		}
1002
	}
1003
1004
	/**
1005
	 * Checks to see if there are any other users available to become primary
1006
	 * Users must both:
1007
	 * - Be linked to wpcom
1008
	 * - Be an admin
1009
	 *
1010
	 * @return mixed False if no other users are linked, Int if there are.
1011
	 */
1012
	static function get_other_linked_admins() {
1013
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1014
1015
		if ( false === $other_linked_users ) {
1016
			$admins = get_users( array( 'role' => 'administrator' ) );
1017
			if ( count( $admins ) > 1 ) {
1018
				$available = array();
1019
				foreach ( $admins as $admin ) {
1020
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1021
						$available[] = $admin->ID;
1022
					}
1023
				}
1024
1025
				$count_connected_admins = count( $available );
1026
				if ( count( $available ) > 1 ) {
1027
					$other_linked_users = $count_connected_admins;
1028
				} else {
1029
					$other_linked_users = 0;
1030
				}
1031
			} else {
1032
				$other_linked_users = 0;
1033
			}
1034
1035
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1036
		}
1037
1038
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1039
	}
1040
1041
	/**
1042
	 * Return whether we are dealing with a multi network setup or not.
1043
	 * The reason we are type casting this is because we want to avoid the situation where
1044
	 * the result is false since when is_main_network_option return false it cases
1045
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1046
	 * database which could be set to anything as opposed to what this function returns.
1047
	 * @param  bool  $option
1048
	 *
1049
	 * @return boolean
1050
	 */
1051
	public function is_main_network_option( $option ) {
1052
		// return '1' or ''
1053
		return (string) (bool) Jetpack::is_multi_network();
1054
	}
1055
1056
	/**
1057
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1058
	 *
1059
	 * @param  string  $option
1060
	 * @return boolean
1061
	 */
1062
	public function is_multisite( $option ) {
1063
		return (string) (bool) is_multisite();
1064
	}
1065
1066
	/**
1067
	 * Implemented since there is no core is multi network function
1068
	 * Right now there is no way to tell if we which network is the dominant network on the system
1069
	 *
1070
	 * @since  3.3
1071
	 * @return boolean
1072
	 */
1073
	public static function is_multi_network() {
1074
		global  $wpdb;
1075
1076
		// if we don't have a multi site setup no need to do any more
1077
		if ( ! is_multisite() ) {
1078
			return false;
1079
		}
1080
1081
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1082
		if ( $num_sites > 1 ) {
1083
			return true;
1084
		} else {
1085
			return false;
1086
		}
1087
	}
1088
1089
	/**
1090
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1091
	 * @return null
1092
	 */
1093
	function update_jetpack_main_network_site_option() {
1094
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1095
	}
1096
	/**
1097
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1098
	 *
1099
	 */
1100
	function update_jetpack_network_settings() {
1101
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1102
		// Only sync this info for the main network site.
1103
	}
1104
1105
	/**
1106
	 * Get back if the current site is single user site.
1107
	 *
1108
	 * @return bool
1109
	 */
1110
	public static function is_single_user_site() {
1111
		global $wpdb;
1112
1113 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1114
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1115
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1116
		}
1117
		return 1 === (int) $some_users;
1118
	}
1119
1120
	/**
1121
	 * Returns true if the site has file write access false otherwise.
1122
	 * @return string ( '1' | '0' )
1123
	 **/
1124
	public static function file_system_write_access() {
1125
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1126
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1127
		}
1128
1129
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1130
1131
		$filesystem_method = get_filesystem_method();
1132
		if ( $filesystem_method === 'direct' ) {
1133
			return 1;
1134
		}
1135
1136
		ob_start();
1137
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1138
		ob_end_clean();
1139
		if ( $filesystem_credentials_are_stored ) {
1140
			return 1;
1141
		}
1142
		return 0;
1143
	}
1144
1145
	/**
1146
	 * Finds out if a site is using a version control system.
1147
	 * @return string ( '1' | '0' )
1148
	 **/
1149
	public static function is_version_controlled() {
1150
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1151
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1152
	}
1153
1154
	/**
1155
	 * Determines whether the current theme supports featured images or not.
1156
	 * @return string ( '1' | '0' )
1157
	 */
1158
	public static function featured_images_enabled() {
1159
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1160
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1161
	}
1162
1163
	/**
1164
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1165
	 *
1166
	 * @deprecated 4.7 use get_avatar_url instead.
1167
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1168
	 * @param int $size Size of the avatar image
1169
	 * @param string $default URL to a default image to use if no avatar is available
1170
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1171
	 *
1172
	 * @return array
1173
	 */
1174
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1175
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1176
		return get_avatar_url( $id_or_email, array(
1177
			'size' => $size,
1178
			'default' => $default,
1179
			'force_default' => $force_display,
1180
		) );
1181
	}
1182
1183
	/**
1184
	 * jetpack_updates is saved in the following schema:
1185
	 *
1186
	 * array (
1187
	 *      'plugins'                       => (int) Number of plugin updates available.
1188
	 *      'themes'                        => (int) Number of theme updates available.
1189
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1190
	 *      'translations'                  => (int) Number of translation updates available.
1191
	 *      'total'                         => (int) Total of all available updates.
1192
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1193
	 * )
1194
	 * @return array
1195
	 */
1196
	public static function get_updates() {
1197
		$update_data = wp_get_update_data();
1198
1199
		// Stores the individual update counts as well as the total count.
1200
		if ( isset( $update_data['counts'] ) ) {
1201
			$updates = $update_data['counts'];
1202
		}
1203
1204
		// If we need to update WordPress core, let's find the latest version number.
1205 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1206
			$cur = get_preferred_from_update_core();
1207
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1208
				$updates['wp_update_version'] = $cur->current;
1209
			}
1210
		}
1211
		return isset( $updates ) ? $updates : array();
1212
	}
1213
1214
	public static function get_update_details() {
1215
		$update_details = array(
1216
			'update_core' => get_site_transient( 'update_core' ),
1217
			'update_plugins' => get_site_transient( 'update_plugins' ),
1218
			'update_themes' => get_site_transient( 'update_themes' ),
1219
		);
1220
		return $update_details;
1221
	}
1222
1223
	public static function refresh_update_data() {
1224
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1225
1226
	}
1227
1228
	public static function refresh_theme_data() {
1229
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1230
	}
1231
1232
	/**
1233
	 * Is Jetpack active?
1234
	 */
1235
	public static function is_active() {
1236
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1237
	}
1238
1239
	/**
1240
	 * Make an API call to WordPress.com for plan status
1241
	 *
1242
	 * @uses Jetpack_Options::get_option()
1243
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1244
	 * @uses update_option()
1245
	 *
1246
	 * @access public
1247
	 * @static
1248
	 *
1249
	 * @return bool True if plan is updated, false if no update
1250
	 */
1251
	public static function refresh_active_plan_from_wpcom() {
1252
		// Make the API request
1253
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1254
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1255
1256
		// Bail if there was an error or malformed response
1257
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1258
			return false;
1259
		}
1260
1261
		// Decode the results
1262
		$results = json_decode( $response['body'], true );
1263
1264
		// Bail if there were no results or plan details returned
1265
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1266
			return false;
1267
		}
1268
1269
		// Store the option and return true if updated
1270
		return update_option( 'jetpack_active_plan', $results['plan'] );
1271
	}
1272
1273
	/**
1274
	 * Get the plan that this Jetpack site is currently using
1275
	 *
1276
	 * @uses get_option()
1277
	 *
1278
	 * @access public
1279
	 * @static
1280
	 *
1281
	 * @return array Active Jetpack plan details
1282
	 */
1283
	public static function get_active_plan() {
1284
		$plan = get_option( 'jetpack_active_plan' );
1285
1286
		// Set the default options
1287
		if ( ! $plan ) {
1288
			$plan = array(
1289
				'product_slug' => 'jetpack_free',
1290
				'supports'     => array(),
1291
				'class'        => 'free',
1292
			);
1293
		}
1294
1295
		// Define what paid modules are supported by personal plans
1296
		$personal_plans = array(
1297
			'jetpack_personal',
1298
			'jetpack_personal_monthly',
1299
			'personal-bundle',
1300
		);
1301
1302
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1303
			$plan['supports'] = array(
1304
				'akismet',
1305
			);
1306
			$plan['class'] = 'personal';
1307
		}
1308
1309
		// Define what paid modules are supported by premium plans
1310
		$premium_plans = array(
1311
			'jetpack_premium',
1312
			'jetpack_premium_monthly',
1313
			'value_bundle',
1314
		);
1315
1316 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1317
			$plan['supports'] = array(
1318
				'videopress',
1319
				'akismet',
1320
				'vaultpress',
1321
				'wordads',
1322
			);
1323
			$plan['class'] = 'premium';
1324
		}
1325
1326
		// Define what paid modules are supported by professional plans
1327
		$business_plans = array(
1328
			'jetpack_business',
1329
			'jetpack_business_monthly',
1330
			'business-bundle',
1331
		);
1332
1333 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1334
			$plan['supports'] = array(
1335
				'videopress',
1336
				'akismet',
1337
				'vaultpress',
1338
				'seo-tools',
1339
				'google-analytics',
1340
				'wordads',
1341
			);
1342
			$plan['class'] = 'business';
1343
		}
1344
1345
		// Make sure we have an array here in the event database data is stale
1346
		if ( ! isset( $plan['supports'] ) ) {
1347
			$plan['supports'] = array();
1348
		}
1349
1350
		return $plan;
1351
	}
1352
1353
	/**
1354
	 * Determine whether the active plan supports a particular feature
1355
	 *
1356
	 * @uses Jetpack::get_active_plan()
1357
	 *
1358
	 * @access public
1359
	 * @static
1360
	 *
1361
	 * @return bool True if plan supports feature, false if not
1362
	 */
1363
	public static function active_plan_supports( $feature ) {
1364
		$plan = Jetpack::get_active_plan();
1365
1366
		if ( in_array( $feature, $plan['supports'] ) ) {
1367
			return true;
1368
		}
1369
1370
		return false;
1371
	}
1372
1373
	/**
1374
	 * Is Jetpack in development (offline) mode?
1375
	 */
1376
	public static function is_development_mode() {
1377
		$development_mode = false;
1378
1379
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1380
			$development_mode = JETPACK_DEV_DEBUG;
1381
		} elseif ( $site_url = site_url() ) {
1382
			$development_mode = false === strpos( $site_url, '.' );
1383
		}
1384
1385
		/**
1386
		 * Filters Jetpack's development mode.
1387
		 *
1388
		 * @see https://jetpack.com/support/development-mode/
1389
		 *
1390
		 * @since 2.2.1
1391
		 *
1392
		 * @param bool $development_mode Is Jetpack's development mode active.
1393
		 */
1394
		return apply_filters( 'jetpack_development_mode', $development_mode );
1395
	}
1396
1397
	/**
1398
	* Get Jetpack development mode notice text and notice class.
1399
	*
1400
	* Mirrors the checks made in Jetpack::is_development_mode
1401
	*
1402
	*/
1403
	public static function show_development_mode_notice() {
1404
		if ( Jetpack::is_development_mode() ) {
1405
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1406
				$notice = sprintf(
1407
					/* translators: %s is a URL */
1408
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1409
					'https://jetpack.com/support/development-mode/'
1410
				);
1411
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1412
				$notice = sprintf(
1413
					/* translators: %s is a URL */
1414
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1415
					'https://jetpack.com/support/development-mode/'
1416
				);
1417
			} else {
1418
				$notice = sprintf(
1419
					/* translators: %s is a URL */
1420
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1421
					'https://jetpack.com/support/development-mode/'
1422
				);
1423
			}
1424
1425
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1426
		}
1427
1428
		// Throw up a notice if using a development version and as for feedback.
1429
		if ( Jetpack::is_development_version() ) {
1430
			/* translators: %s is a URL */
1431
			$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/' );
1432
1433
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1434
		}
1435
		// Throw up a notice if using staging mode
1436
		if ( Jetpack::is_staging_site() ) {
1437
			/* translators: %s is a URL */
1438
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1439
1440
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1441
		}
1442
	}
1443
1444
	/**
1445
	 * Whether Jetpack's version maps to a public release, or a development version.
1446
	 */
1447
	public static function is_development_version() {
1448
		/**
1449
		 * Allows filtering whether this is a development version of Jetpack.
1450
		 *
1451
		 * This filter is especially useful for tests.
1452
		 *
1453
		 * @since 4.3.0
1454
		 *
1455
		 * @param bool $development_version Is this a develoment version of Jetpack?
1456
		 */
1457
		return (bool) apply_filters(
1458
			'jetpack_development_version',
1459
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1460
		);
1461
	}
1462
1463
	/**
1464
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1465
	 */
1466
	public static function is_user_connected( $user_id = false ) {
1467
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1468
		if ( ! $user_id ) {
1469
			return false;
1470
		}
1471
1472
		return (bool) Jetpack_Data::get_access_token( $user_id );
1473
	}
1474
1475
	/**
1476
	 * Get the wpcom user data of the current|specified connected user.
1477
	 */
1478
	public static function get_connected_user_data( $user_id = null ) {
1479
		if ( ! $user_id ) {
1480
			$user_id = get_current_user_id();
1481
		}
1482
1483
		$transient_key = "jetpack_connected_user_data_$user_id";
1484
1485
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1486
			return $cached_user_data;
1487
		}
1488
1489
		Jetpack::load_xml_rpc_client();
1490
		$xml = new Jetpack_IXR_Client( array(
1491
			'user_id' => $user_id,
1492
		) );
1493
		$xml->query( 'wpcom.getUser' );
1494
		if ( ! $xml->isError() ) {
1495
			$user_data = $xml->getResponse();
1496
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1497
			return $user_data;
1498
		}
1499
1500
		return false;
1501
	}
1502
1503
	/**
1504
	 * Get the wpcom email of the current|specified connected user.
1505
	 */
1506 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1507
		if ( ! $user_id ) {
1508
			$user_id = get_current_user_id();
1509
		}
1510
		Jetpack::load_xml_rpc_client();
1511
		$xml = new Jetpack_IXR_Client( array(
1512
			'user_id' => $user_id,
1513
		) );
1514
		$xml->query( 'wpcom.getUserEmail' );
1515
		if ( ! $xml->isError() ) {
1516
			return $xml->getResponse();
1517
		}
1518
		return false;
1519
	}
1520
1521
	/**
1522
	 * Get the wpcom email of the master user.
1523
	 */
1524
	public static function get_master_user_email() {
1525
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1526
		if ( $master_user_id ) {
1527
			return self::get_connected_user_email( $master_user_id );
1528
		}
1529
		return '';
1530
	}
1531
1532
	function current_user_is_connection_owner() {
1533
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1534
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1535
	}
1536
1537
	/**
1538
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1539
	 */
1540
	function extra_oembed_providers() {
1541
		// Cloudup: https://dev.cloudup.com/#oembed
1542
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1543
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1544
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1545
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1546
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1547
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1548
	}
1549
1550
	/**
1551
	 * Synchronize connected user role changes
1552
	 */
1553
	function user_role_change( $user_id ) {
1554
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1555
		Jetpack_Sync_Users::user_role_change( $user_id );
1556
	}
1557
1558
	/**
1559
	 * Loads the currently active modules.
1560
	 */
1561
	public static function load_modules() {
1562
		if ( ! self::is_active() && !self::is_development_mode() ) {
1563
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1564
				return;
1565
			}
1566
		}
1567
1568
		$version = Jetpack_Options::get_option( 'version' );
1569 View Code Duplication
		if ( ! $version ) {
1570
			$version = $old_version = JETPACK__VERSION . ':' . time();
1571
			/** This action is documented in class.jetpack.php */
1572
			do_action( 'updating_jetpack_version', $version, false );
1573
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1574
		}
1575
		list( $version ) = explode( ':', $version );
1576
1577
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1578
1579
		$modules_data = array();
1580
1581
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1582
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1583
			$updated_modules = array();
1584
			foreach ( $modules as $module ) {
1585
				$modules_data[ $module ] = Jetpack::get_module( $module );
1586
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1587
					continue;
1588
				}
1589
1590
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1591
					continue;
1592
				}
1593
1594
				$updated_modules[] = $module;
1595
			}
1596
1597
			$modules = array_diff( $modules, $updated_modules );
1598
		}
1599
1600
		$is_development_mode = Jetpack::is_development_mode();
1601
1602
		foreach ( $modules as $index => $module ) {
1603
			// If we're in dev mode, disable modules requiring a connection
1604
			if ( $is_development_mode ) {
1605
				// Prime the pump if we need to
1606
				if ( empty( $modules_data[ $module ] ) ) {
1607
					$modules_data[ $module ] = Jetpack::get_module( $module );
1608
				}
1609
				// If the module requires a connection, but we're in local mode, don't include it.
1610
				if ( $modules_data[ $module ]['requires_connection'] ) {
1611
					continue;
1612
				}
1613
			}
1614
1615
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1616
				continue;
1617
			}
1618
1619
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1620
				unset( $modules[ $index ] );
1621
				self::update_active_modules( array_values( $modules ) );
1622
				continue;
1623
			}
1624
1625
			/**
1626
			 * Fires when a specific module is loaded.
1627
			 * The dynamic part of the hook, $module, is the module slug.
1628
			 *
1629
			 * @since 1.1.0
1630
			 */
1631
			do_action( 'jetpack_module_loaded_' . $module );
1632
		}
1633
1634
		/**
1635
		 * Fires when all the modules are loaded.
1636
		 *
1637
		 * @since 1.1.0
1638
		 */
1639
		do_action( 'jetpack_modules_loaded' );
1640
1641
		// 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.
1642
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1643
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1644
	}
1645
1646
	/**
1647
	 * Check if Jetpack's REST API compat file should be included
1648
	 * @action plugins_loaded
1649
	 * @return null
1650
	 */
1651
	public function check_rest_api_compat() {
1652
		/**
1653
		 * Filters the list of REST API compat files to be included.
1654
		 *
1655
		 * @since 2.2.5
1656
		 *
1657
		 * @param array $args Array of REST API compat files to include.
1658
		 */
1659
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1660
1661
		if ( function_exists( 'bbpress' ) )
1662
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1663
1664
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1665
			require_once $_jetpack_rest_api_compat_include;
1666
	}
1667
1668
	/**
1669
	 * Gets all plugins currently active in values, regardless of whether they're
1670
	 * traditionally activated or network activated.
1671
	 *
1672
	 * @todo Store the result in core's object cache maybe?
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
1673
	 */
1674
	public static function get_active_plugins() {
1675
		$active_plugins = (array) get_option( 'active_plugins', array() );
1676
1677
		if ( is_multisite() ) {
1678
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1679
			// whereas active_plugins stores them in the values.
1680
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1681
			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...
1682
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1683
			}
1684
		}
1685
1686
		sort( $active_plugins );
1687
1688
		return array_unique( $active_plugins );
1689
	}
1690
1691
	/**
1692
	 * Gets and parses additional plugin data to send with the heartbeat data
1693
	 *
1694
	 * @since 3.8.1
1695
	 *
1696
	 * @return array Array of plugin data
1697
	 */
1698
	public static function get_parsed_plugin_data() {
1699
		if ( ! function_exists( 'get_plugins' ) ) {
1700
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1701
		}
1702
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1703
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1704
		$active_plugins = Jetpack::get_active_plugins();
1705
1706
		$plugins = array();
1707
		foreach ( $all_plugins as $path => $plugin_data ) {
1708
			$plugins[ $path ] = array(
1709
					'is_active' => in_array( $path, $active_plugins ),
1710
					'file'      => $path,
1711
					'name'      => $plugin_data['Name'],
1712
					'version'   => $plugin_data['Version'],
1713
					'author'    => $plugin_data['Author'],
1714
			);
1715
		}
1716
1717
		return $plugins;
1718
	}
1719
1720
	/**
1721
	 * Gets and parses theme data to send with the heartbeat data
1722
	 *
1723
	 * @since 3.8.1
1724
	 *
1725
	 * @return array Array of theme data
1726
	 */
1727
	public static function get_parsed_theme_data() {
1728
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1729
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1730
1731
		$themes = array();
1732
		foreach ( $all_themes as $slug => $theme_data ) {
1733
			$theme_headers = array();
1734
			foreach ( $header_keys as $header_key ) {
1735
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1736
			}
1737
1738
			$themes[ $slug ] = array(
1739
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1740
					'slug' => $slug,
1741
					'theme_root' => $theme_data->get_theme_root_uri(),
1742
					'parent' => $theme_data->parent(),
1743
					'headers' => $theme_headers
1744
			);
1745
		}
1746
1747
		return $themes;
1748
	}
1749
1750
	/**
1751
	 * Checks whether a specific plugin is active.
1752
	 *
1753
	 * We don't want to store these in a static variable, in case
1754
	 * there are switch_to_blog() calls involved.
1755
	 */
1756
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1757
		return in_array( $plugin, self::get_active_plugins() );
1758
	}
1759
1760
	/**
1761
	 * Check if Jetpack's Open Graph tags should be used.
1762
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1763
	 *
1764
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1765
	 * @action plugins_loaded
1766
	 * @return null
1767
	 */
1768
	public function check_open_graph() {
1769
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1770
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1771
		}
1772
1773
		$active_plugins = self::get_active_plugins();
1774
1775
		if ( ! empty( $active_plugins ) ) {
1776
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1777
				if ( in_array( $plugin, $active_plugins ) ) {
1778
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1779
					break;
1780
				}
1781
			}
1782
		}
1783
1784
		/**
1785
		 * Allow the addition of Open Graph Meta Tags to all pages.
1786
		 *
1787
		 * @since 2.0.3
1788
		 *
1789
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1790
		 */
1791
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1792
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1793
		}
1794
	}
1795
1796
	/**
1797
	 * Check if Jetpack's Twitter tags should be used.
1798
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1799
	 *
1800
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1801
	 * @action plugins_loaded
1802
	 * @return null
1803
	 */
1804
	public function check_twitter_tags() {
1805
1806
		$active_plugins = self::get_active_plugins();
1807
1808
		if ( ! empty( $active_plugins ) ) {
1809
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1810
				if ( in_array( $plugin, $active_plugins ) ) {
1811
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1812
					break;
1813
				}
1814
			}
1815
		}
1816
1817
		/**
1818
		 * Allow Twitter Card Meta tags to be disabled.
1819
		 *
1820
		 * @since 2.6.0
1821
		 *
1822
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1823
		 */
1824
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1825
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1826
		}
1827
	}
1828
1829
	/**
1830
	 * Allows plugins to submit security reports.
1831
 	 *
1832
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1833
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1834
	 * @param array   $args         See definitions above
1835
	 */
1836
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1837
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1838
	}
1839
1840
/* Jetpack Options API */
1841
1842
	public static function get_option_names( $type = 'compact' ) {
1843
		return Jetpack_Options::get_option_names( $type );
1844
	}
1845
1846
	/**
1847
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1848
 	 *
1849
	 * @param string $name    Option name
1850
	 * @param mixed  $default (optional)
1851
	 */
1852
	public static function get_option( $name, $default = false ) {
1853
		return Jetpack_Options::get_option( $name, $default );
1854
	}
1855
1856
	/**
1857
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1858
 	 *
1859
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1860
	 * @param string $name  Option name
1861
	 * @param mixed  $value Option value
1862
	 */
1863
	public static function update_option( $name, $value ) {
1864
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1865
		return Jetpack_Options::update_option( $name, $value );
1866
	}
1867
1868
	/**
1869
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1870
 	 *
1871
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1872
	 * @param array $array array( option name => option value, ... )
1873
	 */
1874
	public static function update_options( $array ) {
1875
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1876
		return Jetpack_Options::update_options( $array );
1877
	}
1878
1879
	/**
1880
	 * Deletes the given option.  May be passed multiple option names as an array.
1881
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1882
	 *
1883
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1884
	 * @param string|array $names
1885
	 */
1886
	public static function delete_option( $names ) {
1887
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1888
		return Jetpack_Options::delete_option( $names );
1889
	}
1890
1891
	/**
1892
	 * Enters a user token into the user_tokens option
1893
	 *
1894
	 * @param int $user_id
1895
	 * @param string $token
1896
	 * return bool
1897
	 */
1898
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1899
		// not designed for concurrent updates
1900
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1901
		if ( ! is_array( $user_tokens ) )
1902
			$user_tokens = array();
1903
		$user_tokens[$user_id] = $token;
1904
		if ( $is_master_user ) {
1905
			$master_user = $user_id;
1906
			$options     = compact( 'user_tokens', 'master_user' );
1907
		} else {
1908
			$options = compact( 'user_tokens' );
1909
		}
1910
		return Jetpack_Options::update_options( $options );
1911
	}
1912
1913
	/**
1914
	 * Returns an array of all PHP files in the specified absolute path.
1915
	 * Equivalent to glob( "$absolute_path/*.php" ).
1916
	 *
1917
	 * @param string $absolute_path The absolute path of the directory to search.
1918
	 * @return array Array of absolute paths to the PHP files.
1919
	 */
1920
	public static function glob_php( $absolute_path ) {
1921
		if ( function_exists( 'glob' ) ) {
1922
			return glob( "$absolute_path/*.php" );
1923
		}
1924
1925
		$absolute_path = untrailingslashit( $absolute_path );
1926
		$files = array();
1927
		if ( ! $dir = @opendir( $absolute_path ) ) {
1928
			return $files;
1929
		}
1930
1931
		while ( false !== $file = readdir( $dir ) ) {
1932
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1933
				continue;
1934
			}
1935
1936
			$file = "$absolute_path/$file";
1937
1938
			if ( ! is_file( $file ) ) {
1939
				continue;
1940
			}
1941
1942
			$files[] = $file;
1943
		}
1944
1945
		closedir( $dir );
1946
1947
		return $files;
1948
	}
1949
1950
	public static function activate_new_modules( $redirect = false ) {
1951
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1952
			return;
1953
		}
1954
1955
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1956 View Code Duplication
		if ( ! $jetpack_old_version ) {
1957
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1958
			/** This action is documented in class.jetpack.php */
1959
			do_action( 'updating_jetpack_version', $version, false );
1960
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1961
		}
1962
1963
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1964
1965
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1966
			return;
1967
		}
1968
1969
		$active_modules     = Jetpack::get_active_modules();
1970
		$reactivate_modules = array();
1971
		foreach ( $active_modules as $active_module ) {
1972
			$module = Jetpack::get_module( $active_module );
1973
			if ( ! isset( $module['changed'] ) ) {
1974
				continue;
1975
			}
1976
1977
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1978
				continue;
1979
			}
1980
1981
			$reactivate_modules[] = $active_module;
1982
			Jetpack::deactivate_module( $active_module );
1983
		}
1984
1985
		$new_version = JETPACK__VERSION . ':' . time();
1986
		/** This action is documented in class.jetpack.php */
1987
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1988
		Jetpack_Options::update_options(
1989
			array(
1990
				'version'     => $new_version,
1991
				'old_version' => $jetpack_old_version,
1992
			)
1993
		);
1994
1995
		Jetpack::state( 'message', 'modules_activated' );
1996
		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...
1997
1998
		if ( $redirect ) {
1999
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2000
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2001
				$page = $_GET['page'];
2002
			}
2003
2004
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2005
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_new_modules() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2006
		}
2007
	}
2008
2009
	/**
2010
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2011
	 * Make sure to tuck away module "library" files in a sub-directory.
2012
	 */
2013
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2014
		static $modules = null;
2015
2016
		if ( ! isset( $modules ) ) {
2017
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2018
			// Use the cache if we're on the front-end and it's available...
2019
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2020
				$modules = $available_modules_option[ JETPACK__VERSION ];
2021
			} else {
2022
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2023
2024
				$modules = array();
2025
2026
				foreach ( $files as $file ) {
2027
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2028
						continue;
2029
					}
2030
2031
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2032
				}
2033
2034
				Jetpack_Options::update_option( 'available_modules', array(
2035
					JETPACK__VERSION => $modules,
2036
				) );
2037
			}
2038
		}
2039
2040
		/**
2041
		 * Filters the array of modules available to be activated.
2042
		 *
2043
		 * @since 2.4.0
2044
		 *
2045
		 * @param array $modules Array of available modules.
2046
		 * @param string $min_version Minimum version number required to use modules.
2047
		 * @param string $max_version Maximum version number required to use modules.
2048
		 */
2049
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2050
2051
		if ( ! $min_version && ! $max_version ) {
2052
			return array_keys( $mods );
2053
		}
2054
2055
		$r = array();
2056
		foreach ( $mods as $slug => $introduced ) {
2057
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2058
				continue;
2059
			}
2060
2061
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2062
				continue;
2063
			}
2064
2065
			$r[] = $slug;
2066
		}
2067
2068
		return $r;
2069
	}
2070
2071
	/**
2072
	 * Default modules loaded on activation.
2073
	 */
2074
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2075
		$return = array();
2076
2077
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2078
			$module_data = Jetpack::get_module( $module );
2079
2080
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2081
				case 'yes' :
2082
					$return[] = $module;
2083
					break;
2084
				case 'public' :
2085
					if ( Jetpack_Options::get_option( 'public' ) ) {
2086
						$return[] = $module;
2087
					}
2088
					break;
2089
				case 'no' :
2090
				default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2091
					break;
2092
			}
2093
		}
2094
		/**
2095
		 * Filters the array of default modules.
2096
		 *
2097
		 * @since 2.5.0
2098
		 *
2099
		 * @param array $return Array of default modules.
2100
		 * @param string $min_version Minimum version number required to use modules.
2101
		 * @param string $max_version Maximum version number required to use modules.
2102
		 */
2103
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2104
	}
2105
2106
	/**
2107
	 * Checks activated modules during auto-activation to determine
2108
	 * if any of those modules are being deprecated.  If so, close
2109
	 * them out, and add any replacement modules.
2110
	 *
2111
	 * Runs at priority 99 by default.
2112
	 *
2113
	 * This is run late, so that it can still activate a module if
2114
	 * the new module is a replacement for another that the user
2115
	 * currently has active, even if something at the normal priority
2116
	 * would kibosh everything.
2117
	 *
2118
	 * @since 2.6
2119
	 * @uses jetpack_get_default_modules filter
2120
	 * @param array $modules
2121
	 * @return array
2122
	 */
2123
	function handle_deprecated_modules( $modules ) {
2124
		$deprecated_modules = array(
2125
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2126
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2127
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2128
		);
2129
2130
		// Don't activate SSO if they never completed activating WPCC.
2131
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2132
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2133
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2134
				$deprecated_modules['wpcc'] = null;
2135
			}
2136
		}
2137
2138
		foreach ( $deprecated_modules as $module => $replacement ) {
2139
			if ( Jetpack::is_module_active( $module ) ) {
2140
				self::deactivate_module( $module );
2141
				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...
2142
					$modules[] = $replacement;
2143
				}
2144
			}
2145
		}
2146
2147
		return array_unique( $modules );
2148
	}
2149
2150
	/**
2151
	 * Checks activated plugins during auto-activation to determine
2152
	 * if any of those plugins are in the list with a corresponding module
2153
	 * that is not compatible with the plugin. The module will not be allowed
2154
	 * to auto-activate.
2155
	 *
2156
	 * @since 2.6
2157
	 * @uses jetpack_get_default_modules filter
2158
	 * @param array $modules
2159
	 * @return array
2160
	 */
2161
	function filter_default_modules( $modules ) {
2162
2163
		$active_plugins = self::get_active_plugins();
2164
2165
		if ( ! empty( $active_plugins ) ) {
2166
2167
			// For each module we'd like to auto-activate...
2168
			foreach ( $modules as $key => $module ) {
2169
				// If there are potential conflicts for it...
2170
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2171
					// For each potential conflict...
2172
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2173
						// If that conflicting plugin is active...
2174
						if ( in_array( $plugin, $active_plugins ) ) {
2175
							// Remove that item from being auto-activated.
2176
							unset( $modules[ $key ] );
2177
						}
2178
					}
2179
				}
2180
			}
2181
		}
2182
2183
		return $modules;
2184
	}
2185
2186
	/**
2187
	 * Extract a module's slug from its full path.
2188
	 */
2189
	public static function get_module_slug( $file ) {
2190
		return str_replace( '.php', '', basename( $file ) );
2191
	}
2192
2193
	/**
2194
	 * Generate a module's path from its slug.
2195
	 */
2196
	public static function get_module_path( $slug ) {
2197
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2198
	}
2199
2200
	/**
2201
	 * Load module data from module file. Headers differ from WordPress
2202
	 * plugin headers to avoid them being identified as standalone
2203
	 * plugins on the WordPress plugins page.
2204
	 */
2205
	public static function get_module( $module ) {
2206
		$headers = array(
2207
			'name'                      => 'Module Name',
2208
			'description'               => 'Module Description',
2209
			'jumpstart_desc'            => 'Jumpstart Description',
2210
			'sort'                      => 'Sort Order',
2211
			'recommendation_order'      => 'Recommendation Order',
2212
			'introduced'                => 'First Introduced',
2213
			'changed'                   => 'Major Changes In',
2214
			'deactivate'                => 'Deactivate',
2215
			'free'                      => 'Free',
2216
			'requires_connection'       => 'Requires Connection',
2217
			'auto_activate'             => 'Auto Activate',
2218
			'module_tags'               => 'Module Tags',
2219
			'feature'                   => 'Feature',
2220
			'additional_search_queries' => 'Additional Search Queries',
2221
		);
2222
2223
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2224
2225
		$mod = Jetpack::get_file_data( $file, $headers );
2226
		if ( empty( $mod['name'] ) ) {
2227
			return false;
2228
		}
2229
2230
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2231
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2232
		$mod['deactivate']              = empty( $mod['deactivate'] );
2233
		$mod['free']                    = empty( $mod['free'] );
2234
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2235
2236
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2237
			$mod['auto_activate'] = 'No';
2238
		} else {
2239
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2240
		}
2241
2242
		if ( $mod['module_tags'] ) {
2243
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2244
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2245
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2246
		} else {
2247
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2248
		}
2249
2250
		if ( $mod['feature'] ) {
2251
			$mod['feature'] = explode( ',', $mod['feature'] );
2252
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2253
		} else {
2254
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2255
		}
2256
2257
		/**
2258
		 * Filters the feature array on a module.
2259
		 *
2260
		 * This filter allows you to control where each module is filtered: Recommended,
2261
		 * Jumpstart, and the default "Other" listing.
2262
		 *
2263
		 * @since 3.5.0
2264
		 *
2265
		 * @param array   $mod['feature'] The areas to feature this module:
2266
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2267
		 *     'Recommended' shows on the main Jetpack admin screen.
2268
		 *     'Other' should be the default if no other value is in the array.
2269
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2270
		 * @param array   $mod All the currently assembled module data.
2271
		 */
2272
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2273
2274
		/**
2275
		 * Filter the returned data about a module.
2276
		 *
2277
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2278
		 * so please be careful.
2279
		 *
2280
		 * @since 3.6.0
2281
		 *
2282
		 * @param array   $mod    The details of the requested module.
2283
		 * @param string  $module The slug of the module, e.g. sharedaddy
2284
		 * @param string  $file   The path to the module source file.
2285
		 */
2286
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2287
	}
2288
2289
	/**
2290
	 * Like core's get_file_data implementation, but caches the result.
2291
	 */
2292
	public static function get_file_data( $file, $headers ) {
2293
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2294
		$file_name = basename( $file );
2295
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2296
		$key              = md5( $file_name . serialize( $headers ) );
2297
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2298
2299
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2300
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2301
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2302
		}
2303
2304
		$data = get_file_data( $file, $headers );
2305
2306
		// Strip out any old Jetpack versions that are cluttering the option.
2307
		//
2308
		// We maintain the data for the current version of Jetpack plus the previous version
2309
		// to prevent repeated DB hits on large sites hosted with multiple web servers
2310
		// on a single database (since all web servers might not be updated simultaneously)
2311
2312
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2313
2314
		if ( count( $file_data_option ) > 2 ) {
2315
			$count = 0;
2316
			krsort( $file_data_option );
2317
			foreach ( $file_data_option as $version => $values ) {
2318
				$count++;
2319
				if ( $count > 2 && JETPACK__VERSION != $version ) {
2320
					unset( $file_data_option[ $version ] );
2321
				}
2322
			}
2323
		}
2324
2325
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2326
2327
		return $data;
2328
	}
2329
2330
2331
	/**
2332
	 * Return translated module tag.
2333
	 *
2334
	 * @param string $tag Tag as it appears in each module heading.
2335
	 *
2336
	 * @return mixed
2337
	 */
2338
	public static function translate_module_tag( $tag ) {
2339
		return jetpack_get_module_i18n_tag( $tag );
2340
	}
2341
2342
	/**
2343
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2344
	 *
2345
	 * @since 3.9.2
2346
	 *
2347
	 * @param array $modules
2348
	 *
2349
	 * @return string|void
2350
	 */
2351
	public static function get_translated_modules( $modules ) {
2352
		foreach ( $modules as $index => $module ) {
2353
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2354
			if ( isset( $module['name'] ) ) {
2355
				$modules[ $index ]['name'] = $i18n_module['name'];
2356
			}
2357
			if ( isset( $module['description'] ) ) {
2358
				$modules[ $index ]['description'] = $i18n_module['description'];
2359
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2360
			}
2361
		}
2362
		return $modules;
2363
	}
2364
2365
	/**
2366
	 * Get a list of activated modules as an array of module slugs.
2367
	 */
2368
	public static function get_active_modules() {
2369
		$active = Jetpack_Options::get_option( 'active_modules' );
2370
2371
		if ( ! is_array( $active ) ) {
2372
			$active = array();
2373
		}
2374
2375
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2376
			$active[] = 'vaultpress';
2377
		} else {
2378
			$active = array_diff( $active, array( 'vaultpress' ) );
2379
		}
2380
2381
		//If protect is active on the main site of a multisite, it should be active on all sites.
2382
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2383
			$active[] = 'protect';
2384
		}
2385
2386
		return array_unique( $active );
2387
	}
2388
2389
	/**
2390
	 * Check whether or not a Jetpack module is active.
2391
	 *
2392
	 * @param string $module The slug of a Jetpack module.
2393
	 * @return bool
2394
	 *
2395
	 * @static
2396
	 */
2397
	public static function is_module_active( $module ) {
2398
		return in_array( $module, self::get_active_modules() );
2399
	}
2400
2401
	public static function is_module( $module ) {
2402
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2403
	}
2404
2405
	/**
2406
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2407
	 *
2408
	 * @param bool $catch True to start catching, False to stop.
2409
	 *
2410
	 * @static
2411
	 */
2412
	public static function catch_errors( $catch ) {
2413
		static $display_errors, $error_reporting;
2414
2415
		if ( $catch ) {
2416
			$display_errors  = @ini_set( 'display_errors', 1 );
2417
			$error_reporting = @error_reporting( E_ALL );
2418
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2419
		} else {
2420
			@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...
2421
			@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...
2422
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2423
		}
2424
	}
2425
2426
	/**
2427
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2428
	 */
2429
	public static function catch_errors_on_shutdown() {
2430
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2431
	}
2432
2433
	/**
2434
	 * Rewrite any string to make paths easier to read.
2435
	 *
2436
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2437
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2438
	 *
2439
	 * @param $string
2440
	 * @return mixed
2441
	 */
2442
	public static function alias_directories( $string ) {
2443
		// ABSPATH has a trailing slash.
2444
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2445
		// WP_CONTENT_DIR does not have a trailing slash.
2446
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2447
2448
		return $string;
2449
	}
2450
2451
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2452
		$jetpack = Jetpack::init();
2453
2454
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2455
		$modules = array_merge( $other_modules, $modules );
2456
2457
		// Look for standalone plugins and disable if active.
2458
2459
		$to_deactivate = array();
2460
		foreach ( $modules as $module ) {
2461
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2462
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2463
			}
2464
		}
2465
2466
		$deactivated = array();
2467
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2468
			list( $probable_file, $probable_title ) = $deactivate_me;
2469
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2470
				$deactivated[] = $module;
2471
			}
2472
		}
2473
2474
		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...
2475
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2476
2477
			$url = add_query_arg(
2478
				array(
2479
					'action'   => 'activate_default_modules',
2480
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2481
				),
2482
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2483
			);
2484
			wp_safe_redirect( $url );
2485
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_default_modules() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2486
		}
2487
2488
		/**
2489
		 * Fires before default modules are activated.
2490
		 *
2491
		 * @since 1.9.0
2492
		 *
2493
		 * @param string $min_version Minimum version number required to use modules.
2494
		 * @param string $max_version Maximum version number required to use modules.
2495
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2496
		 */
2497
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2498
2499
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2500
		Jetpack::restate();
2501
		Jetpack::catch_errors( true );
2502
2503
		$active = Jetpack::get_active_modules();
2504
2505
		foreach ( $modules as $module ) {
2506
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2507
				$active[] = $module;
2508
				self::update_active_modules( $active );
2509
				continue;
2510
			}
2511
2512
			if ( in_array( $module, $active ) ) {
2513
				$module_info = Jetpack::get_module( $module );
2514
				if ( ! $module_info['deactivate'] ) {
2515
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2516 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2517
						$active_state = explode( ',', $active_state );
2518
					} else {
2519
						$active_state = array();
2520
					}
2521
					$active_state[] = $module;
2522
					Jetpack::state( $state, implode( ',', $active_state ) );
2523
				}
2524
				continue;
2525
			}
2526
2527
			$file = Jetpack::get_module_path( $module );
2528
			if ( ! file_exists( $file ) ) {
2529
				continue;
2530
			}
2531
2532
			// we'll override this later if the plugin can be included without fatal error
2533
			if ( $redirect ) {
2534
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2535
			}
2536
			Jetpack::state( 'error', 'module_activation_failed' );
2537
			Jetpack::state( 'module', $module );
2538
			ob_start();
2539
			require $file;
2540
2541
			$active[] = $module;
2542
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2543 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2544
				$active_state = explode( ',', $active_state );
2545
			} else {
2546
				$active_state = array();
2547
			}
2548
			$active_state[] = $module;
2549
			Jetpack::state( $state, implode( ',', $active_state ) );
2550
			Jetpack::update_active_modules( $active );
2551
2552
			ob_end_clean();
2553
		}
2554
		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...
2555
		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...
2556
		Jetpack::catch_errors( false );
2557
		/**
2558
		 * Fires when default modules are activated.
2559
		 *
2560
		 * @since 1.9.0
2561
		 *
2562
		 * @param string $min_version Minimum version number required to use modules.
2563
		 * @param string $max_version Maximum version number required to use modules.
2564
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2565
		 */
2566
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2567
	}
2568
2569
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2570
		/**
2571
		 * Fires before a module is activated.
2572
		 *
2573
		 * @since 2.6.0
2574
		 *
2575
		 * @param string $module Module slug.
2576
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2577
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2578
		 */
2579
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2580
2581
		$jetpack = Jetpack::init();
2582
2583
		if ( ! strlen( $module ) )
2584
			return false;
2585
2586
		if ( ! Jetpack::is_module( $module ) )
2587
			return false;
2588
2589
		// If it's already active, then don't do it again
2590
		$active = Jetpack::get_active_modules();
2591
		foreach ( $active as $act ) {
2592
			if ( $act == $module )
2593
				return true;
2594
		}
2595
2596
		$module_data = Jetpack::get_module( $module );
2597
2598
		if ( ! Jetpack::is_active() ) {
2599
			if ( !Jetpack::is_development_mode() )
2600
				return false;
2601
2602
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2603
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2604
				return false;
2605
		}
2606
2607
		// Check and see if the old plugin is active
2608
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2609
			// Deactivate the old plugin
2610
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2611
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2612
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2613
				Jetpack::state( 'deactivated_plugins', $module );
2614
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2615
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2616
			}
2617
		}
2618
2619
		// Protect won't work with mis-configured IPs
2620
		if ( 'protect' === $module ) {
2621
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2622
			if ( ! jetpack_protect_get_ip() ) {
2623
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2624
				return false;
2625
			}
2626
		}
2627
2628
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2629
		Jetpack::state( 'module', $module );
2630
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2631
2632
		Jetpack::catch_errors( true );
2633
		ob_start();
2634
		require Jetpack::get_module_path( $module );
2635
		/** This action is documented in class.jetpack.php */
2636
		do_action( 'jetpack_activate_module', $module );
2637
		$active[] = $module;
2638
		Jetpack::update_active_modules( $active );
2639
2640
		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...
2641
		ob_end_clean();
2642
		Jetpack::catch_errors( false );
2643
2644
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2645 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2646
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2647
2648
			//Jump start is being dismissed send data to MC Stats
2649
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2650
2651
			$jetpack->do_stats( 'server_side' );
2652
		}
2653
2654
		if ( $redirect ) {
2655
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2656
		}
2657
		if ( $exit ) {
2658
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2659
		}
2660
		return true;
2661
	}
2662
2663
	function activate_module_actions( $module ) {
2664
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2665
	}
2666
2667
	public static function deactivate_module( $module ) {
2668
		/**
2669
		 * Fires when a module is deactivated.
2670
		 *
2671
		 * @since 1.9.0
2672
		 *
2673
		 * @param string $module Module slug.
2674
		 */
2675
		do_action( 'jetpack_pre_deactivate_module', $module );
2676
2677
		$jetpack = Jetpack::init();
2678
2679
		$active = Jetpack::get_active_modules();
2680
		$new    = array_filter( array_diff( $active, (array) $module ) );
2681
2682
		// A flag for Jump Start so it's not shown again.
2683 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2684
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2685
2686
			//Jump start is being dismissed send data to MC Stats
2687
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2688
2689
			$jetpack->do_stats( 'server_side' );
2690
		}
2691
2692
		return self::update_active_modules( $new );
2693
	}
2694
2695
	public static function enable_module_configurable( $module ) {
2696
		$module = Jetpack::get_module_slug( $module );
2697
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2698
	}
2699
2700
	public static function module_configuration_url( $module ) {
2701
		$module = Jetpack::get_module_slug( $module );
2702
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2703
	}
2704
2705
	public static function module_configuration_load( $module, $method ) {
2706
		$module = Jetpack::get_module_slug( $module );
2707
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2708
	}
2709
2710
	public static function module_configuration_head( $module, $method ) {
2711
		$module = Jetpack::get_module_slug( $module );
2712
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2713
	}
2714
2715
	public static function module_configuration_screen( $module, $method ) {
2716
		$module = Jetpack::get_module_slug( $module );
2717
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2718
	}
2719
2720
	public static function module_configuration_activation_screen( $module, $method ) {
2721
		$module = Jetpack::get_module_slug( $module );
2722
		add_action( 'display_activate_module_setting_' . $module, $method );
2723
	}
2724
2725
/* Installation */
2726
2727
	public static function bail_on_activation( $message, $deactivate = true ) {
2728
?>
2729
<!doctype html>
2730
<html>
2731
<head>
2732
<meta charset="<?php bloginfo( 'charset' ); ?>">
2733
<style>
2734
* {
2735
	text-align: center;
2736
	margin: 0;
2737
	padding: 0;
2738
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2739
}
2740
p {
2741
	margin-top: 1em;
2742
	font-size: 18px;
2743
}
2744
</style>
2745
<body>
2746
<p><?php echo esc_html( $message ); ?></p>
2747
</body>
2748
</html>
2749
<?php
2750
		if ( $deactivate ) {
2751
			$plugins = get_option( 'active_plugins' );
2752
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2753
			$update  = false;
2754
			foreach ( $plugins as $i => $plugin ) {
2755
				if ( $plugin === $jetpack ) {
2756
					$plugins[$i] = false;
2757
					$update = true;
2758
				}
2759
			}
2760
2761
			if ( $update ) {
2762
				update_option( 'active_plugins', array_filter( $plugins ) );
2763
			}
2764
		}
2765
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method bail_on_activation() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
2766
	}
2767
2768
	/**
2769
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2770
	 * @static
2771
	 */
2772
	public static function plugin_activation( $network_wide ) {
2773
		Jetpack_Options::update_option( 'activated', 1 );
2774
2775
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2776
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2777
		}
2778
2779
		if ( $network_wide )
2780
			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...
2781
2782
		// For firing one-off events (notices) immediately after activation
2783
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2784
2785
		Jetpack::plugin_initialize();
2786
	}
2787
	/**
2788
	 * Runs before bumping version numbers up to a new version
2789
	 * @param  (string) $version    Version:timestamp
2790
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2791
	 * @return null              [description]
2792
	 */
2793
	public static function do_version_bump( $version, $old_version ) {
2794
2795
		if ( ! $old_version ) { // For new sites
2796
			// Setting up jetpack manage
2797
			Jetpack::activate_manage();
2798
		}
2799
	}
2800
2801
	/**
2802
	 * Sets the internal version number and activation state.
2803
	 * @static
2804
	 */
2805
	public static function plugin_initialize() {
2806
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2807
			Jetpack_Options::update_option( 'activated', 2 );
2808
		}
2809
2810 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2811
			$version = $old_version = JETPACK__VERSION . ':' . time();
2812
			/** This action is documented in class.jetpack.php */
2813
			do_action( 'updating_jetpack_version', $version, false );
2814
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2815
		}
2816
2817
		Jetpack::load_modules();
2818
2819
		Jetpack_Options::delete_option( 'do_activate' );
2820
	}
2821
2822
	/**
2823
	 * Removes all connection options
2824
	 * @static
2825
	 */
2826
	public static function plugin_deactivation( ) {
2827
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2828
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2829
			Jetpack_Network::init()->deactivate();
2830
		} else {
2831
			Jetpack::disconnect( false );
2832
			//Jetpack_Heartbeat::init()->deactivate();
2833
		}
2834
	}
2835
2836
	/**
2837
	 * Disconnects from the Jetpack servers.
2838
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2839
	 * @static
2840
	 */
2841
	public static function disconnect( $update_activated_state = true ) {
2842
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2843
		Jetpack::clean_nonces( true );
2844
2845
		// If the site is in an IDC because sync is not allowed,
2846
		// let's make sure to not disconnect the production site.
2847
		if ( ! self::validate_sync_error_idc_option() ) {
2848
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2849
			Jetpack::load_xml_rpc_client();
2850
			$xml = new Jetpack_IXR_Client();
2851
			$xml->query( 'jetpack.deregister' );
2852
		}
2853
2854
		Jetpack_Options::delete_option(
2855
			array(
2856
				'blog_token',
2857
				'user_token',
2858
				'user_tokens',
2859
				'master_user',
2860
				'time_diff',
2861
				'fallback_no_verify_ssl_certs',
2862
			)
2863
		);
2864
		
2865
		Jetpack_IDC::clear_all_idc_options();
2866
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
2867
2868
		if ( $update_activated_state ) {
2869
			Jetpack_Options::update_option( 'activated', 4 );
2870
		}
2871
2872
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2873
			// Check then record unique disconnection if site has never been disconnected previously
2874
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2875
				$jetpack_unique_connection['disconnected'] = 1;
2876
			} else {
2877
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2878
					//track unique disconnect
2879
					$jetpack = Jetpack::init();
2880
2881
					$jetpack->stat( 'connections', 'unique-disconnect' );
2882
					$jetpack->do_stats( 'server_side' );
2883
				}
2884
				// increment number of times disconnected
2885
				$jetpack_unique_connection['disconnected'] += 1;
2886
			}
2887
2888
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2889
		}
2890
2891
		// Delete cached connected user data
2892
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2893
		delete_transient( $transient_key );
2894
2895
		// Delete all the sync related data. Since it could be taking up space.
2896
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2897
		Jetpack_Sync_Sender::get_instance()->uninstall();
2898
2899
		// Disable the Heartbeat cron
2900
		Jetpack_Heartbeat::init()->deactivate();
2901
	}
2902
2903
	/**
2904
	 * Unlinks the current user from the linked WordPress.com user
2905
	 */
2906
	public static function unlink_user( $user_id = null ) {
2907
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2908
			return false;
2909
2910
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2911
2912
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2913
			return false;
2914
2915
		if ( ! isset( $tokens[ $user_id ] ) )
2916
			return false;
2917
2918
		Jetpack::load_xml_rpc_client();
2919
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2920
		$xml->query( 'jetpack.unlink_user', $user_id );
2921
2922
		unset( $tokens[ $user_id ] );
2923
2924
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2925
2926
		/**
2927
		 * Fires after the current user has been unlinked from WordPress.com.
2928
		 *
2929
		 * @since 4.1.0
2930
		 *
2931
		 * @param int $user_id The current user's ID.
2932
		 */
2933
		do_action( 'jetpack_unlinked_user', $user_id );
2934
2935
		return true;
2936
	}
2937
2938
	/**
2939
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2940
	 */
2941
	public static function try_registration() {
2942
		// Let's get some testing in beta versions and such.
2943
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2944
			// Before attempting to connect, let's make sure that the domains are viable.
2945
			$domains_to_check = array_unique( array(
2946
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2947
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2948
			) );
2949
			foreach ( $domains_to_check as $domain ) {
2950
				$result = Jetpack_Data::is_usable_domain( $domain );
2951
				if ( is_wp_error( $result ) ) {
2952
					return $result;
2953
				}
2954
			}
2955
		}
2956
2957
		$result = Jetpack::register();
2958
2959
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2960
		if ( ! $result || is_wp_error( $result ) ) {
2961
			return $result;
2962
		} else {
2963
			return true;
2964
		}
2965
	}
2966
2967
	/**
2968
	 * Tracking an internal event log. Try not to put too much chaff in here.
2969
	 *
2970
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2971
	 */
2972
	public static function log( $code, $data = null ) {
2973
		// only grab the latest 200 entries
2974
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2975
2976
		// Append our event to the log
2977
		$log_entry = array(
2978
			'time'    => time(),
2979
			'user_id' => get_current_user_id(),
2980
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2981
			'code'    => $code,
2982
		);
2983
		// Don't bother storing it unless we've got some.
2984
		if ( ! is_null( $data ) ) {
2985
			$log_entry['data'] = $data;
2986
		}
2987
		$log[] = $log_entry;
2988
2989
		// Try add_option first, to make sure it's not autoloaded.
2990
		// @todo: Add an add_option method to Jetpack_Options
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
2991
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2992
			Jetpack_Options::update_option( 'log', $log );
2993
		}
2994
2995
		/**
2996
		 * Fires when Jetpack logs an internal event.
2997
		 *
2998
		 * @since 3.0.0
2999
		 *
3000
		 * @param array $log_entry {
3001
		 *	Array of details about the log entry.
3002
		 *
3003
		 *	@param string time Time of the event.
3004
		 *	@param int user_id ID of the user who trigerred the event.
3005
		 *	@param int blog_id Jetpack Blog ID.
3006
		 *	@param string code Unique name for the event.
3007
		 *	@param string data Data about the event.
3008
		 * }
3009
		 */
3010
		do_action( 'jetpack_log_entry', $log_entry );
3011
	}
3012
3013
	/**
3014
	 * Get the internal event log.
3015
	 *
3016
	 * @param $event (string) - only return the specific log events
3017
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3018
	 *
3019
	 * @return array of log events || WP_Error for invalid params
3020
	 */
3021
	public static function get_log( $event = false, $num = false ) {
3022
		if ( $event && ! is_string( $event ) ) {
3023
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3024
		}
3025
3026
		if ( $num && ! is_numeric( $num ) ) {
3027
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3028
		}
3029
3030
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3031
3032
		// If nothing set - act as it did before, otherwise let's start customizing the output
3033
		if ( ! $num && ! $event ) {
3034
			return $entire_log;
3035
		} else {
3036
			$entire_log = array_reverse( $entire_log );
3037
		}
3038
3039
		$custom_log_output = array();
3040
3041
		if ( $event ) {
3042
			foreach ( $entire_log as $log_event ) {
3043
				if ( $event == $log_event[ 'code' ] ) {
3044
					$custom_log_output[] = $log_event;
3045
				}
3046
			}
3047
		} else {
3048
			$custom_log_output = $entire_log;
3049
		}
3050
3051
		if ( $num ) {
3052
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3053
		}
3054
3055
		return $custom_log_output;
3056
	}
3057
3058
	/**
3059
	 * Log modification of important settings.
3060
	 */
3061
	public static function log_settings_change( $option, $old_value, $value ) {
3062
		switch( $option ) {
3063
			case 'jetpack_sync_non_public_post_stati':
3064
				self::log( $option, $value );
3065
				break;
3066
		}
3067
	}
3068
3069
	/**
3070
	 * Return stat data for WPCOM sync
3071
	 */
3072
	public static function get_stat_data( $encode = true, $extended = true ) {
3073
		$data = Jetpack_Heartbeat::generate_stats_array();
3074
3075
		if ( $extended ) {
3076
			$additional_data = self::get_additional_stat_data();
3077
			$data = array_merge( $data, $additional_data );
3078
		}
3079
3080
		if ( $encode ) {
3081
			return json_encode( $data );
3082
		}
3083
3084
		return $data;
3085
	}
3086
3087
	/**
3088
	 * Get additional stat data to sync to WPCOM
3089
	 */
3090
	public static function get_additional_stat_data( $prefix = '' ) {
3091
		$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...
3092
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3093
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3094
		$return["{$prefix}site-count"]     = 0;
3095
3096
		if ( function_exists( 'get_blog_count' ) ) {
3097
			$return["{$prefix}site-count"] = get_blog_count();
3098
		}
3099
		return $return;
3100
	}
3101
3102
	private static function get_site_user_count() {
3103
		global $wpdb;
3104
3105
		if ( function_exists( 'wp_is_large_network' ) ) {
3106
			if ( wp_is_large_network( 'users' ) ) {
3107
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3108
			}
3109
		}
3110 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3111
			// It wasn't there, so regenerate the data and save the transient
3112
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3113
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3114
		}
3115
		return $user_count;
3116
	}
3117
3118
	/* Admin Pages */
3119
3120
	function admin_init() {
3121
		// If the plugin is not connected, display a connect message.
3122
		if (
3123
			// the plugin was auto-activated and needs its candy
3124
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3125
		||
3126
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3127
			! Jetpack_Options::get_option( 'activated' )
3128
		) {
3129
			Jetpack::plugin_initialize();
3130
		}
3131
3132
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3133
			Jetpack_Connection_Banner::init();
3134
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3135
			// Upgrade: 1.1 -> 1.1.1
3136
			// Check and see if host can verify the Jetpack servers' SSL certificate
3137
			$args = array();
3138
			Jetpack_Client::_wp_remote_request(
3139
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3140
				$args,
3141
				true
3142
			);
3143
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3144
			// Show the notice on the Dashboard only for now
3145
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3146
		}
3147
3148
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3149
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3150
		}
3151
3152
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3153
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3154
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3155
3156
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3157
			// Artificially throw errors in certain whitelisted cases during plugin activation
3158
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3159
		}
3160
3161
		// Jetpack Manage Activation Screen from .com
3162
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3163
3164
		// Add custom column in wp-admin/users.php to show whether user is linked.
3165
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3166
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3167
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3168
	}
3169
3170
	function admin_body_class( $admin_body_class = '' ) {
3171
		$classes = explode( ' ', trim( $admin_body_class ) );
3172
3173
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3174
3175
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3176
		return " $admin_body_class ";
3177
	}
3178
3179
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3180
		return $admin_body_class . ' jetpack-pagestyles ';
3181
	}
3182
3183
	/**
3184
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3185
	 *
3186
	 * @return null
3187
	 */
3188
	function prepare_manage_jetpack_notice() {
3189
3190
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3191
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3192
	}
3193
3194
	function manage_activate_screen() {
3195
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3196
	}
3197
	/**
3198
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3199
	 * This function artificially throws errors for such cases (whitelisted).
3200
	 *
3201
	 * @param string $plugin The activated plugin.
3202
	 */
3203
	function throw_error_on_activate_plugin( $plugin ) {
3204
		$active_modules = Jetpack::get_active_modules();
3205
3206
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3207
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3208
			$throw = false;
3209
3210
			// Try and make sure it really was the stats plugin
3211
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3212
				if ( 'stats.php' == basename( $plugin ) ) {
3213
					$throw = true;
3214
				}
3215
			} else {
3216
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3217
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3218
					$throw = true;
3219
				}
3220
			}
3221
3222
			if ( $throw ) {
3223
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3224
			}
3225
		}
3226
	}
3227
3228
	function intercept_plugin_error_scrape_init() {
3229
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3230
	}
3231
3232
	function intercept_plugin_error_scrape( $action, $result ) {
3233
		if ( ! $result ) {
3234
			return;
3235
		}
3236
3237
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3238
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3239
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3240
			}
3241
		}
3242
	}
3243
3244
	function add_remote_request_handlers() {
3245
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3246
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3247
	}
3248
3249
	function remote_request_handlers() {
3250
		$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...
3251
3252
		switch ( current_filter() ) {
3253
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3254
			$response = $this->upload_handler();
3255
			break;
3256
3257
		case 'wp_ajax_nopriv_jetpack_update_file' :
3258
			$response = $this->upload_handler( true );
3259
			break;
3260
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
3261
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3262
			break;
3263
		}
3264
3265
		if ( ! $response ) {
3266
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3267
		}
3268
3269
		if ( is_wp_error( $response ) ) {
3270
			$status_code       = $response->get_error_data();
3271
			$error             = $response->get_error_code();
3272
			$error_description = $response->get_error_message();
3273
3274
			if ( ! is_int( $status_code ) ) {
3275
				$status_code = 400;
3276
			}
3277
3278
			status_header( $status_code );
3279
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
0 ignored issues
show
Coding Style Compatibility introduced by
The method remote_request_handlers() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3280
		}
3281
3282
		status_header( 200 );
3283
		if ( true === $response ) {
3284
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method remote_request_handlers() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3285
		}
3286
3287
		die( json_encode( (object) $response ) );
0 ignored issues
show
Coding Style Compatibility introduced by
The method remote_request_handlers() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3288
	}
3289
3290
	/**
3291
	 * Uploads a file gotten from the global $_FILES.
3292
	 * If `$update_media_item` is true and `post_id` is defined
3293
	 * the attachment file of the media item (gotten through of the post_id)
3294
	 * will be updated instead of add a new one.
3295
	 *
3296
	 * @param  boolean $update_media_item - update media attachment
3297
	 * @return array - An array describing the uploadind files process
3298
	 */
3299
	function upload_handler( $update_media_item = false ) {
3300
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3301
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3302
		}
3303
3304
		$user = wp_authenticate( '', '' );
3305
		if ( ! $user || is_wp_error( $user ) ) {
3306
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3307
		}
3308
3309
		wp_set_current_user( $user->ID );
3310
3311
		if ( ! current_user_can( 'upload_files' ) ) {
3312
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3313
		}
3314
3315
		if ( empty( $_FILES ) ) {
3316
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3317
		}
3318
3319
		foreach ( array_keys( $_FILES ) as $files_key ) {
3320
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3321
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3322
			}
3323
		}
3324
3325
		$media_keys = array_keys( $_FILES['media'] );
3326
3327
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3328
		if ( ! $token || is_wp_error( $token ) ) {
3329
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3330
		}
3331
3332
		$uploaded_files = array();
3333
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3334
		unset( $GLOBALS['post'] );
3335
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3336
			$file = array();
3337
			foreach ( $media_keys as $media_key ) {
3338
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3339
			}
3340
3341
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3342
3343
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3344
			if ( $hmac_provided !== $hmac_file ) {
3345
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3346
				continue;
3347
			}
3348
3349
			$_FILES['.jetpack.upload.'] = $file;
3350
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3351
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3352
				$post_id = 0;
3353
			}
3354
3355
			if ( $update_media_item ) {
3356
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3357
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3358
				}
3359
3360
				$media_array = $_FILES['media'];
3361
3362
				$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...
3363
				$file_array['type'] = $media_array['type'][0];
3364
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3365
				$file_array['error'] = $media_array['error'][0];
3366
				$file_array['size'] = $media_array['size'][0];
3367
3368
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3369
3370
				if ( is_wp_error( $edited_media_item ) ) {
3371
					return $edited_media_item;
3372
				}
3373
3374
				$response = (object) array(
3375
					'id'   => (string) $post_id,
3376
					'file' => (string) $edited_media_item->post_title,
3377
					'url'  => (string) wp_get_attachment_url( $post_id ),
3378
					'type' => (string) $edited_media_item->post_mime_type,
3379
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3380
				);
3381
3382
				return (array) array( $response );
3383
			}
3384
3385
			$attachment_id = media_handle_upload(
3386
				'.jetpack.upload.',
3387
				$post_id,
3388
				array(),
3389
				array(
3390
					'action' => 'jetpack_upload_file',
3391
				)
3392
			);
3393
3394
			if ( ! $attachment_id ) {
3395
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3396
			} elseif ( is_wp_error( $attachment_id ) ) {
3397
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3398
			} else {
3399
				$attachment = get_post( $attachment_id );
3400
				$uploaded_files[$index] = (object) array(
3401
					'id'   => (string) $attachment_id,
3402
					'file' => $attachment->post_title,
3403
					'url'  => wp_get_attachment_url( $attachment_id ),
3404
					'type' => $attachment->post_mime_type,
3405
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3406
				);
3407
				// Zip files uploads are not supported unless they are done for installation purposed
3408
				// lets delete them in case something goes wrong in this whole process
3409
				if ( 'application/zip' === $attachment->post_mime_type ) {
3410
					// Schedule a cleanup for 2 hours from now in case of failed install.
3411
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3412
				}
3413
			}
3414
		}
3415
		if ( ! is_null( $global_post ) ) {
3416
			$GLOBALS['post'] = $global_post;
3417
		}
3418
3419
		return $uploaded_files;
3420
	}
3421
3422
	/**
3423
	 * Add help to the Jetpack page
3424
	 *
3425
	 * @since Jetpack (1.2.3)
3426
	 * @return false if not the Jetpack page
3427
	 */
3428
	function admin_help() {
3429
		$current_screen = get_current_screen();
3430
3431
		// Overview
3432
		$current_screen->add_help_tab(
3433
			array(
3434
				'id'		=> 'home',
3435
				'title'		=> __( 'Home', 'jetpack' ),
3436
				'content'	=>
3437
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3438
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3439
					'<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>',
3440
			)
3441
		);
3442
3443
		// Screen Content
3444
		if ( current_user_can( 'manage_options' ) ) {
3445
			$current_screen->add_help_tab(
3446
				array(
3447
					'id'		=> 'settings',
3448
					'title'		=> __( 'Settings', 'jetpack' ),
3449
					'content'	=>
3450
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3451
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3452
						'<ol>' .
3453
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3454
							'<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>' .
3455
						'</ol>' .
3456
						'<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>'
3457
				)
3458
			);
3459
		}
3460
3461
		// Help Sidebar
3462
		$current_screen->set_help_sidebar(
3463
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3464
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3465
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3466
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3467
		);
3468
	}
3469
3470
	function admin_menu_css() {
3471
		wp_enqueue_style( 'jetpack-icons' );
3472
	}
3473
3474
	function admin_menu_order() {
3475
		return true;
3476
	}
3477
3478 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3479
		$jp_menu_order = array();
3480
3481
		foreach ( $menu_order as $index => $item ) {
3482
			if ( $item != 'jetpack' ) {
3483
				$jp_menu_order[] = $item;
3484
			}
3485
3486
			if ( $index == 0 ) {
3487
				$jp_menu_order[] = 'jetpack';
3488
			}
3489
		}
3490
3491
		return $jp_menu_order;
3492
	}
3493
3494
	function admin_head() {
3495 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3496
			/** This action is documented in class.jetpack-admin-page.php */
3497
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3498
	}
3499
3500
	function admin_banner_styles() {
3501
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3502
3503 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3504
			wp_register_style(
3505
				'jetpack-dops-style',
3506
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3507
				array(),
3508
				JETPACK__VERSION
3509
			);
3510
		}
3511
3512
		wp_enqueue_style(
3513
			'jetpack',
3514
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3515
			array( 'jetpack-dops-style' ),
3516
			 JETPACK__VERSION . '-20121016'
3517
		);
3518
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3519
		wp_style_add_data( 'jetpack', 'suffix', $min );
3520
	}
3521
3522
	function plugin_action_links( $actions ) {
3523
3524
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3525
3526
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3527
			return array_merge(
3528
				$jetpack_home,
3529
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3530
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3531
				$actions
3532
				);
3533
			}
3534
3535
		return array_merge( $jetpack_home, $actions );
3536
	}
3537
3538
	/**
3539
	 * This is the first banner
3540
	 * It should be visible only to user that can update the option
3541
	 * Are not connected
3542
	 *
3543
	 * @return null
3544
	 */
3545
	function admin_jetpack_manage_notice() {
3546
		$screen = get_current_screen();
3547
3548
		// Don't show the connect notice on the jetpack settings page.
3549
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3550
			return;
3551
		}
3552
3553
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3554
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3555
		/**
3556
		 * I think it would be great to have different wordsing depending on where you are
3557
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3558
		 * etc..
3559
		 */
3560
3561
		?>
3562
		<div id="message" class="updated jp-banner">
3563
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3564
				<div class="jp-banner__description-container">
3565
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3566
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3567
					<p class="jp-banner__button-container">
3568
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3569
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3570
					</p>
3571
				</div>
3572
		</div>
3573
		<?php
3574
	}
3575
3576
	/**
3577
	 * Returns the url that the user clicks to remove the notice for the big banner
3578
	 * @return (string)
3579
	 */
3580
	function opt_out_jetpack_manage_url() {
3581
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3582
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3583
	}
3584
	/**
3585
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3586
	 * @return (string)
3587
	 */
3588
	function opt_in_jetpack_manage_url() {
3589
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3590
	}
3591
3592
	function opt_in_jetpack_manage_notice() {
3593
		?>
3594
		<div class="wrap">
3595
			<div id="message" class="jetpack-message is-opt-in">
3596
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'https://jetpack.com/support/site-management' ); ?>
3597
			</div>
3598
		</div>
3599
		<?php
3600
3601
	}
3602
	/**
3603
	 * Determines whether to show the notice of not true = display notice
3604
	 * @return (bool)
3605
	 */
3606
	function can_display_jetpack_manage_notice() {
3607
		// never display the notice to users that can't do anything about it anyways
3608
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3609
			return false;
3610
3611
		// don't display if we are in development more
3612
		if( Jetpack::is_development_mode() ) {
3613
			return false;
3614
		}
3615
		// don't display if the site is private
3616
		if(  ! Jetpack_Options::get_option( 'public' ) )
3617
			return false;
3618
3619
		/**
3620
		 * Should the Jetpack Remote Site Management notice be displayed.
3621
		 *
3622
		 * @since 3.3.0
3623
		 *
3624
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3625
		 */
3626
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3627
	}
3628
3629
	/*
3630
	 * Registration flow:
3631
	 * 1 - ::admin_page_load() action=register
3632
	 * 2 - ::try_registration()
3633
	 * 3 - ::register()
3634
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3635
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3636
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3637
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3638
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3639
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3640
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3641
	 *       jetpack_id, jetpack_secret, jetpack_public
3642
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3643
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3644
	 * 5 - user logs in with WP.com account
3645
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3646
	 *		- Jetpack_Client_Server::authorize()
3647
	 *		- Jetpack_Client_Server::get_token()
3648
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3649
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3650
	 *			- which responds with access_token, token_type, scope
3651
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3652
	 *		- Jetpack::activate_default_modules()
3653
	 *     		- Deactivates deprecated plugins
3654
	 *     		- Activates all default modules
3655
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3656
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3657
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3658
	 *     Done!
3659
	 */
3660
3661
	/**
3662
	 * Handles the page load events for the Jetpack admin page
3663
	 */
3664
	function admin_page_load() {
3665
		$error = false;
3666
3667
		// Make sure we have the right body class to hook stylings for subpages off of.
3668
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3669
3670
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3671
			// Should only be used in intermediate redirects to preserve state across redirects
3672
			Jetpack::restate();
3673
		}
3674
3675
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3676
			// User clicked in the iframe to link their accounts
3677
			if ( ! Jetpack::is_user_connected() ) {
3678
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3679
				if ( isset( $_GET['notes_iframe'] ) )
3680
					$connect_url .= '&notes_iframe';
3681
				wp_redirect( $connect_url );
3682
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3683
			} else {
3684
				if ( ! isset( $_GET['calypso_env'] ) ) {
3685
					Jetpack::state( 'message', 'already_authorized' );
3686
					wp_safe_redirect( Jetpack::admin_url() );
3687
				} else {
3688
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3689
					$connect_url .= '&already_authorized=true';
3690
					wp_redirect( $connect_url );
3691
				}
3692
			}
3693
		}
3694
3695
3696
		if ( isset( $_GET['action'] ) ) {
3697
			switch ( $_GET['action'] ) {
3698
			case 'authorize':
3699
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3700
					Jetpack::state( 'message', 'already_authorized' );
3701
					wp_safe_redirect( Jetpack::admin_url() );
3702
					exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3703
				}
3704
				Jetpack::log( 'authorize' );
3705
				$client_server = new Jetpack_Client_Server;
3706
				$client_server->client_authorize();
3707
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3708
			case 'register' :
3709
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3710
					$error = 'cheatin';
3711
					break;
3712
				}
3713
				check_admin_referer( 'jetpack-register' );
3714
				Jetpack::log( 'register' );
3715
				Jetpack::maybe_set_version_option();
3716
				$registered = Jetpack::try_registration();
3717
				if ( is_wp_error( $registered ) ) {
3718
					$error = $registered->get_error_code();
3719
					Jetpack::state( 'error', $error );
3720
					Jetpack::state( 'error', $registered->get_error_message() );
3721
					break;
3722
				}
3723
3724
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3725
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3726
3727
				wp_redirect( $this->build_connect_url( true, $redirect, $from ) );
3728
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3729
			case 'activate' :
3730
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3731
					$error = 'cheatin';
3732
					break;
3733
				}
3734
3735
				$module = stripslashes( $_GET['module'] );
3736
				check_admin_referer( "jetpack_activate-$module" );
3737
				Jetpack::log( 'activate', $module );
3738
				Jetpack::activate_module( $module );
3739
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3740
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3741
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3742
			case 'activate_default_modules' :
3743
				check_admin_referer( 'activate_default_modules' );
3744
				Jetpack::log( 'activate_default_modules' );
3745
				Jetpack::restate();
3746
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3747
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3748
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3749
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3750
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3751
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3752
			case 'disconnect' :
3753
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3754
					$error = 'cheatin';
3755
					break;
3756
				}
3757
3758
				check_admin_referer( 'jetpack-disconnect' );
3759
				Jetpack::log( 'disconnect' );
3760
				Jetpack::disconnect();
3761
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3762
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3763
			case 'reconnect' :
3764
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3765
					$error = 'cheatin';
3766
					break;
3767
				}
3768
3769
				check_admin_referer( 'jetpack-reconnect' );
3770
				Jetpack::log( 'reconnect' );
3771
				$this->disconnect();
3772
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3773
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3774 View Code Duplication
			case 'deactivate' :
3775
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3776
					$error = 'cheatin';
3777
					break;
3778
				}
3779
3780
				$modules = stripslashes( $_GET['module'] );
3781
				check_admin_referer( "jetpack_deactivate-$modules" );
3782
				foreach ( explode( ',', $modules ) as $module ) {
3783
					Jetpack::log( 'deactivate', $module );
3784
					Jetpack::deactivate_module( $module );
3785
					Jetpack::state( 'message', 'module_deactivated' );
3786
				}
3787
				Jetpack::state( 'module', $modules );
3788
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3789
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3790
			case 'unlink' :
3791
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3792
				check_admin_referer( 'jetpack-unlink' );
3793
				Jetpack::log( 'unlink' );
3794
				$this->unlink_user();
3795
				Jetpack::state( 'message', 'unlinked' );
3796
				if ( 'sub-unlink' == $redirect ) {
3797
					wp_safe_redirect( admin_url() );
3798
				} else {
3799
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3800
				}
3801
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
3802
			default:
3803
				/**
3804
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3805
				 *
3806
				 * @since 2.6.0
3807
				 *
3808
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3809
				 */
3810
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3811
			}
3812
		}
3813
3814
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3815
			self::activate_new_modules( true );
3816
		}
3817
3818
		$message_code = Jetpack::state( 'message' );
3819
		if ( Jetpack::state( 'optin-manage' ) ) {
3820
			$activated_manage = $message_code;
3821
			$message_code = 'jetpack-manage';
3822
		}
3823
3824
		switch ( $message_code ) {
3825
		case 'jetpack-manage':
3826
			$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>';
3827
			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...
3828
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3829
			}
3830
			break;
3831
3832
		}
3833
3834
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3835
3836
		if ( ! empty( $deactivated_plugins ) ) {
3837
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3838
			$deactivated_titles  = array();
3839
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3840
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3841
					continue;
3842
				}
3843
3844
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3845
			}
3846
3847
			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...
3848
				if ( $this->message ) {
3849
					$this->message .= "<br /><br />\n";
3850
				}
3851
3852
				$this->message .= wp_sprintf(
3853
					_n(
3854
						'Jetpack contains the most recent version of the old %l plugin.',
3855
						'Jetpack contains the most recent versions of the old %l plugins.',
3856
						count( $deactivated_titles ),
3857
						'jetpack'
3858
					),
3859
					$deactivated_titles
3860
				);
3861
3862
				$this->message .= "<br />\n";
3863
3864
				$this->message .= _n(
3865
					'The old version has been deactivated and can be removed from your site.',
3866
					'The old versions have been deactivated and can be removed from your site.',
3867
					count( $deactivated_titles ),
3868
					'jetpack'
3869
				);
3870
			}
3871
		}
3872
3873
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3874
3875
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3876
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3877
		}
3878
3879 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3880
			/**
3881
			 * Fires when a module configuration page is loaded.
3882
			 * The dynamic part of the hook is the configure parameter from the URL.
3883
			 *
3884
			 * @since 1.1.0
3885
			 */
3886
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3887
		}
3888
3889
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3890
	}
3891
3892
	function admin_notices() {
3893
3894
		if ( $this->error ) {
3895
?>
3896
<div id="message" class="jetpack-message jetpack-err">
3897
	<div class="squeezer">
3898
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3899
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3900
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3901
<?php	endif; ?>
3902
	</div>
3903
</div>
3904
<?php
3905
		}
3906
3907
		if ( $this->message ) {
3908
?>
3909
<div id="message" class="jetpack-message">
3910
	<div class="squeezer">
3911
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3912
	</div>
3913
</div>
3914
<?php
3915
		}
3916
3917
		if ( $this->privacy_checks ) :
3918
			$module_names = $module_slugs = array();
3919
3920
			$privacy_checks = explode( ',', $this->privacy_checks );
3921
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3922
			foreach ( $privacy_checks as $module_slug ) {
3923
				$module = Jetpack::get_module( $module_slug );
3924
				if ( ! $module ) {
3925
					continue;
3926
				}
3927
3928
				$module_slugs[] = $module_slug;
3929
				$module_names[] = "<strong>{$module['name']}</strong>";
3930
			}
3931
3932
			$module_slugs = join( ',', $module_slugs );
3933
?>
3934
<div id="message" class="jetpack-message jetpack-err">
3935
	<div class="squeezer">
3936
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3937
		<p><?php
3938
			echo wp_kses(
3939
				wptexturize(
3940
					wp_sprintf(
3941
						_nx(
3942
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3943
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3944
							count( $privacy_checks ),
3945
							'%l = list of Jetpack module/feature names',
3946
							'jetpack'
3947
						),
3948
						$module_names
3949
					)
3950
				),
3951
				array( 'strong' => true )
3952
			);
3953
3954
			echo "\n<br />\n";
3955
3956
			echo wp_kses(
3957
				sprintf(
3958
					_nx(
3959
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3960
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3961
						count( $privacy_checks ),
3962
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3963
						'jetpack'
3964
					),
3965
					wp_nonce_url(
3966
						Jetpack::admin_url(
3967
							array(
3968
								'page'   => 'jetpack',
3969
								'action' => 'deactivate',
3970
								'module' => urlencode( $module_slugs ),
3971
							)
3972
						),
3973
						"jetpack_deactivate-$module_slugs"
3974
					),
3975
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3976
				),
3977
				array( 'a' => array( 'href' => true, 'title' => true ) )
3978
			);
3979
		?></p>
3980
	</div>
3981
</div>
3982
<?php endif;
3983
	// only display the notice if the other stuff is not there
3984
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3985
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3986
			$this->opt_in_jetpack_manage_notice();
3987
		}
3988
	}
3989
3990
	/**
3991
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3992
	 */
3993
	function stat( $group, $detail ) {
3994
		if ( ! isset( $this->stats[ $group ] ) )
3995
			$this->stats[ $group ] = array();
3996
		$this->stats[ $group ][] = $detail;
3997
	}
3998
3999
	/**
4000
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4001
	 */
4002
	function do_stats( $method = '' ) {
4003
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4004
			foreach ( $this->stats as $group => $stats ) {
4005
				if ( is_array( $stats ) && count( $stats ) ) {
4006
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4007
					if ( 'server_side' === $method ) {
4008
						self::do_server_side_stat( $args );
4009
					} else {
4010
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4011
					}
4012
				}
4013
				unset( $this->stats[ $group ] );
4014
			}
4015
		}
4016
	}
4017
4018
	/**
4019
	 * Runs stats code for a one-off, server-side.
4020
	 *
4021
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4022
	 *
4023
	 * @return bool If it worked.
4024
	 */
4025
	static function do_server_side_stat( $args ) {
4026
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4027
		if ( is_wp_error( $response ) )
4028
			return false;
4029
4030
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4031
			return false;
4032
4033
		return true;
4034
	}
4035
4036
	/**
4037
	 * Builds the stats url.
4038
	 *
4039
	 * @param $args array|string The arguments to append to the URL.
4040
	 *
4041
	 * @return string The URL to be pinged.
4042
	 */
4043
	static function build_stats_url( $args ) {
4044
		$defaults = array(
4045
			'v'    => 'wpcom2',
4046
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4047
		);
4048
		$args     = wp_parse_args( $args, $defaults );
4049
		/**
4050
		 * Filter the URL used as the Stats tracking pixel.
4051
		 *
4052
		 * @since 2.3.2
4053
		 *
4054
		 * @param string $url Base URL used as the Stats tracking pixel.
4055
		 */
4056
		$base_url = apply_filters(
4057
			'jetpack_stats_base_url',
4058
			'https://pixel.wp.com/g.gif'
4059
		);
4060
		$url      = add_query_arg( $args, $base_url );
4061
		return $url;
4062
	}
4063
4064
	static function translate_current_user_to_role() {
4065
		foreach ( self::$capability_translations as $role => $cap ) {
4066
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4067
				return $role;
4068
			}
4069
		}
4070
4071
		return false;
4072
	}
4073
4074
	static function translate_role_to_cap( $role ) {
4075
		if ( ! isset( self::$capability_translations[$role] ) ) {
4076
			return false;
4077
		}
4078
4079
		return self::$capability_translations[$role];
4080
	}
4081
4082
	static function sign_role( $role ) {
4083
		if ( ! $user_id = (int) get_current_user_id() ) {
4084
			return false;
4085
		}
4086
4087
		$token = Jetpack_Data::get_access_token();
4088
		if ( ! $token || is_wp_error( $token ) ) {
4089
			return false;
4090
		}
4091
4092
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4093
	}
4094
4095
4096
	/**
4097
	 * Builds a URL to the Jetpack connection auth page
4098
	 *
4099
	 * @since 3.9.5
4100
	 *
4101
	 * @param bool $raw If true, URL will not be escaped.
4102
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4103
	 *                              If string, will be a custom redirect.
4104
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4105
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4106
	 *
4107
	 * @return string Connect URL
4108
	 */
4109
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4110
		$site_id = Jetpack_Options::get_option( 'id' );
4111
		$token = Jetpack_Options::get_option( 'blog_token' );
4112
4113
		if ( $register || ! $token || ! $site_id ) {
4114
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4115
4116
			if ( ! empty( $redirect ) ) {
4117
				$url = add_query_arg(
4118
					'redirect',
4119
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4120
					$url
4121
				);
4122
			}
4123
4124
			if( is_network_admin() ) {
4125
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4126
			}
4127
		} else {
4128
4129
			// Checking existing token
4130
			$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4131
				sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4132
				'1.1'
4133
			);
4134
4135
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4136
				// Generating a register URL instead to refresh the existing token
4137
				return $this->build_connect_url( $raw, $redirect, $from, true );
4138
			}
4139
4140
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4141
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4142
			}
4143
4144
			$role = self::translate_current_user_to_role();
4145
			$signed_role = self::sign_role( $role );
4146
4147
			$user = wp_get_current_user();
4148
4149
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4150
			$redirect = $redirect
4151
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4152
				: $jetpack_admin_page;
4153
4154
			if( isset( $_REQUEST['is_multisite'] ) ) {
4155
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4156
			}
4157
4158
			$secrets = Jetpack::generate_secrets( 'authorize' );
4159
4160
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4161
				? get_site_icon_url()
4162
				: false;
4163
4164
			/**
4165
			 * Filter the type of authorization.
4166
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4167
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4168
			 *
4169
			 * @since 4.3.3
4170
			 *
4171
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4172
			 */
4173
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4174
4175
			$args = urlencode_deep(
4176
				array(
4177
					'response_type' => 'code',
4178
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4179
					'redirect_uri'  => add_query_arg(
4180
						array(
4181
							'action'   => 'authorize',
4182
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4183
							'redirect' => urlencode( $redirect ),
4184
						),
4185
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4186
					),
4187
					'state'         => $user->ID,
4188
					'scope'         => $signed_role,
4189
					'user_email'    => $user->user_email,
4190
					'user_login'    => $user->user_login,
4191
					'is_active'     => Jetpack::is_active(),
4192
					'jp_version'    => JETPACK__VERSION,
4193
					'auth_type'     => $auth_type,
4194
					'secret'        => $secrets['secret_1'],
4195
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4196
					'blogname'      => get_option( 'blogname' ),
4197
					'site_url'      => site_url(),
4198
					'home_url'      => home_url(),
4199
					'site_icon'     => $site_icon,
4200
				)
4201
			);
4202
4203
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4204
		}
4205
4206
		if ( $from ) {
4207
			$url = add_query_arg( 'from', $from, $url );
4208
		}
4209
4210
4211
		if ( isset( $_GET['calypso_env'] ) ) {
4212
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4213
		}
4214
4215
		return $raw ? $url : esc_url( $url );
4216
	}
4217
4218
	function build_reconnect_url( $raw = false ) {
4219
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4220
		return $raw ? $url : esc_url( $url );
4221
	}
4222
4223
	public static function admin_url( $args = null ) {
4224
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4225
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4226
		return $url;
4227
	}
4228
4229
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4230
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4231
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4232
	}
4233
4234
	function dismiss_jetpack_notice() {
4235
4236
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4237
			return;
4238
		}
4239
4240
		switch( $_GET['jetpack-notice'] ) {
4241
			case 'dismiss':
4242
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4243
4244
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4245
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4246
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4247
				}
4248
				break;
4249 View Code Duplication
			case 'jetpack-manage-opt-out':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
4250
4251
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4252
					// Don't show the banner again
4253
4254
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4255
					// redirect back to the page that had the notice
4256
					if ( wp_get_referer() ) {
4257
						wp_safe_redirect( wp_get_referer() );
4258
					} else {
4259
						// Take me to Jetpack
4260
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4261
					}
4262
				}
4263
				break;
4264 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
4265
4266
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4267
					// Don't show the banner again
4268
4269
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4270
					// redirect back to the page that had the notice
4271
					if ( wp_get_referer() ) {
4272
						wp_safe_redirect( wp_get_referer() );
4273
					} else {
4274
						// Take me to Jetpack
4275
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4276
					}
4277
				}
4278
				break;
4279
			case 'jetpack-manage-opt-in':
4280
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4281
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4282
4283
					$redirection_url = Jetpack::admin_url();
4284
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4285
4286
					// Don't redirect form the Jetpack Setting Page
4287
					$referer_parsed = parse_url ( wp_get_referer() );
4288
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4289
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4290
						// Take the user to Jetpack home except when on the setting page
4291
						$redirection_url = wp_get_referer();
4292
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4293
					}
4294
					// Also update the JSON API FULL MANAGEMENT Option
4295
					Jetpack::activate_module( 'manage', false, false );
4296
4297
					// Special Message when option in.
4298
					Jetpack::state( 'optin-manage', 'true' );
4299
					// Activate the Module if not activated already
4300
4301
					// Redirect properly
4302
					wp_safe_redirect( $redirection_url );
4303
4304
				}
4305
				break;
4306
		}
4307
	}
4308
4309
	public static function admin_screen_configure_module( $module_id ) {
4310
4311
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4312
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4313
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4314
				/**
4315
				 * Fires to diplay a custom module activation screen.
4316
				 *
4317
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4318
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4319
				 *
4320
				 * @module manage
4321
				 *
4322
				 * @since 3.8.0
4323
				 *
4324
				 * @param int $module_id Module ID.
4325
				 */
4326
				do_action( 'display_activate_module_setting_' . $module_id );
4327
			} else {
4328
				self::display_activate_module_link( $module_id );
4329
			}
4330
4331
			return false;
4332
		} ?>
4333
4334
		<div id="jp-settings-screen" style="position: relative">
4335
			<h3>
4336
			<?php
4337
				$module = Jetpack::get_module( $module_id );
4338
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4339
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4340
			?>
4341
			</h3>
4342
			<?php
4343
				/**
4344
				 * Fires within the displayed message when a feature configuation is updated.
4345
				 *
4346
				 * @since 3.4.0
4347
				 *
4348
				 * @param int $module_id Module ID.
4349
				 */
4350
				do_action( 'jetpack_notices_update_settings', $module_id );
4351
				/**
4352
				 * Fires when a feature configuation screen is loaded.
4353
				 * The dynamic part of the hook, $module_id, is the module ID.
4354
				 *
4355
				 * @since 1.1.0
4356
				 */
4357
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4358
			?>
4359
		</div><?php
4360
	}
4361
4362
	/**
4363
	 * Display link to activate the module to see the settings screen.
4364
	 * @param  string $module_id
4365
	 * @return null
4366
	 */
4367
	public static function display_activate_module_link( $module_id ) {
4368
4369
		$info =  Jetpack::get_module( $module_id );
4370
		$extra = '';
4371
		$activate_url = wp_nonce_url(
4372
				Jetpack::admin_url(
4373
					array(
4374
						'page'   => 'jetpack',
4375
						'action' => 'activate',
4376
						'module' => $module_id,
4377
					)
4378
				),
4379
				"jetpack_activate-$module_id"
4380
			);
4381
4382
		?>
4383
4384
		<div class="wrap configure-module">
4385
			<div id="jp-settings-screen">
4386
				<?php
4387
				if ( $module_id == 'json-api' ) {
4388
4389
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4390
4391
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4392
4393
					$info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'https://jetpack.com/support/site-management' );
4394
4395
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4396
				} ?>
4397
4398
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4399
				<div class="narrow">
4400
					<p><?php echo  $info['description']; ?></p>
4401
					<?php if( $extra ) { ?>
4402
					<p><?php echo esc_html( $extra ); ?></p>
4403
					<?php } ?>
4404
					<p>
4405
						<?php
4406
						if( wp_get_referer() ) {
4407
							printf( __( '<a class="button-primary" href="%s">Activate Now</a> or <a href="%s" >return to previous page</a>.', 'jetpack' ) , $activate_url, wp_get_referer() );
4408
						} else {
4409
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4410
						} ?>
4411
					</p>
4412
				</div>
4413
4414
			</div>
4415
		</div>
4416
4417
		<?php
4418
	}
4419
4420
	public static function sort_modules( $a, $b ) {
4421
		if ( $a['sort'] == $b['sort'] )
4422
			return 0;
4423
4424
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4425
	}
4426
4427
	function ajax_recheck_ssl() {
4428
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4429
		$result = Jetpack::permit_ssl( true );
4430
		wp_send_json( array(
4431
			'enabled' => $result,
4432
			'message' => get_transient( 'jetpack_https_test_message' )
4433
		) );
4434
	}
4435
4436
/* Client API */
4437
4438
	/**
4439
	 * Returns the requested Jetpack API URL
4440
	 *
4441
	 * @return string
4442
	 */
4443
	public static function api_url( $relative_url ) {
4444
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4445
	}
4446
4447
	/**
4448
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4449
	 */
4450
	public static function fix_url_for_bad_hosts( $url ) {
4451
		if ( 0 !== strpos( $url, 'https://' ) ) {
4452
			return $url;
4453
		}
4454
4455
		switch ( JETPACK_CLIENT__HTTPS ) {
4456
			case 'ALWAYS' :
4457
				return $url;
4458
			case 'NEVER' :
4459
				return set_url_scheme( $url, 'http' );
4460
			// default : case 'AUTO' :
4461
		}
4462
4463
		// we now return the unmodified SSL URL by default, as a security precaution
4464
		return $url;
4465
	}
4466
4467
	/**
4468
	 * Checks to see if the URL is using SSL to connect with Jetpack
4469
	 *
4470
	 * @since 2.3.3
4471
	 * @return boolean
4472
	 */
4473
	public static function permit_ssl( $force_recheck = false ) {
4474
		// Do some fancy tests to see if ssl is being supported
4475
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4476
			$message = '';
4477
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4478
				$ssl = 0;
4479
			} else {
4480
				switch ( JETPACK_CLIENT__HTTPS ) {
4481
					case 'NEVER':
4482
						$ssl = 0;
4483
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4484
						break;
4485
					case 'ALWAYS':
4486
					case 'AUTO':
4487
					default:
4488
						$ssl = 1;
4489
						break;
4490
				}
4491
4492
				// If it's not 'NEVER', test to see
4493
				if ( $ssl ) {
4494
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4495
						$ssl = 0;
4496
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4497
					} else {
4498
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4499
						if ( is_wp_error( $response ) ) {
4500
							$ssl = 0;
4501
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4502
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4503
							$ssl = 0;
4504
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4505
						}
4506
					}
4507
				}
4508
			}
4509
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4510
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4511
		}
4512
4513
		return (bool) $ssl;
4514
	}
4515
4516
	/*
4517
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4518
	 */
4519
	public function alert_auto_ssl_fail() {
4520
		if ( ! current_user_can( 'manage_options' ) )
4521
			return;
4522
4523
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4524
		?>
4525
4526
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4527
			<div class="jp-banner__content">
4528
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4529
				<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>
4530
				<p>
4531
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4532
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4533
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4534
				</p>
4535
				<p>
4536
					<?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' ),
4537
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4538
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4539
				</p>
4540
			</div>
4541
		</div>
4542
		<style>
4543
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4544
		</style>
4545
		<script type="text/javascript">
4546
			jQuery( document ).ready( function( $ ) {
4547
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4548
					var $this = $( this );
4549
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4550
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4551
					e.preventDefault();
4552
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4553
					$.post( ajaxurl, data )
4554
					  .done( function( response ) {
4555
					  	if ( response.enabled ) {
4556
					  		$( '#jetpack-ssl-warning' ).hide();
4557
					  	} else {
4558
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4559
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4560
					  	}
4561
					  }.bind( $this ) );
4562
				} );
4563
			} );
4564
		</script>
4565
4566
		<?php
4567
	}
4568
4569
	/**
4570
	 * Returns the Jetpack XML-RPC API
4571
	 *
4572
	 * @return string
4573
	 */
4574
	public static function xmlrpc_api_url() {
4575
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4576
		return untrailingslashit( $base ) . '/xmlrpc.php';
4577
	}
4578
4579
	/**
4580
	 * Creates two secret tokens and the end of life timestamp for them.
4581
	 *
4582
	 * Note these tokens are unique per call, NOT static per site for connecting.
4583
	 *
4584
	 * @since 2.6
4585
	 * @return array
4586
	 */
4587
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4588
		if ( ! $user_id ) {
4589
			$user_id = get_current_user_id();
4590
		}
4591
4592
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
4593
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4594
4595
		if (
4596
			isset( $secrets[ $secret_name ] ) &&
4597
			$secrets[ $secret_name ]['exp'] > time()
4598
		) {
4599
			return $secrets[ $secret_name ];
4600
		}
4601
4602
		$secret_value = array(
4603
			'secret_1'  => wp_generate_password( 32, false ),
4604
			'secret_2'  => wp_generate_password( 32, false ),
4605
			'exp'       => time() + $exp,
4606
		);
4607
4608
		$secrets[ $secret_name ] = $secret_value;
4609
4610
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4611
		return $secrets[ $secret_name ];
4612
	}
4613
4614
	public static function get_secrets( $action, $user_id ) {
4615
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4616
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4617
4618
		if ( ! isset( $secrets[ $secret_name ] ) ) {
4619
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4620
		}
4621
4622
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
4623
			self::delete_secrets( $action, $user_id );
4624
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4625
		}
4626
4627
		return $secrets[ $secret_name ];
4628
	}
4629
4630
	public static function delete_secrets( $action, $user_id ) {
4631
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4632
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4633
		if ( isset( $secrets[ $secret_name ] ) ) {
4634
			unset( $secrets[ $secret_name ] );
4635
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4636
		}
4637
	}
4638
4639
	/**
4640
	 * Builds the timeout limit for queries talking with the wpcom servers.
4641
	 *
4642
	 * Based on local php max_execution_time in php.ini
4643
	 *
4644
	 * @since 2.6
4645
	 * @return int
4646
	 **/
4647
	public function get_remote_query_timeout_limit() {
4648
	    $timeout = (int) ini_get( 'max_execution_time' );
4649
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4650
				$timeout = 30;
4651
	    return intval( $timeout / 2 );
4652
	}
4653
4654
4655
	/**
4656
	 * Takes the response from the Jetpack register new site endpoint and
4657
	 * verifies it worked properly.
4658
	 *
4659
	 * @since 2.6
4660
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4661
	 **/
4662
	public function validate_remote_register_response( $response ) {
4663
	  if ( is_wp_error( $response ) ) {
4664
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4665
		}
4666
4667
		$code   = wp_remote_retrieve_response_code( $response );
4668
		$entity = wp_remote_retrieve_body( $response );
4669
		if ( $entity )
4670
			$registration_response = json_decode( $entity );
4671
		else
4672
			$registration_response = false;
4673
4674
		$code_type = intval( $code / 100 );
4675
		if ( 5 == $code_type ) {
4676
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4677
		} elseif ( 408 == $code ) {
4678
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4679
		} elseif ( ! empty( $registration_response->error ) ) {
4680
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4681
				$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' );
4682
			} else {
4683
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4684
			}
4685
4686
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4687
		} elseif ( 200 != $code ) {
4688
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4689
		}
4690
4691
		// Jetpack ID error block
4692
		if ( empty( $registration_response->jetpack_id ) ) {
4693
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4694
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4695
			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 );
4696
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4697
			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 );
4698
		}
4699
4700
	    return $registration_response;
4701
	}
4702
	/**
4703
	 * @return bool|WP_Error
4704
	 */
4705
	public static function register() {
4706
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4707
		$secrets = Jetpack::generate_secrets( 'register' );
4708
4709 View Code Duplication
		if (
4710
			empty( $secrets['secret_1'] ) ||
4711
			empty( $secrets['secret_2'] ) ||
4712
			empty( $secrets['exp'] )
4713
		) {
4714
			return new Jetpack_Error( 'missing_secrets' );
4715
		}
4716
4717
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4718
4719
		$gmt_offset = get_option( 'gmt_offset' );
4720
		if ( ! $gmt_offset ) {
4721
			$gmt_offset = 0;
4722
		}
4723
4724
		$stats_options = get_option( 'stats_options' );
4725
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4726
4727
		$args = array(
4728
			'method'  => 'POST',
4729
			'body'    => array(
4730
				'siteurl'         => site_url(),
4731
				'home'            => home_url(),
4732
				'gmt_offset'      => $gmt_offset,
4733
				'timezone_string' => (string) get_option( 'timezone_string' ),
4734
				'site_name'       => (string) get_option( 'blogname' ),
4735
				'secret_1'        => $secrets['secret_1'],
4736
				'secret_2'        => $secrets['secret_2'],
4737
				'site_lang'       => get_locale(),
4738
				'timeout'         => $timeout,
4739
				'stats_id'        => $stats_id,
4740
				'state'           => get_current_user_id(),
4741
			),
4742
			'headers' => array(
4743
				'Accept' => 'application/json',
4744
			),
4745
			'timeout' => $timeout,
4746
		);
4747
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4748
4749
		// Make sure the response is valid and does not contain any Jetpack errors
4750
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4751
		if ( is_wp_error( $registration_details ) ) {
4752
			return $registration_details;
4753
		} elseif ( ! $registration_details ) {
4754
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
4755
		}
4756
4757 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4758
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
4759
		}
4760
4761
		if ( isset( $registration_details->jetpack_public ) ) {
4762
			$jetpack_public = (int) $registration_details->jetpack_public;
4763
		} else {
4764
			$jetpack_public = false;
4765
		}
4766
4767
		Jetpack_Options::update_options(
4768
			array(
4769
				'id'         => (int)    $registration_details->jetpack_id,
4770
				'blog_token' => (string) $registration_details->jetpack_secret,
4771
				'public'     => $jetpack_public,
4772
			)
4773
		);
4774
4775
		/**
4776
		 * Fires when a site is registered on WordPress.com.
4777
		 *
4778
		 * @since 3.7.0
4779
		 *
4780
		 * @param int $json->jetpack_id Jetpack Blog ID.
4781
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4782
		 * @param int|bool $jetpack_public Is the site public.
4783
		 */
4784
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
4785
4786
		// Initialize Jump Start for the first and only time.
4787
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4788
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4789
4790
			$jetpack = Jetpack::init();
4791
4792
			$jetpack->stat( 'jumpstart', 'unique-views' );
4793
			$jetpack->do_stats( 'server_side' );
4794
		};
4795
4796
		return true;
4797
	}
4798
4799
	/**
4800
	 * If the db version is showing something other that what we've got now, bump it to current.
4801
	 *
4802
	 * @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...
4803
	 */
4804
	public static function maybe_set_version_option() {
4805
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4806
		if ( JETPACK__VERSION != $version ) {
4807
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4808
4809
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4810
				/** This action is documented in class.jetpack.php */
4811
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4812
			}
4813
4814
			return true;
4815
		}
4816
		return false;
4817
	}
4818
4819
/* Client Server API */
4820
4821
	/**
4822
	 * Loads the Jetpack XML-RPC client
4823
	 */
4824
	public static function load_xml_rpc_client() {
4825
		require_once ABSPATH . WPINC . '/class-IXR.php';
4826
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4827
	}
4828
4829
	/**
4830
	 * Resets the saved authentication state in between testing requests.
4831
	 */
4832
	public function reset_saved_auth_state() {
4833
		$this->xmlrpc_verification = null;
4834
		$this->rest_authentication_status = null;
4835
	}
4836
4837
	function verify_xml_rpc_signature() {
4838
		if ( $this->xmlrpc_verification ) {
4839
			return $this->xmlrpc_verification;
4840
		}
4841
4842
		// It's not for us
4843
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4844
			return false;
4845
		}
4846
4847
		@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...
4848
		if (
4849
			empty( $token_key )
4850
		||
4851
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4852
		) {
4853
			return false;
4854
		}
4855
4856
		if ( '0' === $user_id ) {
4857
			$token_type = 'blog';
4858
			$user_id = 0;
4859
		} else {
4860
			$token_type = 'user';
4861
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4862
				return false;
4863
			}
4864
			$user_id = (int) $user_id;
4865
4866
			$user = new WP_User( $user_id );
4867
			if ( ! $user || ! $user->exists() ) {
4868
				return false;
4869
			}
4870
		}
4871
4872
		$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...
4873
		if ( ! $token ) {
4874
			return false;
4875
		}
4876
4877
		$token_check = "$token_key.";
4878
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4879
			return false;
4880
		}
4881
4882
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4883
4884
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4885
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4886
			$post_data   = $_POST;
4887
			$file_hashes = array();
4888
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4889
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4890
					continue;
4891
				}
4892
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4893
				$file_hashes[$post_data_key] = $post_data_value;
4894
			}
4895
4896
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4897
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4898
				$post_data[$post_data_key] = $post_data_value;
4899
			}
4900
4901
			ksort( $post_data );
4902
4903
			$body = http_build_query( stripslashes_deep( $post_data ) );
4904
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4905
			$body = file_get_contents( 'php://input' );
4906
		} else {
4907
			$body = null;
4908
		}
4909
4910
		$signature = $jetpack_signature->sign_current_request(
4911
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4912
		);
4913
4914
		if ( ! $signature ) {
4915
			return false;
4916
		} else if ( is_wp_error( $signature ) ) {
4917
			return $signature;
4918
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4919
			return false;
4920
		}
4921
4922
		$timestamp = (int) $_GET['timestamp'];
4923
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4924
4925
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4926
			return false;
4927
		}
4928
4929
		$this->xmlrpc_verification = array(
4930
			'type'    => $token_type,
4931
			'user_id' => $token->external_user_id,
4932
		);
4933
4934
		return $this->xmlrpc_verification;
4935
	}
4936
4937
	/**
4938
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4939
	 */
4940
	function authenticate_jetpack( $user, $username, $password ) {
4941
		if ( is_a( $user, 'WP_User' ) ) {
4942
			return $user;
4943
		}
4944
4945
		$token_details = $this->verify_xml_rpc_signature();
4946
4947
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4948
			return $user;
4949
		}
4950
4951
		if ( 'user' !== $token_details['type'] ) {
4952
			return $user;
4953
		}
4954
4955
		if ( ! $token_details['user_id'] ) {
4956
			return $user;
4957
		}
4958
4959
		nocache_headers();
4960
4961
		return new WP_User( $token_details['user_id'] );
4962
	}
4963
4964
	// Authenticates requests from Jetpack server to WP REST API endpoints.
4965
	// Uses the existing XMLRPC request signing implementation.
4966
	function wp_rest_authenticate( $user ) {
4967
		if ( ! empty( $user ) ) {
4968
			// Another authentication method is in effect.
4969
			return $user;
4970
		}
4971
4972
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
4973
			// Nothing to do for this authentication method.
4974
			return null;
4975
		}
4976
4977
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
4978
			// Nothing to do for this authentication method.
4979
			return null;
4980
		}
4981
4982
		// Ensure that we always have the request body available.  At this
4983
		// point, the WP REST API code to determine the request body has not
4984
		// run yet.  That code may try to read from 'php://input' later, but
4985
		// this can only be done once per request in PHP versions prior to 5.6.
4986
		// So we will go ahead and perform this read now if needed, and save
4987
		// the request body where both the Jetpack signature verification code
4988
		// and the WP REST API code can see it.
4989
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
4990
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
4991
		}
4992
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4993
4994
		// Only support specific request parameters that have been tested and
4995
		// are known to work with signature verification.  A different method
4996
		// can be passed to the WP REST API via the '?_method=' parameter if
4997
		// needed.
4998
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
4999
			$this->rest_authentication_status = new WP_Error(
5000
				'rest_invalid_request',
5001
				__( 'This request method is not supported.', 'jetpack' ),
5002
				array( 'status' => 400 )
5003
			);
5004
			return null;
5005
		}
5006
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5007
			$this->rest_authentication_status = new WP_Error(
5008
				'rest_invalid_request',
5009
				__( 'This request method does not support body parameters.', 'jetpack' ),
5010
				array( 'status' => 400 )
5011
			);
5012
			return null;
5013
		}
5014
5015
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
5016
			$content_type = $_SERVER['CONTENT_TYPE'];
5017
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
5018
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
5019
		}
5020
5021
		if (
5022
			isset( $content_type ) &&
5023
			$content_type !== 'application/x-www-form-urlencoded' &&
5024
			$content_type !== 'application/json'
5025
		) {
5026
			$this->rest_authentication_status = new WP_Error(
5027
				'rest_invalid_request',
5028
				__( 'This Content-Type is not supported.', 'jetpack' ),
5029
				array( 'status' => 400 )
5030
			);
5031
			return null;
5032
		}
5033
5034
		$verified = $this->verify_xml_rpc_signature();
5035
5036
		if ( is_wp_error( $verified ) ) {
5037
			$this->rest_authentication_status = $verified;
5038
			return null;
5039
		}
5040
5041
		if (
5042
			$verified &&
5043
			isset( $verified['type'] ) &&
5044
			'user' === $verified['type'] &&
5045
			! empty( $verified['user_id'] )
5046
		) {
5047
			// Authentication successful.
5048
			$this->rest_authentication_status = true;
5049
			return $verified['user_id'];
5050
		}
5051
5052
		// Something else went wrong.  Probably a signature error.
5053
		$this->rest_authentication_status = new WP_Error(
5054
			'rest_invalid_signature',
5055
			__( 'The request is not signed correctly.', 'jetpack' ),
5056
			array( 'status' => 400 )
5057
		);
5058
		return null;
5059
	}
5060
5061
	/**
5062
	 * Report authentication status to the WP REST API.
5063
	 *
5064
	 * @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...
5065
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5066
	 */
5067
	public function wp_rest_authentication_errors( $value ) {
5068
		if ( $value !== null ) {
5069
			return $value;
5070
		}
5071
		return $this->rest_authentication_status;
5072
	}
5073
5074
	function add_nonce( $timestamp, $nonce ) {
5075
		global $wpdb;
5076
		static $nonces_used_this_request = array();
5077
5078
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5079
			return $nonces_used_this_request["$timestamp:$nonce"];
5080
		}
5081
5082
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5083
		$timestamp = (int) $timestamp;
5084
		$nonce     = esc_sql( $nonce );
5085
5086
		// Raw query so we can avoid races: add_option will also update
5087
		$show_errors = $wpdb->show_errors( false );
5088
5089
		$old_nonce = $wpdb->get_row(
5090
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5091
		);
5092
5093
		if ( is_null( $old_nonce ) ) {
5094
			$return = $wpdb->query(
5095
				$wpdb->prepare(
5096
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5097
					"jetpack_nonce_{$timestamp}_{$nonce}",
5098
					time(),
5099
					'no'
5100
				)
5101
			);
5102
		} else {
5103
			$return = false;
5104
		}
5105
5106
		$wpdb->show_errors( $show_errors );
5107
5108
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5109
5110
		return $return;
5111
	}
5112
5113
	/**
5114
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5115
	 * Capture it here so we can verify the signature later.
5116
	 */
5117
	function xmlrpc_methods( $methods ) {
5118
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5119
		return $methods;
5120
	}
5121
5122
	function public_xmlrpc_methods( $methods ) {
5123
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5124
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5125
		}
5126
		return $methods;
5127
	}
5128
5129
	function jetpack_getOptions( $args ) {
5130
		global $wp_xmlrpc_server;
5131
5132
		$wp_xmlrpc_server->escape( $args );
5133
5134
		$username	= $args[1];
5135
		$password	= $args[2];
5136
5137
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5138
			return $wp_xmlrpc_server->error;
5139
		}
5140
5141
		$options = array();
5142
		$user_data = $this->get_connected_user_data();
5143
		if ( is_array( $user_data ) ) {
5144
			$options['jetpack_user_id'] = array(
5145
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5146
				'readonly'      => true,
5147
				'value'         => $user_data['ID'],
5148
			);
5149
			$options['jetpack_user_login'] = array(
5150
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5151
				'readonly'      => true,
5152
				'value'         => $user_data['login'],
5153
			);
5154
			$options['jetpack_user_email'] = array(
5155
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5156
				'readonly'      => true,
5157
				'value'         => $user_data['email'],
5158
			);
5159
			$options['jetpack_user_site_count'] = array(
5160
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5161
				'readonly'      => true,
5162
				'value'         => $user_data['site_count'],
5163
			);
5164
		}
5165
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5166
		$args = stripslashes_deep( $args );
5167
		return $wp_xmlrpc_server->wp_getOptions( $args );
5168
	}
5169
5170
	function xmlrpc_options( $options ) {
5171
		$jetpack_client_id = false;
5172
		if ( self::is_active() ) {
5173
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5174
		}
5175
		$options['jetpack_version'] = array(
5176
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5177
				'readonly'      => true,
5178
				'value'         => JETPACK__VERSION,
5179
		);
5180
5181
		$options['jetpack_client_id'] = array(
5182
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5183
				'readonly'      => true,
5184
				'value'         => $jetpack_client_id,
5185
		);
5186
		return $options;
5187
	}
5188
5189
	public static function clean_nonces( $all = false ) {
5190
		global $wpdb;
5191
5192
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5193
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5194
5195
		if ( true !== $all ) {
5196
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5197
			$sql_args[] = time() - 3600;
5198
		}
5199
5200
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5201
5202
		$sql = $wpdb->prepare( $sql, $sql_args );
5203
5204
		for ( $i = 0; $i < 1000; $i++ ) {
5205
			if ( ! $wpdb->query( $sql ) ) {
5206
				break;
5207
			}
5208
		}
5209
	}
5210
5211
	/**
5212
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5213
	 * SET: state( $key, $value );
5214
	 * GET: $value = state( $key );
5215
	 *
5216
	 * @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...
5217
	 * @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...
5218
	 * @param bool $restate private
5219
	 */
5220
	public static function state( $key = null, $value = null, $restate = false ) {
5221
		static $state = array();
5222
		static $path, $domain;
5223
		if ( ! isset( $path ) ) {
5224
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5225
			$admin_url = Jetpack::admin_url();
5226
			$bits      = parse_url( $admin_url );
5227
5228
			if ( is_array( $bits ) ) {
5229
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5230
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5231
			} else {
5232
				$path = $domain = null;
5233
			}
5234
		}
5235
5236
		// Extract state from cookies and delete cookies
5237
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5238
			$yum = $_COOKIE[ 'jetpackState' ];
5239
			unset( $_COOKIE[ 'jetpackState' ] );
5240
			foreach ( $yum as $k => $v ) {
5241
				if ( strlen( $v ) )
5242
					$state[ $k ] = $v;
5243
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5244
			}
5245
		}
5246
5247
		if ( $restate ) {
5248
			foreach ( $state as $k => $v ) {
5249
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5250
			}
5251
			return;
5252
		}
5253
5254
		// Get a state variable
5255
		if ( isset( $key ) && ! isset( $value ) ) {
5256
			if ( array_key_exists( $key, $state ) )
5257
				return $state[ $key ];
5258
			return null;
5259
		}
5260
5261
		// Set a state variable
5262
		if ( isset ( $key ) && isset( $value ) ) {
5263
			if( is_array( $value ) && isset( $value[0] ) ) {
5264
				$value = $value[0];
5265
			}
5266
			$state[ $key ] = $value;
5267
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5268
		}
5269
	}
5270
5271
	public static function restate() {
5272
		Jetpack::state( null, null, true );
5273
	}
5274
5275
	public static function check_privacy( $file ) {
5276
		static $is_site_publicly_accessible = null;
5277
5278
		if ( is_null( $is_site_publicly_accessible ) ) {
5279
			$is_site_publicly_accessible = false;
5280
5281
			Jetpack::load_xml_rpc_client();
5282
			$rpc = new Jetpack_IXR_Client();
5283
5284
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5285
			if ( $success ) {
5286
				$response = $rpc->getResponse();
5287
				if ( $response ) {
5288
					$is_site_publicly_accessible = true;
5289
				}
5290
			}
5291
5292
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5293
		}
5294
5295
		if ( $is_site_publicly_accessible ) {
5296
			return;
5297
		}
5298
5299
		$module_slug = self::get_module_slug( $file );
5300
5301
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5302
		if ( ! $privacy_checks ) {
5303
			$privacy_checks = $module_slug;
5304
		} else {
5305
			$privacy_checks .= ",$module_slug";
5306
		}
5307
5308
		Jetpack::state( 'privacy_checks', $privacy_checks );
5309
	}
5310
5311
	/**
5312
	 * Helper method for multicall XMLRPC.
5313
	 */
5314
	public static function xmlrpc_async_call() {
5315
		global $blog_id;
5316
		static $clients = array();
5317
5318
		$client_blog_id = is_multisite() ? $blog_id : 0;
5319
5320
		if ( ! isset( $clients[$client_blog_id] ) ) {
5321
			Jetpack::load_xml_rpc_client();
5322
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5323
			if ( function_exists( 'ignore_user_abort' ) ) {
5324
				ignore_user_abort( true );
5325
			}
5326
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5327
		}
5328
5329
		$args = func_get_args();
5330
5331
		if ( ! empty( $args[0] ) ) {
5332
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5333
		} elseif ( is_multisite() ) {
5334
			foreach ( $clients as $client_blog_id => $client ) {
5335
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5336
					continue;
5337
				}
5338
5339
				$switch_success = switch_to_blog( $client_blog_id, true );
5340
				if ( ! $switch_success ) {
5341
					continue;
5342
				}
5343
5344
				flush();
5345
				$client->query();
5346
5347
				restore_current_blog();
5348
			}
5349
		} else {
5350
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5351
				flush();
5352
				$clients[0]->query();
5353
			}
5354
		}
5355
	}
5356
5357
	public static function staticize_subdomain( $url ) {
5358
5359
		// Extract hostname from URL
5360
		$host = parse_url( $url, PHP_URL_HOST );
5361
5362
		// Explode hostname on '.'
5363
		$exploded_host = explode( '.', $host );
5364
5365
		// Retrieve the name and TLD
5366
		if ( count( $exploded_host ) > 1 ) {
5367
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5368
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5369
			// Rebuild domain excluding subdomains
5370
			$domain = $name . '.' . $tld;
5371
		} else {
5372
			$domain = $host;
5373
		}
5374
		// Array of Automattic domains
5375
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5376
5377
		// Return $url if not an Automattic domain
5378
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5379
			return $url;
5380
		}
5381
5382
		if ( is_ssl() ) {
5383
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5384
		}
5385
5386
		srand( crc32( basename( $url ) ) );
5387
		$static_counter = rand( 0, 2 );
5388
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5389
5390
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5391
	}
5392
5393
/* JSON API Authorization */
5394
5395
	/**
5396
	 * Handles the login action for Authorizing the JSON API
5397
	 */
5398
	function login_form_json_api_authorization() {
5399
		$this->verify_json_api_authorization_request();
5400
5401
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5402
5403
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5404
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5405
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5406
	}
5407
5408
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5409
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5410
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5411
			return $url;
5412
		}
5413
5414
		$parsed_url = parse_url( $url );
5415
		$url = strtok( $url, '?' );
5416
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5417
		if ( ! empty( $parsed_url['query'] ) )
5418
			$url .= "&{$parsed_url['query']}";
5419
5420
		return $url;
5421
	}
5422
5423
	// Make sure the POSTed request is handled by the same action
5424
	function preserve_action_in_login_form_for_json_api_authorization() {
5425
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5426
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5427
	}
5428
5429
	// If someone logs in to approve API access, store the Access Code in usermeta
5430
	function store_json_api_authorization_token( $user_login, $user ) {
5431
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5432
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5433
		$token = wp_generate_password( 32, false );
5434
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5435
	}
5436
5437
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5438
	function allow_wpcom_public_api_domain( $domains ) {
5439
		$domains[] = 'public-api.wordpress.com';
5440
		return $domains;
5441
	}
5442
5443
	// Add the Access Code details to the public-api.wordpress.com redirect
5444
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5445
		return add_query_arg(
5446
			urlencode_deep(
5447
				array(
5448
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5449
					'jetpack-user-id' => (int) $user->ID,
5450
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5451
				)
5452
			),
5453
			$redirect_to
5454
		);
5455
	}
5456
5457
5458
	/**
5459
	 * Verifies the request by checking the signature
5460
	 *
5461
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5462
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5463
	 *
5464
	 * @param null|array $environment
5465
	 */
5466
	function verify_json_api_authorization_request( $environment = null ) {
5467
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5468
5469
		$environment = is_null( $environment )
5470
			? $_REQUEST
5471
			: $environment;
5472
5473
		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...
5474
		$token = Jetpack_Data::get_access_token( $envUserId );
5475
		if ( ! $token || empty( $token->secret ) ) {
5476
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5477
		}
5478
5479
		$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' );
5480
5481
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5482
5483
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5484
			$signature = $jetpack_signature->sign_request(
5485
				$environment['token'],
5486
				$environment['timestamp'],
5487
				$environment['nonce'],
5488
				'',
5489
				'GET',
5490
				$environment['jetpack_json_api_original_query'],
5491
				null,
5492
				true
5493
			);
5494
		} else {
5495
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5496
		}
5497
5498
		if ( ! $signature ) {
5499
			wp_die( $die_error );
5500
		} else if ( is_wp_error( $signature ) ) {
5501
			wp_die( $die_error );
5502
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5503
			if ( is_ssl() ) {
5504
				// 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
5505
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5506
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5507
					wp_die( $die_error );
5508
				}
5509
			} else {
5510
				wp_die( $die_error );
5511
			}
5512
		}
5513
5514
		$timestamp = (int) $environment['timestamp'];
5515
		$nonce     = stripslashes( (string) $environment['nonce'] );
5516
5517
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5518
			// De-nonce the nonce, at least for 5 minutes.
5519
			// 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)
5520
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5521
			if ( $old_nonce_time < time() - 300 ) {
5522
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5523
			}
5524
		}
5525
5526
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5527
		$data_filters = array(
5528
			'state'        => 'opaque',
5529
			'client_id'    => 'int',
5530
			'client_title' => 'string',
5531
			'client_image' => 'url',
5532
		);
5533
5534
		foreach ( $data_filters as $key => $sanitation ) {
5535
			if ( ! isset( $data->$key ) ) {
5536
				wp_die( $die_error );
5537
			}
5538
5539
			switch ( $sanitation ) {
5540
			case 'int' :
5541
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5542
				break;
5543
			case 'opaque' :
5544
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5545
				break;
5546
			case 'string' :
5547
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5548
				break;
5549
			case 'url' :
5550
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5551
				break;
5552
			}
5553
		}
5554
5555
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5556
			wp_die( $die_error );
5557
		}
5558
	}
5559
5560
	function login_message_json_api_authorization( $message ) {
5561
		return '<p class="message">' . sprintf(
5562
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5563
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5564
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5565
	}
5566
5567
	/**
5568
	 * Get $content_width, but with a <s>twist</s> filter.
5569
	 */
5570
	public static function get_content_width() {
5571
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5572
		/**
5573
		 * Filter the Content Width value.
5574
		 *
5575
		 * @since 2.2.3
5576
		 *
5577
		 * @param string $content_width Content Width value.
5578
		 */
5579
		return apply_filters( 'jetpack_content_width', $content_width );
5580
	}
5581
5582
	/**
5583
	 * Pings the WordPress.com Mirror Site for the specified options.
5584
	 *
5585
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5586
	 *
5587
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5588
	 */
5589
	public function get_cloud_site_options( $option_names ) {
5590
		$option_names = array_filter( (array) $option_names, 'is_string' );
5591
5592
		Jetpack::load_xml_rpc_client();
5593
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5594
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5595
		if ( $xml->isError() ) {
5596
			return array(
5597
				'error_code' => $xml->getErrorCode(),
5598
				'error_msg'  => $xml->getErrorMessage(),
5599
			);
5600
		}
5601
		$cloud_site_options = $xml->getResponse();
5602
5603
		return $cloud_site_options;
5604
	}
5605
5606
	/**
5607
	 * Checks if the site is currently in an identity crisis.
5608
	 *
5609
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5610
	 */
5611
	public static function check_identity_crisis() {
5612
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5613
			return false;
5614
		}
5615
5616
		return Jetpack_Options::get_option( 'sync_error_idc' );
5617
	}
5618
5619
	/**
5620
	 * Checks whether the home and siteurl specifically are whitelisted
5621
	 * Written so that we don't have re-check $key and $value params every time
5622
	 * we want to check if this site is whitelisted, for example in footer.php
5623
	 *
5624
	 * @since  3.8.0
5625
	 * @return bool True = already whitelisted False = not whitelisted
5626
	 */
5627
	public static function is_staging_site() {
5628
		$is_staging = false;
5629
5630
		$known_staging = array(
5631
			'urls' => array(
5632
				'#\.staging\.wpengine\.com$#i', // WP Engine
5633
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5634
				),
5635
			'constants' => array(
5636
				'IS_WPE_SNAPSHOT',      // WP Engine
5637
				'KINSTA_DEV_ENV',       // Kinsta.com
5638
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5639
				'JETPACK_STAGING_MODE', // Generic
5640
				)
5641
			);
5642
		/**
5643
		 * Filters the flags of known staging sites.
5644
		 *
5645
		 * @since 3.9.0
5646
		 *
5647
		 * @param array $known_staging {
5648
		 *     An array of arrays that each are used to check if the current site is staging.
5649
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5650
		 *     @type array $constants PHP constants of known staging/developement environments.
5651
		 *  }
5652
		 */
5653
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5654
5655
		if ( isset( $known_staging['urls'] ) ) {
5656
			foreach ( $known_staging['urls'] as $url ){
5657
				if ( preg_match( $url, site_url() ) ) {
5658
					$is_staging = true;
5659
					break;
5660
				}
5661
			}
5662
		}
5663
5664
		if ( isset( $known_staging['constants'] ) ) {
5665
			foreach ( $known_staging['constants'] as $constant ) {
5666
				if ( defined( $constant ) && constant( $constant ) ) {
5667
					$is_staging = true;
5668
				}
5669
			}
5670
		}
5671
5672
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5673
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5674
			$is_staging = true;
5675
		}
5676
5677
		/**
5678
		 * Filters is_staging_site check.
5679
		 *
5680
		 * @since 3.9.0
5681
		 *
5682
		 * @param bool $is_staging If the current site is a staging site.
5683
		 */
5684
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5685
	}
5686
5687
	/**
5688
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5689
	 *
5690
	 * @return bool
5691
	 */
5692
	public static function validate_sync_error_idc_option() {
5693
		$is_valid = false;
5694
5695
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5696
		if ( false === $idc_allowed ) {
5697
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5698
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5699
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5700
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5701
				$transient_duration = HOUR_IN_SECONDS;
5702
			} else {
5703
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5704
				$idc_allowed = '1';
5705
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5706
			}
5707
5708
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5709
		}
5710
5711
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5712
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5713
		$local_options = self::get_sync_error_idc_option();
5714
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5715
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5716
				$is_valid = true;
5717
			}
5718
		}
5719
5720
		/**
5721
		 * Filters whether the sync_error_idc option is valid.
5722
		 *
5723
		 * @since 4.4.0
5724
		 *
5725
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5726
		 */
5727
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5728
5729
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5730
			// Since the option exists, and did not validate, delete it
5731
			Jetpack_Options::delete_option( 'sync_error_idc' );
5732
		}
5733
5734
		return $is_valid;
5735
	}
5736
5737
	/**
5738
	 * Normalizes a url by doing three things:
5739
	 *  - Strips protocol
5740
	 *  - Strips www
5741
	 *  - Adds a trailing slash
5742
	 *
5743
	 * @since 4.4.0
5744
	 * @param string $url
5745
	 * @return WP_Error|string
5746
	 */
5747
	public static function normalize_url_protocol_agnostic( $url ) {
5748
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5749
		if ( ! $parsed_url ) {
5750
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5751
		}
5752
5753
		// Strip www and protocols
5754
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5755
		return $url;
5756
	}
5757
5758
	/**
5759
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5760
	 *
5761
	 * @since 4.4.0
5762
	 *
5763
	 * @param array $response
5764
	 * @return array Array of the local urls, wpcom urls, and error code
5765
	 */
5766
	public static function get_sync_error_idc_option( $response = array() ) {
5767
		$local_options = array(
5768
			'home' => get_home_url(),
5769
			'siteurl' => get_site_url(),
5770
		);
5771
5772
		$options = array_merge( $local_options, $response );
5773
5774
		$returned_values = array();
5775
		foreach( $options as $key => $option ) {
5776
			if ( 'error_code' === $key ) {
5777
				$returned_values[ $key ] = $option;
5778
				continue;
5779
			}
5780
5781
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5782
				continue;
5783
			}
5784
5785
			$returned_values[ $key ] = $normalized_url;
5786
		}
5787
5788
		return $returned_values;
5789
	}
5790
5791
	/**
5792
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5793
	 * If set to true, the site will be put into staging mode.
5794
	 *
5795
	 * @since 4.3.2
5796
	 * @return bool
5797
	 */
5798
	public static function sync_idc_optin() {
5799
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5800
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5801
		} else {
5802
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5803
		}
5804
5805
		/**
5806
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5807
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5808
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5809
		 *
5810
		 * @since 4.3.2
5811
		 *
5812
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5813
		 */
5814
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5815
	}
5816
5817
	/**
5818
	 * Maybe Use a .min.css stylesheet, maybe not.
5819
	 *
5820
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5821
	 */
5822
	public static function maybe_min_asset( $url, $path, $plugin ) {
5823
		// Short out on things trying to find actual paths.
5824
		if ( ! $path || empty( $plugin ) ) {
5825
			return $url;
5826
		}
5827
5828
		$path = ltrim( $path, '/' );
5829
5830
		// Strip out the abspath.
5831
		$base = dirname( plugin_basename( $plugin ) );
5832
5833
		// Short out on non-Jetpack assets.
5834
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5835
			return $url;
5836
		}
5837
5838
		// File name parsing.
5839
		$file              = "{$base}/{$path}";
5840
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5841
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5842
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5843
		$extension         = array_shift( $file_name_parts_r );
5844
5845
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5846
			// Already pointing at the minified version.
5847
			if ( 'min' === $file_name_parts_r[0] ) {
5848
				return $url;
5849
			}
5850
5851
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5852
			if ( file_exists( $min_full_path ) ) {
5853
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5854
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5855
				if ( 'css' === $extension ) {
5856
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5857
					self::$min_assets[ $key ] = $path;
5858
				}
5859
			}
5860
		}
5861
5862
		return $url;
5863
	}
5864
5865
	/**
5866
	 * If the asset is minified, let's flag .min as the suffix.
5867
	 *
5868
	 * Attached to `style_loader_src` filter.
5869
	 *
5870
	 * @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...
5871
	 * @param string $handle The registered handle of the script in question.
5872
	 * @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...
5873
	 */
5874
	public static function set_suffix_on_min( $src, $handle ) {
5875
		if ( false === strpos( $src, '.min.css' ) ) {
5876
			return $src;
5877
		}
5878
5879
		if ( ! empty( self::$min_assets ) ) {
5880
			foreach ( self::$min_assets as $file => $path ) {
5881
				if ( false !== strpos( $src, $file ) ) {
5882
					wp_style_add_data( $handle, 'suffix', '.min' );
5883
					return $src;
5884
				}
5885
			}
5886
		}
5887
5888
		return $src;
5889
	}
5890
5891
	/**
5892
	 * Maybe inlines a stylesheet.
5893
	 *
5894
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5895
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5896
	 *
5897
	 * Attached to `style_loader_tag` filter.
5898
	 *
5899
	 * @param string $tag The tag that would link to the external asset.
5900
	 * @param string $handle The registered handle of the script in question.
5901
	 *
5902
	 * @return string
5903
	 */
5904
	public static function maybe_inline_style( $tag, $handle ) {
5905
		global $wp_styles;
5906
		$item = $wp_styles->registered[ $handle ];
5907
5908
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5909
			return $tag;
5910
		}
5911
5912
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5913
			$href = $matches[1];
5914
			// Strip off query string
5915
			if ( $pos = strpos( $href, '?' ) ) {
5916
				$href = substr( $href, 0, $pos );
5917
			}
5918
			// Strip off fragment
5919
			if ( $pos = strpos( $href, '#' ) ) {
5920
				$href = substr( $href, 0, $pos );
5921
			}
5922
		} else {
5923
			return $tag;
5924
		}
5925
5926
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5927
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5928
			return $tag;
5929
		}
5930
5931
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5932
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5933
			// And this isn't the pass that actually deals with the RTL version...
5934
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5935
				// Short out, as the RTL version will deal with it in a moment.
5936
				return $tag;
5937
			}
5938
		}
5939
5940
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5941
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5942
		if ( $css ) {
5943
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5944
			if ( empty( $item->extra['after'] ) ) {
5945
				wp_add_inline_style( $handle, $css );
5946
			} else {
5947
				array_unshift( $item->extra['after'], $css );
5948
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5949
			}
5950
		}
5951
5952
		return $tag;
5953
	}
5954
5955
	/**
5956
	 * Loads a view file from the views
5957
	 *
5958
	 * Data passed in with the $data parameter will be available in the
5959
	 * template file as $data['value']
5960
	 *
5961
	 * @param string $template - Template file to load
5962
	 * @param array $data - Any data to pass along to the template
5963
	 * @return boolean - If template file was found
5964
	 **/
5965
	public function load_view( $template, $data = array() ) {
5966
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5967
5968
		if( file_exists( $views_dir . $template ) ) {
5969
			require_once( $views_dir . $template );
5970
			return true;
5971
		}
5972
5973
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5974
		return false;
5975
	}
5976
5977
	/**
5978
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5979
	 */
5980
	public function deprecated_hooks() {
5981
		global $wp_filter;
5982
5983
		/*
5984
		 * Format:
5985
		 * deprecated_filter_name => replacement_name
5986
		 *
5987
		 * If there is no replacement, use null for replacement_name
5988
		 */
5989
		$deprecated_list = array(
5990
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5991
			'wpl_sharing_2014_1'                                     => null,
5992
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5993
			'jetpack_identity_crisis_options_to_check'               => null,
5994
			'update_option_jetpack_single_user_site'                 => null,
5995
			'audio_player_default_colors'                            => null,
5996
			'add_option_jetpack_featured_images_enabled'             => null,
5997
			'add_option_jetpack_update_details'                      => null,
5998
			'add_option_jetpack_updates'                             => null,
5999
			'add_option_jetpack_network_name'                        => null,
6000
			'add_option_jetpack_network_allow_new_registrations'     => null,
6001
			'add_option_jetpack_network_add_new_users'               => null,
6002
			'add_option_jetpack_network_site_upload_space'           => null,
6003
			'add_option_jetpack_network_upload_file_types'           => null,
6004
			'add_option_jetpack_network_enable_administration_menus' => null,
6005
			'add_option_jetpack_is_multi_site'                       => null,
6006
			'add_option_jetpack_is_main_network'                     => null,
6007
			'add_option_jetpack_main_network_site'                   => null,
6008
			'jetpack_sync_all_registered_options'                    => null,
6009
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6010
			'jetpack_is_post_mailable'                               => null,
6011
			'jetpack_seo_site_host'                                  => null,
6012
		);
6013
6014
		// This is a silly loop depth. Better way?
6015
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6016
			if ( has_action( $hook ) ) {
6017
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6018
					foreach( $values AS $hooked ) {
6019
						if ( is_callable( $hooked['function'] ) ) {
6020
							$function_name = 'an anonymous function';
6021
						} else {
6022
							$function_name = $hooked['function'];
6023
						}
6024
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6025
					}
6026
				}
6027
			}
6028
		}
6029
	}
6030
6031
	/**
6032
	 * Converts any url in a stylesheet, to the correct absolute url.
6033
	 *
6034
	 * Considerations:
6035
	 *  - Normal, relative URLs     `feh.png`
6036
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6037
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6038
	 *  - Absolute URLs             `http://domain.com/feh.png`
6039
	 *  - Domain root relative URLs `/feh.png`
6040
	 *
6041
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6042
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6043
	 *
6044
	 * @return mixed|string
6045
	 */
6046
	public static function absolutize_css_urls( $css, $css_file_url ) {
6047
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6048
		$css_dir = dirname( $css_file_url );
6049
		$p       = parse_url( $css_dir );
6050
		$domain  = sprintf(
6051
					'%1$s//%2$s%3$s%4$s',
6052
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6053
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6054
					$p['host'],
6055
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6056
				);
6057
6058
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6059
			$find = $replace = array();
6060
			foreach ( $matches as $match ) {
6061
				$url = trim( $match['path'], "'\" \t" );
6062
6063
				// If this is a data url, we don't want to mess with it.
6064
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6065
					continue;
6066
				}
6067
6068
				// If this is an absolute or protocol-agnostic url,
6069
				// we don't want to mess with it.
6070
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6071
					continue;
6072
				}
6073
6074
				switch ( substr( $url, 0, 1 ) ) {
6075
					case '/':
6076
						$absolute = $domain . $url;
6077
						break;
6078
					default:
6079
						$absolute = $css_dir . '/' . $url;
6080
				}
6081
6082
				$find[]    = $match[0];
6083
				$replace[] = sprintf( 'url("%s")', $absolute );
6084
			}
6085
			$css = str_replace( $find, $replace, $css );
6086
		}
6087
6088
		return $css;
6089
	}
6090
6091
	/**
6092
	 * This methods removes all of the registered css files on the front end
6093
	 * from Jetpack in favor of using a single file. In effect "imploding"
6094
	 * all the files into one file.
6095
	 *
6096
	 * Pros:
6097
	 * - Uses only ONE css asset connection instead of 15
6098
	 * - Saves a minimum of 56k
6099
	 * - Reduces server load
6100
	 * - Reduces time to first painted byte
6101
	 *
6102
	 * Cons:
6103
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6104
	 *		should not cause any issues with themes.
6105
	 * - Plugins/themes dequeuing styles no longer do anything. See
6106
	 *		jetpack_implode_frontend_css filter for a workaround
6107
	 *
6108
	 * For some situations developers may wish to disable css imploding and
6109
	 * instead operate in legacy mode where each file loads seperately and
6110
	 * can be edited individually or dequeued. This can be accomplished with
6111
	 * the following line:
6112
	 *
6113
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6114
	 *
6115
	 * @since 3.2
6116
	 **/
6117
	public function implode_frontend_css( $travis_test = false ) {
6118
		$do_implode = true;
6119
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6120
			$do_implode = false;
6121
		}
6122
6123
		/**
6124
		 * Allow CSS to be concatenated into a single jetpack.css file.
6125
		 *
6126
		 * @since 3.2.0
6127
		 *
6128
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6129
		 */
6130
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6131
6132
		// Do not use the imploded file when default behaviour was altered through the filter
6133
		if ( ! $do_implode ) {
6134
			return;
6135
		}
6136
6137
		// We do not want to use the imploded file in dev mode, or if not connected
6138
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6139
			if ( ! $travis_test ) {
6140
				return;
6141
			}
6142
		}
6143
6144
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6145
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6146
			return;
6147
		}
6148
6149
		/*
6150
		 * Now we assume Jetpack is connected and able to serve the single
6151
		 * file.
6152
		 *
6153
		 * In the future there will be a check here to serve the file locally
6154
		 * or potentially from the Jetpack CDN
6155
		 *
6156
		 * For now:
6157
		 * - Enqueue a single imploded css file
6158
		 * - Zero out the style_loader_tag for the bundled ones
6159
		 * - Be happy, drink scotch
6160
		 */
6161
6162
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6163
6164
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6165
6166
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6167
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6168
	}
6169
6170
	function concat_remove_style_loader_tag( $tag, $handle ) {
6171
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6172
			$tag = '';
6173
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6174
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6175
			}
6176
		}
6177
6178
		return $tag;
6179
	}
6180
6181
	/*
6182
	 * Check the heartbeat data
6183
	 *
6184
	 * Organizes the heartbeat data by severity.  For example, if the site
6185
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6186
	 *
6187
	 * Data will be added to "caution" array, if it either:
6188
	 *  - Out of date Jetpack version
6189
	 *  - Out of date WP version
6190
	 *  - Out of date PHP version
6191
	 *
6192
	 * $return array $filtered_data
6193
	 */
6194
	public static function jetpack_check_heartbeat_data() {
6195
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6196
6197
		$good    = array();
6198
		$caution = array();
6199
		$bad     = array();
6200
6201
		foreach ( $raw_data as $stat => $value ) {
6202
6203
			// Check jetpack version
6204
			if ( 'version' == $stat ) {
6205
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6206
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6207
					continue;
6208
				}
6209
			}
6210
6211
			// Check WP version
6212
			if ( 'wp-version' == $stat ) {
6213
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6214
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6215
					continue;
6216
				}
6217
			}
6218
6219
			// Check PHP version
6220
			if ( 'php-version' == $stat ) {
6221
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6222
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6223
					continue;
6224
				}
6225
			}
6226
6227
			// Check ID crisis
6228
			if ( 'identitycrisis' == $stat ) {
6229
				if ( 'yes' == $value ) {
6230
					$bad[ $stat ] = $value;
6231
					continue;
6232
				}
6233
			}
6234
6235
			// The rest are good :)
6236
			$good[ $stat ] = $value;
6237
		}
6238
6239
		$filtered_data = array(
6240
			'good'    => $good,
6241
			'caution' => $caution,
6242
			'bad'     => $bad
6243
		);
6244
6245
		return $filtered_data;
6246
	}
6247
6248
6249
	/*
6250
	 * This method is used to organize all options that can be reset
6251
	 * without disconnecting Jetpack.
6252
	 *
6253
	 * It is used in class.jetpack-cli.php to reset options
6254
	 *
6255
	 * @return array of options to delete.
6256
	 */
6257
	public static function get_jetpack_options_for_reset() {
6258
		$jetpack_options            = Jetpack_Options::get_option_names();
6259
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6260
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6261
6262
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6263
6264
		// A manual build of the wp options
6265
		$wp_options = array(
6266
			'sharing-options',
6267
			'disabled_likes',
6268
			'disabled_reblogs',
6269
			'jetpack_comments_likes_enabled',
6270
			'wp_mobile_excerpt',
6271
			'wp_mobile_featured_images',
6272
			'wp_mobile_app_promos',
6273
			'stats_options',
6274
			'stats_dashboard_widget',
6275
			'safecss_preview_rev',
6276
			'safecss_rev',
6277
			'safecss_revision_migrated',
6278
			'nova_menu_order',
6279
			'jetpack_portfolio',
6280
			'jetpack_portfolio_posts_per_page',
6281
			'jetpack_testimonial',
6282
			'jetpack_testimonial_posts_per_page',
6283
			'wp_mobile_custom_css',
6284
			'sharedaddy_disable_resources',
6285
			'sharing-options',
6286
			'sharing-services',
6287
			'site_icon_temp_data',
6288
			'featured-content',
6289
			'site_logo',
6290
			'jetpack_dismissed_notices',
6291
		);
6292
6293
		// Flag some Jetpack options as unsafe
6294
		$unsafe_options = array(
6295
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6296
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6297
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6298
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6299
6300
			// non_compact
6301
			'activated',
6302
6303
			// private
6304
			'register',
6305
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6306
			'user_token',                  // (string) The User Token of this site. (deprecated)
6307
			'user_tokens'
6308
		);
6309
6310
		// Remove the unsafe Jetpack options
6311
		foreach ( $unsafe_options as $unsafe_option ) {
6312
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6313
				unset( $all_jp_options[ $key ] );
6314
			}
6315
		}
6316
6317
		$options = array(
6318
			'jp_options' => $all_jp_options,
6319
			'wp_options' => $wp_options
6320
		);
6321
6322
		return $options;
6323
	}
6324
6325
	/**
6326
	 * Check if an option of a Jetpack module has been updated.
6327
	 *
6328
	 * If any module option has been updated before Jump Start has been dismissed,
6329
	 * update the 'jumpstart' option so we can hide Jump Start.
6330
	 *
6331
	 * @param string $option_name
6332
	 *
6333
	 * @return bool
6334
	 */
6335
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6336
		// Bail if Jump Start has already been dismissed
6337
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6338
			return false;
6339
		}
6340
6341
		$jetpack = Jetpack::init();
6342
6343
		// Manual build of module options
6344
		$option_names = self::get_jetpack_options_for_reset();
6345
6346
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6347
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6348
6349
			//Jump start is being dismissed send data to MC Stats
6350
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6351
6352
			$jetpack->do_stats( 'server_side' );
6353
		}
6354
6355
	}
6356
6357
	/*
6358
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6359
	 * so we can bring them directly to their site in calypso.
6360
	 *
6361
	 * @param string | url
6362
	 * @return string | url without the guff
6363
	 */
6364
	public static function build_raw_urls( $url ) {
6365
		$strip_http = '/.*?:\/\//i';
6366
		$url = preg_replace( $strip_http, '', $url  );
6367
		$url = str_replace( '/', '::', $url );
6368
		return $url;
6369
	}
6370
6371
	/**
6372
	 * Stores and prints out domains to prefetch for page speed optimization.
6373
	 *
6374
	 * @param mixed $new_urls
6375
	 */
6376
	public static function dns_prefetch( $new_urls = null ) {
6377
		static $prefetch_urls = array();
6378
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6379
			echo "\r\n";
6380
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6381
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6382
			}
6383
		} elseif ( ! empty( $new_urls ) ) {
6384
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6385
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6386
			}
6387
			foreach ( (array) $new_urls as $this_new_url ) {
6388
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6389
			}
6390
			$prefetch_urls = array_unique( $prefetch_urls );
6391
		}
6392
	}
6393
6394
	public function wp_dashboard_setup() {
6395
		if ( self::is_active() ) {
6396
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6397
			$widget_title = __( 'Site Stats', 'jetpack' );
6398
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6399
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6400
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6401
		}
6402
6403
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6404
			wp_add_dashboard_widget(
6405
				'jetpack_summary_widget',
6406
				$widget_title,
0 ignored issues
show
Bug introduced by
The variable $widget_title 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...
6407
				array( __CLASS__, 'dashboard_widget' )
6408
			);
6409
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6410
6411
			// If we're inactive and not in development mode, sort our box to the top.
6412
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6413
				global $wp_meta_boxes;
6414
6415
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6416
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6417
6418
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6419
			}
6420
		}
6421
	}
6422
6423
	/**
6424
	 * @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...
6425
	 * @return mixed
6426
	 */
6427
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6428
		if ( ! is_array( $sorted ) ) {
6429
			return $sorted;
6430
		}
6431
6432
		foreach ( $sorted as $box_context => $ids ) {
6433
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6434
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6435
				continue;
6436
			}
6437
6438
			$ids_array = explode( ',', $ids );
6439
			$key = array_search( 'dashboard_stats', $ids_array );
6440
6441
			if ( false !== $key ) {
6442
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6443
				$ids_array[ $key ] = 'jetpack_summary_widget';
6444
				$sorted[ $box_context ] = implode( ',', $ids_array );
6445
				// We've found it, stop searching, and just return.
6446
				break;
6447
			}
6448
		}
6449
6450
		return $sorted;
6451
	}
6452
6453
	public static function dashboard_widget() {
6454
		/**
6455
		 * Fires when the dashboard is loaded.
6456
		 *
6457
		 * @since 3.4.0
6458
		 */
6459
		do_action( 'jetpack_dashboard_widget' );
6460
	}
6461
6462
	public static function dashboard_widget_footer() {
6463
		?>
6464
		<footer>
6465
6466
		<div class="protect">
6467
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6468
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6469
				<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>
6470
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6471
				<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' ); ?>">
6472
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6473
				</a>
6474
			<?php else : ?>
6475
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6476
			<?php endif; ?>
6477
		</div>
6478
6479
		<div class="akismet">
6480
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6481
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6482
				<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>
6483
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6484
				<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">
6485
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6486
				</a>
6487
			<?php else : ?>
6488
				<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>
6489
			<?php endif; ?>
6490
		</div>
6491
6492
		</footer>
6493
		<?php
6494
	}
6495
6496
	public function dashboard_widget_connect_to_wpcom() {
6497
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6498
			return;
6499
		}
6500
		?>
6501
		<div class="wpcom-connect">
6502
			<div class="jp-emblem">
6503
			<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0" y="0" viewBox="0 0 172.9 172.9" enable-background="new 0 0 172.9 172.9" xml:space="preserve">
6504
				<path d="M86.4 0C38.7 0 0 38.7 0 86.4c0 47.7 38.7 86.4 86.4 86.4s86.4-38.7 86.4-86.4C172.9 38.7 134.2 0 86.4 0zM83.1 106.6l-27.1-6.9C49 98 45.7 90.1 49.3 84l33.8-58.5V106.6zM124.9 88.9l-33.8 58.5V66.3l27.1 6.9C125.1 74.9 128.4 82.8 124.9 88.9z"/>
6505
			</svg>
6506
			</div>
6507
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6508
			<p><?php echo wp_kses( __( 'Connecting Jetpack will show you <strong>stats</strong> about your traffic, <strong>protect</strong> you from brute force attacks, <strong>speed up</strong> your images and photos, and enable other <strong>traffic and security</strong> features.', 'jetpack' ), 'jetpack' ) ?></p>
6509
6510
			<div class="actions">
6511
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6512
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6513
				</a>
6514
			</div>
6515
		</div>
6516
		<?php
6517
	}
6518
6519
	/**
6520
	 * Return string containing the Jetpack logo.
6521
	 *
6522
	 * @since 3.9.0
6523
	 *
6524
	 * @return string
6525
	 */
6526
	public static function get_jp_emblem() {
6527
		return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0" y="0" width="20" height="20" viewBox="0 0 172.9 172.9" enable-background="new 0 0 172.9 172.9" xml:space="preserve"><path d="M86.4 0C38.7 0 0 38.7 0 86.4c0 47.7 38.7 86.4 86.4 86.4s86.4-38.7 86.4-86.4C172.9 38.7 134.2 0 86.4 0zM83.1 106.6l-27.1-6.9C49 98 45.7 90.1 49.3 84l33.8-58.5V106.6zM124.9 88.9l-33.8 58.5V66.3l27.1 6.9C125.1 74.9 128.4 82.8 124.9 88.9z" /></svg>';
6528
	}
6529
6530
	/*
6531
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6532
	 */
6533
	function jetpack_icon_user_connected( $columns ) {
6534
		$columns['user_jetpack'] = '';
6535
		return $columns;
6536
	}
6537
6538
	/*
6539
	 * Show Jetpack icon if the user is linked.
6540
	 */
6541
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6542
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6543
			$emblem_html = sprintf(
6544
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6545
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6546
				Jetpack::get_jp_emblem()
6547
			);
6548
			return $emblem_html;
6549
		}
6550
6551
		return $val;
6552
	}
6553
6554
	/*
6555
	 * Style the Jetpack user column
6556
	 */
6557
	function jetpack_user_col_style() {
6558
		global $current_screen;
6559
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6560
			<style>
6561
				.fixed .column-user_jetpack {
6562
					width: 21px;
6563
				}
6564
				.jp-emblem-user-admin svg {
6565
					width: 20px;
6566
					height: 20px;
6567
				}
6568
				.jp-emblem-user-admin path {
6569
					fill: #8cc258;
6570
				}
6571
			</style>
6572
		<?php }
6573
	}
6574
}
6575