Completed
Push — try/user_token-auth-for-rest-a... ( 57dad5...fc1d66 )
by
unknown
07:43
created

Jetpack::wp_rest_authenticate()   C

Complexity

Conditions 16
Paths 8

Size

Total Lines 73
Code Lines 38

Duplication

Lines 18
Ratio 24.66 %

Importance

Changes 0
Metric Value
cc 16
eloc 38
nc 8
nop 1
dl 18
loc 73
rs 5.4156
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'jetpack-responsive-videos-style',
46
		'jetpack-social-menu',
47
		'tiled-gallery',
48
		'jetpack_display_posts_widget',
49
		'gravatar-profile-widget',
50
		'goodreads-widget',
51
		'jetpack_social_media_icons_widget',
52
		'jetpack-top-posts-widget',
53
		'jetpack_image_widget',
54
		'jetpack-my-community-widget',
55
		'wordads',
56
	);
57
58
	public $plugins_to_deactivate = array(
59
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
60
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
61
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
62
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
63
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
64
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
65
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
66
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
67
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
68
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
69
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
70
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
71
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
72
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
73
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
74
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
75
	);
76
77
	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...
78
		'administrator' => 'manage_options',
79
		'editor'        => 'edit_others_posts',
80
		'author'        => 'publish_posts',
81
		'contributor'   => 'edit_posts',
82
		'subscriber'    => 'read',
83
	);
84
85
	/**
86
	 * Map of modules that have conflicts with plugins and should not be auto-activated
87
	 * if the plugins are active.  Used by filter_default_modules
88
	 *
89
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
90
	 * change `module-slug` and add this to your plugin:
91
	 *
92
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
93
	 * function my_jetpack_get_default_modules( $modules ) {
94
	 *     return array_diff( $modules, array( 'module-slug' ) );
95
	 * }
96
	 *
97
	 * @var array
98
	 */
99
	private $conflicting_plugins = array(
100
		'comments'          => array(
101
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
102
			'Disqus'                               => 'disqus-comment-system/disqus.php',
103
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
104
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
105
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
106
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
107
		),
108
		'contact-form'      => array(
109
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
110
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
111
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
112
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
113
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
114
		),
115
		'minileven'         => array(
116
			'WPtouch'                              => 'wptouch/wptouch.php',
117
		),
118
		'latex'             => array(
119
			'LaTeX for WordPress'                  => 'latex/latex.php',
120
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
121
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
122
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
123
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
124
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
125
		),
126
		'protect'           => array(
127
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
128
			'Captcha'                              => 'captcha/captcha.php',
129
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
130
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
131
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
132
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
133
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
134
			'Security-protection'                  => 'security-protection/security-protection.php',
135
			'Login Security'                       => 'login-security/login-security.php',
136
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
137
			'Wordfence Security'                   => 'wordfence/wordfence.php',
138
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
139
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
140
		),
141
		'random-redirect'   => array(
142
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
143
		),
144
		'related-posts'     => array(
145
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
146
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
147
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
148
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
149
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
150
			'outbrain'                             => 'outbrain/outbrain.php',
151
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
152
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
153
		),
154
		'sharedaddy'        => array(
155
			'AddThis'                              => 'addthis/addthis_social_widget.php',
156
			'Add To Any'                           => 'add-to-any/add-to-any.php',
157
			'ShareThis'                            => 'share-this/sharethis.php',
158
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
159
		),
160
		'seo-tools' => array(
161
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
162
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
163
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
164
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
165
		),
166
		'verification-tools' => array(
167
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
168
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
169
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
170
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
171
		),
172
		'widget-visibility' => array(
173
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
174
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
175
		),
176
		'sitemaps' => array(
177
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
178
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
179
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
180
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
181
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
182
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
183
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
184
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
185
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
186
			'Sitemap'                              => 'sitemap/sitemap.php',
187
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
188
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
189
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
190
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
191
		),
192
	);
193
194
	/**
195
	 * Plugins for which we turn off our Facebook OG Tags implementation.
196
	 *
197
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
198
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
199
	 *
200
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
201
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
202
	 */
203
	private $open_graph_conflicting_plugins = array(
204
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
205
		                                                         // 2 Click Social Media Buttons
206
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
207
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
208
		'autodescription/autodescription.php',                   // The SEO Framework
209
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
210
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
211
		                                                         // Open Graph Meta Tags by Heateor
212
		'facebook/facebook.php',                                 // Facebook (official plugin)
213
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
214
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
215
		                                                         // Facebook Featured Image & OG Meta Tags
216
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
217
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
218
		                                                         // Facebook Open Graph Meta Tags for WordPress
219
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
220
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
221
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
222
		                                                         // Fedmich's Facebook Open Graph Meta
223
		'header-footer/plugin.php',                              // Header and Footer
224
		'network-publisher/networkpub.php',                      // Network Publisher
225
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
226
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
227
		                                                         // NextScripts SNAP
228
		'og-tags/og-tags.php',                                   // OG Tags
229
		'opengraph/opengraph.php',                               // Open Graph
230
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
231
		                                                         // Open Graph Protocol Framework
232
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
233
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
234
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
235
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
236
		'sharepress/sharepress.php',                             // SharePress
237
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
238
		'social-discussions/social-discussions.php',             // Social Discussions
239
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
240
		'socialize/socialize.php',                               // Socialize
241
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
242
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
243
		                                                         // Tweet, Like, Google +1 and Share
244
		'wordbooker/wordbooker.php',                             // Wordbooker
245
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
246
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
247
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
248
		                                                         // WP Facebook Like Send & Open Graph Meta
249
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
250
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
251
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
252
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
253
	);
254
255
	/**
256
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
257
	 */
258
	private $twitter_cards_conflicting_plugins = array(
259
	//	'twitter/twitter.php',                       // The official one handles this on its own.
260
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
261
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
262
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
263
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
264
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
265
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
266
		'twitter-cards/twitter-cards.php',           // Twitter Cards
267
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
268
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
269
	);
270
271
	/**
272
	 * Message to display in admin_notice
273
	 * @var string
274
	 */
275
	public $message = '';
276
277
	/**
278
	 * Error to display in admin_notice
279
	 * @var string
280
	 */
281
	public $error = '';
282
283
	/**
284
	 * Modules that need more privacy description.
285
	 * @var string
286
	 */
287
	public $privacy_checks = '';
288
289
	/**
290
	 * Stats to record once the page loads
291
	 *
292
	 * @var array
293
	 */
294
	public $stats = array();
295
296
	/**
297
	 * Jetpack_Sync object
298
	 */
299
	public $sync;
300
301
	/**
302
	 * Verified data for JSON authorization request
303
	 */
304
	public $json_api_authorization_request = array();
305
306
	/**
307
	 * Holds the singleton instance of this class
308
	 * @since 2.3.3
309
	 * @var Jetpack
310
	 */
311
	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...
312
313
	/**
314
	 * Singleton
315
	 * @static
316
	 */
317
	public static function init() {
318
		if ( ! self::$instance ) {
319
			self::$instance = new Jetpack;
320
321
			self::$instance->plugin_upgrade();
322
		}
323
324
		return self::$instance;
325
	}
326
327
	/**
328
	 * Must never be called statically
329
	 */
330
	function plugin_upgrade() {
331
		if ( Jetpack::is_active() ) {
332
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
333
			if ( JETPACK__VERSION != $version ) {
334
335
				// Check which active modules actually exist and remove others from active_modules list
336
				$unfiltered_modules = Jetpack::get_active_modules();
337
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
338
				if ( array_diff( $unfiltered_modules, $modules ) ) {
339
					Jetpack::update_active_modules( $modules );
340
				}
341
342
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
343
344
				// Upgrade to 4.3.0
345
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
346
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
347
				}
348
349
				Jetpack::maybe_set_version_option();
350
			}
351
		}
352
	}
353
354
	static function activate_manage( ) {
355
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
356
			self::activate_module( 'manage', false, false );
357
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
358
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
359
		}
360
	}
361
362
	static function update_active_modules( $modules ) {
363
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
364
365
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
366
367
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
368
			$new_active_modules = array_diff( $modules, $current_modules );
369
			foreach( $new_active_modules as $module ) {
370
				/**
371
				 * Fires when a specific module is activated.
372
				 *
373
				 * @since 1.9.0
374
				 *
375
				 * @param string $module Module slug.
376
				 * @param boolean $success whether the module was activated. @since 4.2
377
				 */
378
				do_action( 'jetpack_activate_module', $module, $success );
379
380
				/**
381
				 * Fires when a module is activated.
382
				 * The dynamic part of the filter, $module, is the module slug.
383
				 *
384
				 * @since 1.9.0
385
				 *
386
				 * @param string $module Module slug.
387
				 */
388
				do_action( "jetpack_activate_module_$module", $module );
389
			}
390
391
			$new_deactive_modules = array_diff( $current_modules, $modules );
392
			foreach( $new_deactive_modules as $module ) {
393
				/**
394
				 * Fired after a module has been deactivated.
395
				 *
396
				 * @since 4.2.0
397
				 *
398
				 * @param string $module Module slug.
399
				 * @param boolean $success whether the module was deactivated.
400
				 */
401
				do_action( 'jetpack_deactivate_module', $module, $success );
402
				/**
403
				 * Fires when a module is deactivated.
404
				 * The dynamic part of the filter, $module, is the module slug.
405
				 *
406
				 * @since 1.9.0
407
				 *
408
				 * @param string $module Module slug.
409
				 */
410
				do_action( "jetpack_deactivate_module_$module", $module );
411
			}
412
		}
413
414
		return $success;
415
	}
416
417
	static function delete_active_modules() {
418
		self::update_active_modules( array() );
419
	}
420
421
	/**
422
	 * Constructor.  Initializes WordPress hooks
423
	 */
424
	private function __construct() {
425
		/*
426
		 * Check for and alert any deprecated hooks
427
		 */
428
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
429
430
431
		/*
432
		 * Load things that should only be in Network Admin.
433
		 *
434
		 * For now blow away everything else until a more full
435
		 * understanding of what is needed at the network level is
436
		 * available
437
		 */
438
		if( is_multisite() ) {
439
			Jetpack_Network::init();
440
		}
441
442
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
443
444
		// Unlink user before deleting the user from .com
445
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
446
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
447
448
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
449
			@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...
450
451
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
452
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
453
454
			$this->require_jetpack_authentication();
455
456
			if ( Jetpack::is_active() ) {
457
				// Hack to preserve $HTTP_RAW_POST_DATA
458
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
459
460
				$signed = $this->verify_xml_rpc_signature();
461
				if ( $signed && ! is_wp_error( $signed ) ) {
462
					// The actual API methods.
463
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
464
				} else {
465
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
466
					// active Jetpack connection, so that additional users can link their account.
467
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
468
				}
469
			} else {
470
				// The bootstrap API methods.
471
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
472
			}
473
474
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
475
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
476
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
477
			$this->require_jetpack_authentication();
478
			$this->add_remote_request_handlers();
479
		} else {
480
			if ( Jetpack::is_active() ) {
481
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
482
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
483
			}
484
		}
485
486
		if ( Jetpack::is_active() ) {
487
			Jetpack_Heartbeat::init();
488
		}
489
490
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authenticate' ) );
491
492
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
493
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
494
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
495
		}
496
497
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
498
499
		add_action( 'admin_init', array( $this, 'admin_init' ) );
500
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
501
502
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
503
504
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
505
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
506
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
507
508
		// returns HTTPS support status
509
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
510
511
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
512
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
513
514
		// JITM AJAX callback function
515
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
516
517
		// Universal ajax callback for all tracking events triggered via js
518
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
519
520
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
521
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
522
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
523
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
524
525
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
526
527
		/**
528
		 * These actions run checks to load additional files.
529
		 * They check for external files or plugins, so they need to run as late as possible.
530
		 */
531
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
532
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
533
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
534
535
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
536
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
537
538
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
539
540
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
541
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
542
543
		// A filter to control all just in time messages
544
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
545
546
		// Update the Jetpack plan from API on heartbeats
547
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
548
549
		/**
550
		 * This is the hack to concatinate all css files into one.
551
		 * For description and reasoning see the implode_frontend_css method
552
		 *
553
		 * Super late priority so we catch all the registered styles
554
		 */
555
		if( !is_admin() ) {
556
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
557
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
558
		}
559
	}
560
561
	function jetpack_admin_ajax_tracks_callback() {
562
		// Check for nonce
563
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
564
			wp_die( 'Permissions check failed.' );
565
		}
566
567
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
568
			wp_die( 'No valid event name or type.' );
569
		}
570
571
		$tracks_data = array();
572
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
573
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
574
		}
575
576
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
577
		wp_send_json_success();
578
		wp_die();
579
	}
580
581
	/**
582
	 * The callback for the JITM ajax requests.
583
	 */
584
	function jetpack_jitm_ajax_callback() {
585
		// Check for nonce
586
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
587
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
588
		}
589
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
590
			$module_slug = $_REQUEST['jitmModule'];
591
			Jetpack::log( 'activate', $module_slug );
592
			Jetpack::activate_module( $module_slug, false, false );
593
			Jetpack::state( 'message', 'no_message' );
594
595
			//A Jetpack module is being activated through a JITM, track it
596
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
597
			$this->do_stats( 'server_side' );
598
599
			wp_send_json_success();
600
		}
601
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
602
			// get the hide_jitm options array
603
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
604
			$module_slug = $_REQUEST['jitmModule'];
605
606
			if( ! $jetpack_hide_jitm ) {
607
				$jetpack_hide_jitm = array(
608
					$module_slug => 'hide'
609
				);
610
			} else {
611
				$jetpack_hide_jitm[$module_slug] = 'hide';
612
			}
613
614
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
615
616
			//jitm is being dismissed forever, track it
617
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
618
			$this->do_stats( 'server_side' );
619
620
			wp_send_json_success();
621
		}
622 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
623
			$module_slug = $_REQUEST['jitmModule'];
624
625
			// User went to WordPress.com, track this
626
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
627
			$this->do_stats( 'server_side' );
628
629
			wp_send_json_success();
630
		}
631 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
632
			$track = $_REQUEST['jitmModule'];
633
634
			// User is viewing JITM, track it.
635
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
636
			$this->do_stats( 'server_side' );
637
638
			wp_send_json_success();
639
		}
640
	}
641
642
	/**
643
	 * If there are any stats that need to be pushed, but haven't been, push them now.
644
	 */
645
	function __destruct() {
646
		if ( ! empty( $this->stats ) ) {
647
			$this->do_stats( 'server_side' );
648
		}
649
	}
650
651
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
652
		switch( $cap ) {
653
			case 'jetpack_connect' :
654
			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...
655
				if ( Jetpack::is_development_mode() ) {
656
					$caps = array( 'do_not_allow' );
657
					break;
658
				}
659
				/**
660
				 * Pass through. If it's not development mode, these should match disconnect.
661
				 * Let users disconnect if it's development mode, just in case things glitch.
662
				 */
663
			case 'jetpack_disconnect' :
664
				/**
665
				 * In multisite, can individual site admins manage their own connection?
666
				 *
667
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
668
				 */
669
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
670
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
671
						/**
672
						 * We need to update the option name -- it's terribly unclear which
673
						 * direction the override goes.
674
						 *
675
						 * @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...
676
						 */
677
						$caps = array( 'do_not_allow' );
678
						break;
679
					}
680
				}
681
682
				$caps = array( 'manage_options' );
683
				break;
684
			case 'jetpack_manage_modules' :
685
			case 'jetpack_activate_modules' :
686
			case 'jetpack_deactivate_modules' :
687
				$caps = array( 'manage_options' );
688
				break;
689
			case 'jetpack_configure_modules' :
690
				$caps = array( 'manage_options' );
691
				break;
692
			case 'jetpack_network_admin_page':
693
			case 'jetpack_network_settings_page':
694
				$caps = array( 'manage_network_plugins' );
695
				break;
696
			case 'jetpack_network_sites_page':
697
				$caps = array( 'manage_sites' );
698
				break;
699
			case 'jetpack_admin_page' :
700
				if ( Jetpack::is_development_mode() ) {
701
					$caps = array( 'manage_options' );
702
					break;
703
				} else {
704
					$caps = array( 'read' );
705
				}
706
				break;
707
			case 'jetpack_connect_user' :
708
				if ( Jetpack::is_development_mode() ) {
709
					$caps = array( 'do_not_allow' );
710
					break;
711
				}
712
				$caps = array( 'read' );
713
				break;
714
		}
715
		return $caps;
716
	}
717
718
	function require_jetpack_authentication() {
719
		// Don't let anyone authenticate
720
		$_COOKIE = array();
721
		remove_all_filters( 'authenticate' );
722
		remove_all_actions( 'wp_login_failed' );
723
724
		if ( Jetpack::is_active() ) {
725
			// Allow Jetpack authentication
726
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
727
		}
728
	}
729
730
	/**
731
	 * Load language files
732
	 * @action plugins_loaded
733
	 */
734
	public static function plugin_textdomain() {
735
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
736
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
737
	}
738
739
	/**
740
	 * Register assets for use in various modules and the Jetpack admin page.
741
	 *
742
	 * @uses wp_script_is, wp_register_script, plugins_url
743
	 * @action wp_loaded
744
	 * @return null
745
	 */
746
	public function register_assets() {
747
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
748
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
749
		}
750
751 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
752
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
753
		}
754
755 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
756
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
757
		}
758
759 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
760
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
761
		}
762
763
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
764
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
765
766
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
767
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
768
			if ( ! is_numeric( $fb_app_id ) ) {
769
				$fb_app_id = '';
770
			}
771
			wp_localize_script(
772
				'jetpack-facebook-embed',
773
				'jpfbembed',
774
				array(
775
					'appid' => $fb_app_id,
776
					'locale' => $this->get_locale(),
777
				)
778
			);
779
		}
780
781
		/**
782
		 * As jetpack_register_genericons is by default fired off a hook,
783
		 * the hook may have already fired by this point.
784
		 * So, let's just trigger it manually.
785
		 */
786
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
787
		jetpack_register_genericons();
788
789
		/**
790
		 * Register the social logos
791
		 */
792
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
793
		jetpack_register_social_logos();
794
795 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
796
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
797
	}
798
799
	/**
800
	 * Guess locale from language code.
801
	 *
802
	 * @param string $lang Language code.
803
	 * @return string|bool
804
	 */
805 View Code Duplication
	function guess_locale_from_lang( $lang ) {
806
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
807
			return 'en_US';
808
		}
809
810
		if ( ! class_exists( 'GP_Locales' ) ) {
811
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
812
				return false;
813
			}
814
815
			require JETPACK__GLOTPRESS_LOCALES_PATH;
816
		}
817
818
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
819
			// WP.com: get_locale() returns 'it'
820
			$locale = GP_Locales::by_slug( $lang );
821
		} else {
822
			// Jetpack: get_locale() returns 'it_IT';
823
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
824
		}
825
826
		if ( ! $locale ) {
827
			return false;
828
		}
829
830
		if ( empty( $locale->facebook_locale ) ) {
831
			if ( empty( $locale->wp_locale ) ) {
832
				return false;
833
			} else {
834
				// Facebook SDK is smart enough to fall back to en_US if a
835
				// locale isn't supported. Since supported Facebook locales
836
				// can fall out of sync, we'll attempt to use the known
837
				// wp_locale value and rely on said fallback.
838
				return $locale->wp_locale;
839
			}
840
		}
841
842
		return $locale->facebook_locale;
843
	}
844
845
	/**
846
	 * Get the locale.
847
	 *
848
	 * @return string|bool
849
	 */
850
	function get_locale() {
851
		$locale = $this->guess_locale_from_lang( get_locale() );
852
853
		if ( ! $locale ) {
854
			$locale = 'en_US';
855
		}
856
857
		return $locale;
858
	}
859
860
	/**
861
	 * Device Pixels support
862
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
863
	 */
864
	function devicepx() {
865
		if ( Jetpack::is_active() ) {
866
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
867
		}
868
	}
869
870
	/**
871
	 * Return the network_site_url so that .com knows what network this site is a part of.
872
	 * @param  bool $option
873
	 * @return string
874
	 */
875
	public function jetpack_main_network_site_option( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
876
		return network_site_url();
877
	}
878
	/**
879
	 * Network Name.
880
	 */
881
	static function network_name( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
882
		global $current_site;
883
		return $current_site->site_name;
884
	}
885
	/**
886
	 * Does the network allow new user and site registrations.
887
	 * @return string
888
	 */
889
	static function network_allow_new_registrations( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
890
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
891
	}
892
	/**
893
	 * Does the network allow admins to add new users.
894
	 * @return boolian
895
	 */
896
	static function network_add_new_users( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
897
		return (bool) get_site_option( 'add_new_users' );
898
	}
899
	/**
900
	 * File upload psace left per site in MB.
901
	 *  -1 means NO LIMIT.
902
	 * @return number
903
	 */
904
	static function network_site_upload_space( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
905
		// value in MB
906
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
907
	}
908
909
	/**
910
	 * Network allowed file types.
911
	 * @return string
912
	 */
913
	static function network_upload_file_types( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
914
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
915
	}
916
917
	/**
918
	 * Maximum file upload size set by the network.
919
	 * @return number
920
	 */
921
	static function network_max_upload_file_size( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
922
		// value in KB
923
		return get_site_option( 'fileupload_maxk', 300 );
924
	}
925
926
	/**
927
	 * Lets us know if a site allows admins to manage the network.
928
	 * @return array
929
	 */
930
	static function network_enable_administration_menus( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
931
		return get_site_option( 'menu_items' );
932
	}
933
934
	/**
935
	 * If a user has been promoted to or demoted from admin, we need to clear the
936
	 * jetpack_other_linked_admins transient.
937
	 *
938
	 * @since 4.3.2
939
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
940
	 *
941
	 * @param int    $user_id   The user ID whose role changed.
942
	 * @param string $role      The new role.
943
	 * @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...
944
	 */
945
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
946
		if ( 'administrator' == $role
947
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
948
			|| is_null( $old_roles )
949
		) {
950
			delete_transient( 'jetpack_other_linked_admins' );
951
		}
952
	}
953
954
	/**
955
	 * Checks to see if there are any other users available to become primary
956
	 * Users must both:
957
	 * - Be linked to wpcom
958
	 * - Be an admin
959
	 *
960
	 * @return mixed False if no other users are linked, Int if there are.
961
	 */
962
	static function get_other_linked_admins() {
963
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
964
965
		if ( false === $other_linked_users ) {
966
			$admins = get_users( array( 'role' => 'administrator' ) );
967
			if ( count( $admins ) > 1 ) {
968
				$available = array();
969
				foreach ( $admins as $admin ) {
970
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
971
						$available[] = $admin->ID;
972
					}
973
				}
974
975
				$count_connected_admins = count( $available );
976
				if ( count( $available ) > 1 ) {
977
					$other_linked_users = $count_connected_admins;
978
				} else {
979
					$other_linked_users = 0;
980
				}
981
			} else {
982
				$other_linked_users = 0;
983
			}
984
985
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
986
		}
987
988
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
989
	}
990
991
	/**
992
	 * Return whether we are dealing with a multi network setup or not.
993
	 * The reason we are type casting this is because we want to avoid the situation where
994
	 * the result is false since when is_main_network_option return false it cases
995
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
996
	 * database which could be set to anything as opposed to what this function returns.
997
	 * @param  bool  $option
998
	 *
999
	 * @return boolean
1000
	 */
1001
	public function is_main_network_option( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1002
		// return '1' or ''
1003
		return (string) (bool) Jetpack::is_multi_network();
1004
	}
1005
1006
	/**
1007
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1008
	 *
1009
	 * @param  string  $option
1010
	 * @return boolean
1011
	 */
1012
	public function is_multisite( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1013
		return (string) (bool) is_multisite();
1014
	}
1015
1016
	/**
1017
	 * Implemented since there is no core is multi network function
1018
	 * Right now there is no way to tell if we which network is the dominant network on the system
1019
	 *
1020
	 * @since  3.3
1021
	 * @return boolean
1022
	 */
1023
	public static function is_multi_network() {
1024
		global  $wpdb;
1025
1026
		// if we don't have a multi site setup no need to do any more
1027
		if ( ! is_multisite() ) {
1028
			return false;
1029
		}
1030
1031
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1032
		if ( $num_sites > 1 ) {
1033
			return true;
1034
		} else {
1035
			return false;
1036
		}
1037
	}
1038
1039
	/**
1040
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1041
	 * @return null
1042
	 */
1043
	function update_jetpack_main_network_site_option() {
1044
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1045
	}
1046
	/**
1047
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1048
	 *
1049
	 */
1050
	function update_jetpack_network_settings() {
1051
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1052
		// Only sync this info for the main network site.
1053
	}
1054
1055
	/**
1056
	 * Get back if the current site is single user site.
1057
	 *
1058
	 * @return bool
1059
	 */
1060
	public static function is_single_user_site() {
1061
		global $wpdb;
1062
1063 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1064
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1065
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1066
		}
1067
		return 1 === (int) $some_users;
1068
	}
1069
1070
	/**
1071
	 * Returns true if the site has file write access false otherwise.
1072
	 * @return string ( '1' | '0' )
1073
	 **/
1074
	public static function file_system_write_access() {
1075
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1076
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1077
		}
1078
1079
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1080
1081
		$filesystem_method = get_filesystem_method();
1082
		if ( $filesystem_method === 'direct' ) {
1083
			return 1;
1084
		}
1085
1086
		ob_start();
1087
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1088
		ob_end_clean();
1089
		if ( $filesystem_credentials_are_stored ) {
1090
			return 1;
1091
		}
1092
		return 0;
1093
	}
1094
1095
	/**
1096
	 * Finds out if a site is using a version control system.
1097
	 * @return string ( '1' | '0' )
1098
	 **/
1099
	public static function is_version_controlled() {
1100
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1101
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1102
	}
1103
1104
	/**
1105
	 * Determines whether the current theme supports featured images or not.
1106
	 * @return string ( '1' | '0' )
1107
	 */
1108
	public static function featured_images_enabled() {
1109
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1110
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1111
	}
1112
1113
	/**
1114
	 * jetpack_updates is saved in the following schema:
1115
	 *
1116
	 * array (
1117
	 *      'plugins'                       => (int) Number of plugin updates available.
1118
	 *      'themes'                        => (int) Number of theme updates available.
1119
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1120
	 *      'translations'                  => (int) Number of translation updates available.
1121
	 *      'total'                         => (int) Total of all available updates.
1122
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1123
	 * )
1124
	 * @return array
1125
	 */
1126
	public static function get_updates() {
1127
		$update_data = wp_get_update_data();
1128
1129
		// Stores the individual update counts as well as the total count.
1130
		if ( isset( $update_data['counts'] ) ) {
1131
			$updates = $update_data['counts'];
1132
		}
1133
1134
		// If we need to update WordPress core, let's find the latest version number.
1135 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1136
			$cur = get_preferred_from_update_core();
1137
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1138
				$updates['wp_update_version'] = $cur->current;
1139
			}
1140
		}
1141
		return isset( $updates ) ? $updates : array();
1142
	}
1143
1144
	public static function get_update_details() {
1145
		$update_details = array(
1146
			'update_core' => get_site_transient( 'update_core' ),
1147
			'update_plugins' => get_site_transient( 'update_plugins' ),
1148
			'update_themes' => get_site_transient( 'update_themes' ),
1149
		);
1150
		return $update_details;
1151
	}
1152
1153
	public static function refresh_update_data() {
1154
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1155
1156
	}
1157
1158
	public static function refresh_theme_data() {
1159
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1160
	}
1161
1162
	/**
1163
	 * Is Jetpack active?
1164
	 */
1165
	public static function is_active() {
1166
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1167
	}
1168
1169
	/**
1170
	 * Make an API call to WordPress.com for plan status
1171
	 *
1172
	 * @uses Jetpack_Options::get_option()
1173
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1174
	 * @uses update_option()
1175
	 *
1176
	 * @access public
1177
	 * @static
1178
	 *
1179
	 * @return bool True if plan is updated, false if no update
1180
	 */
1181
	public static function refresh_active_plan_from_wpcom() {
1182
		// Make the API request
1183
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1184
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1185
1186
		// Bail if there was an error or malformed response
1187
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1188
			return false;
1189
		}
1190
1191
		// Decode the results
1192
		$results = json_decode( $response['body'], true );
1193
1194
		// Bail if there were no results or plan details returned
1195
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1196
			return false;
1197
		}
1198
1199
		// Store the option and return true if updated
1200
		return update_option( 'jetpack_active_plan', $results['plan'] );
1201
	}
1202
1203
	/**
1204
	 * Get the plan that this Jetpack site is currently using
1205
	 *
1206
	 * @uses get_option()
1207
	 *
1208
	 * @access public
1209
	 * @static
1210
	 *
1211
	 * @return array Active Jetpack plan details
1212
	 */
1213
	public static function get_active_plan() {
1214
		$plan = get_option( 'jetpack_active_plan' );
1215
1216
		// Set the default options
1217
		if ( ! $plan ) {
1218
			$plan = array( 
1219
				'product_slug' => 'jetpack_free', 
1220
				'supports' => array(), 
1221
			);
1222
		}
1223
1224
		// Define what paid modules are supported by personal plans
1225
		$personal_plans = array( 
1226
			'jetpack_personal',
1227
			'jetpack_personal_monthly',
1228
		);
1229
1230
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1231
			$plan['supports'] = array(
1232
				'akismet',
1233
			);
1234
		}
1235
1236
		// Define what paid modules are supported by premium plans
1237
		$premium_plans = array(
1238
			'jetpack_premium',
1239
			'jetpack_premium_monthly',
1240
		);
1241
1242 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1243
			$plan['supports'] = array(
1244
				'videopress',
1245
				'akismet',
1246
				'vaultpress',
1247
			);
1248
		}
1249
1250
		// Define what paid modules are supported by professional plans
1251
		$business_plans = array(
1252
			'jetpack_business',
1253
			'jetpack_business_monthly',
1254
		);
1255
1256 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1257
			$plan['supports'] = array(
1258
				'videopress',
1259
				'akismet',
1260
				'vaultpress',
1261
				'seo-tools',
1262
			);
1263
		}
1264
1265
		// Make sure we have an array here in the event database data is stale
1266
		if ( ! isset( $plan['supports'] ) ) {
1267
			$plan['supports'] = array();
1268
		}
1269
1270
		return $plan;
1271
	}
1272
1273
	/**
1274
	 * Determine whether the active plan supports a particular feature
1275
	 *
1276
	 * @uses Jetpack::get_active_plan()
1277
	 *
1278
	 * @access public
1279
	 * @static
1280
	 *
1281
	 * @return bool True if plan supports feature, false if not
1282
	 */
1283
	public static function active_plan_supports( $feature ) {
1284
		$plan = Jetpack::get_active_plan();
1285
1286
		if ( in_array( $feature, $plan['supports'] ) ) {
1287
			return true;
1288
		}
1289
1290
		return false;
1291
	}
1292
1293
	/**
1294
	 * Is Jetpack in development (offline) mode?
1295
	 */
1296
	public static function is_development_mode() {
1297
		$development_mode = false;
1298
1299
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1300
			$development_mode = JETPACK_DEV_DEBUG;
1301
		}
1302
1303
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1304
			$development_mode = true;
1305
		}
1306
		/**
1307
		 * Filters Jetpack's development mode.
1308
		 *
1309
		 * @see https://jetpack.com/support/development-mode/
1310
		 *
1311
		 * @since 2.2.1
1312
		 *
1313
		 * @param bool $development_mode Is Jetpack's development mode active.
1314
		 */
1315
		return apply_filters( 'jetpack_development_mode', $development_mode );
1316
	}
1317
1318
	/**
1319
	* Get Jetpack development mode notice text and notice class.
1320
	*
1321
	* Mirrors the checks made in Jetpack::is_development_mode
1322
	*
1323
	*/
1324
	public static function show_development_mode_notice() {
1325
		if ( Jetpack::is_development_mode() ) {
1326
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1327
				$notice = sprintf(
1328
					/* translators: %s is a URL */
1329
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1330
					'https://jetpack.com/support/development-mode/'
1331
				);
1332
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1333
				$notice = sprintf(
1334
					/* translators: %s is a URL */
1335
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1336
					'https://jetpack.com/support/development-mode/'
1337
				);
1338
			} else {
1339
				$notice = sprintf(
1340
					/* translators: %s is a URL */
1341
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1342
					'https://jetpack.com/support/development-mode/'
1343
				);
1344
			}
1345
1346
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1347
		}
1348
1349
		// Throw up a notice if using a development version and as for feedback.
1350
		if ( Jetpack::is_development_version() ) {
1351
			/* translators: %s is a URL */
1352
			$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/' );
1353
1354
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1355
		}
1356
		// Throw up a notice if using staging mode
1357
		if ( Jetpack::is_staging_site() ) {
1358
			/* translators: %s is a URL */
1359
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1360
1361
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1362
		}
1363
	}
1364
1365
	/**
1366
	 * Whether Jetpack's version maps to a public release, or a development version.
1367
	 */
1368
	public static function is_development_version() {
1369
		/**
1370
		 * Allows filtering whether this is a development version of Jetpack.
1371
		 *
1372
		 * This filter is especially useful for tests.
1373
		 *
1374
		 * @since 4.3.0
1375
		 *
1376
		 * @param bool $development_version Is this a develoment version of Jetpack?
1377
		 */
1378
		return (bool) apply_filters(
1379
			'jetpack_development_version',
1380
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1381
		);
1382
	}
1383
1384
	/**
1385
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1386
	 */
1387
	public static function is_user_connected( $user_id = false ) {
1388
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1389
		if ( ! $user_id ) {
1390
			return false;
1391
		}
1392
1393
		return (bool) Jetpack_Data::get_access_token( $user_id );
1394
	}
1395
1396
	/**
1397
	 * Get the wpcom user data of the current|specified connected user.
1398
	 */
1399
	public static function get_connected_user_data( $user_id = null ) {
1400
		if ( ! $user_id ) {
1401
			$user_id = get_current_user_id();
1402
		}
1403
1404
		$transient_key = "jetpack_connected_user_data_$user_id";
1405
1406
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1407
			return $cached_user_data;
1408
		}
1409
1410
		Jetpack::load_xml_rpc_client();
1411
		$xml = new Jetpack_IXR_Client( array(
1412
			'user_id' => $user_id,
1413
		) );
1414
		$xml->query( 'wpcom.getUser' );
1415
		if ( ! $xml->isError() ) {
1416
			$user_data = $xml->getResponse();
1417
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1418
			return $user_data;
1419
		}
1420
1421
		return false;
1422
	}
1423
1424
	/**
1425
	 * Get the wpcom email of the current|specified connected user.
1426
	 */
1427 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1428
		if ( ! $user_id ) {
1429
			$user_id = get_current_user_id();
1430
		}
1431
		Jetpack::load_xml_rpc_client();
1432
		$xml = new Jetpack_IXR_Client( array(
1433
			'user_id' => $user_id,
1434
		) );
1435
		$xml->query( 'wpcom.getUserEmail' );
1436
		if ( ! $xml->isError() ) {
1437
			return $xml->getResponse();
1438
		}
1439
		return false;
1440
	}
1441
1442
	/**
1443
	 * Get the wpcom email of the master user.
1444
	 */
1445
	public static function get_master_user_email() {
1446
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1447
		if ( $master_user_id ) {
1448
			return self::get_connected_user_email( $master_user_id );
1449
		}
1450
		return '';
1451
	}
1452
1453
	function current_user_is_connection_owner() {
1454
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1455
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1456
	}
1457
1458
	/**
1459
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1460
	 */
1461
	function extra_oembed_providers() {
1462
		// Cloudup: https://dev.cloudup.com/#oembed
1463
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1464
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1465
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1466
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1467
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1468
	}
1469
1470
	/**
1471
	 * Synchronize connected user role changes
1472
	 */
1473
	function user_role_change( $user_id ) {
1474
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1475
		Jetpack_Sync_Users::user_role_change( $user_id );
1476
	}
1477
1478
	/**
1479
	 * Loads the currently active modules.
1480
	 */
1481
	public static function load_modules() {
1482
		if ( ! self::is_active() && !self::is_development_mode() ) {
1483
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1484
				return;
1485
			}
1486
		}
1487
1488
		$version = Jetpack_Options::get_option( 'version' );
1489 View Code Duplication
		if ( ! $version ) {
1490
			$version = $old_version = JETPACK__VERSION . ':' . time();
1491
			/** This action is documented in class.jetpack.php */
1492
			do_action( 'updating_jetpack_version', $version, false );
1493
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1494
		}
1495
		list( $version ) = explode( ':', $version );
1496
1497
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1498
1499
		$modules_data = array();
1500
1501
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1502
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1503
			$updated_modules = array();
1504
			foreach ( $modules as $module ) {
1505
				$modules_data[ $module ] = Jetpack::get_module( $module );
1506
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1507
					continue;
1508
				}
1509
1510
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1511
					continue;
1512
				}
1513
1514
				$updated_modules[] = $module;
1515
			}
1516
1517
			$modules = array_diff( $modules, $updated_modules );
1518
		}
1519
1520
		$is_development_mode = Jetpack::is_development_mode();
1521
1522
		foreach ( $modules as $index => $module ) {
1523
			// If we're in dev mode, disable modules requiring a connection
1524
			if ( $is_development_mode ) {
1525
				// Prime the pump if we need to
1526
				if ( empty( $modules_data[ $module ] ) ) {
1527
					$modules_data[ $module ] = Jetpack::get_module( $module );
1528
				}
1529
				// If the module requires a connection, but we're in local mode, don't include it.
1530
				if ( $modules_data[ $module ]['requires_connection'] ) {
1531
					continue;
1532
				}
1533
			}
1534
1535
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1536
				continue;
1537
			}
1538
1539
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1540
				unset( $modules[ $index ] );
1541
				self::update_active_modules( array_values( $modules ) );
1542
				continue;
1543
			}
1544
1545
			/**
1546
			 * Fires when a specific module is loaded.
1547
			 * The dynamic part of the hook, $module, is the module slug.
1548
			 *
1549
			 * @since 1.1.0
1550
			 */
1551
			do_action( 'jetpack_module_loaded_' . $module );
1552
		}
1553
1554
		/**
1555
		 * Fires when all the modules are loaded.
1556
		 *
1557
		 * @since 1.1.0
1558
		 */
1559
		do_action( 'jetpack_modules_loaded' );
1560
1561
		// 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.
1562
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1563
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1564
	}
1565
1566
	/**
1567
	 * Check if Jetpack's REST API compat file should be included
1568
	 * @action plugins_loaded
1569
	 * @return null
1570
	 */
1571
	public function check_rest_api_compat() {
1572
		/**
1573
		 * Filters the list of REST API compat files to be included.
1574
		 *
1575
		 * @since 2.2.5
1576
		 *
1577
		 * @param array $args Array of REST API compat files to include.
1578
		 */
1579
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1580
1581
		if ( function_exists( 'bbpress' ) )
1582
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1583
1584
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1585
			require_once $_jetpack_rest_api_compat_include;
1586
	}
1587
1588
	/**
1589
	 * Gets all plugins currently active in values, regardless of whether they're
1590
	 * traditionally activated or network activated.
1591
	 *
1592
	 * @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...
1593
	 */
1594
	public static function get_active_plugins() {
1595
		$active_plugins = (array) get_option( 'active_plugins', array() );
1596
1597
		if ( is_multisite() ) {
1598
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1599
			// whereas active_plugins stores them in the values.
1600
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1601
			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...
1602
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1603
			}
1604
		}
1605
1606
		sort( $active_plugins );
1607
1608
		return array_unique( $active_plugins );
1609
	}
1610
1611
	/**
1612
	 * Gets and parses additional plugin data to send with the heartbeat data
1613
	 *
1614
	 * @since 3.8.1
1615
	 *
1616
	 * @return array Array of plugin data
1617
	 */
1618
	public static function get_parsed_plugin_data() {
1619
		if ( ! function_exists( 'get_plugins' ) ) {
1620
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1621
		}
1622
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1623
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1624
		$active_plugins = Jetpack::get_active_plugins();
1625
1626
		$plugins = array();
1627
		foreach ( $all_plugins as $path => $plugin_data ) {
1628
			$plugins[ $path ] = array(
1629
					'is_active' => in_array( $path, $active_plugins ),
1630
					'file'      => $path,
1631
					'name'      => $plugin_data['Name'],
1632
					'version'   => $plugin_data['Version'],
1633
					'author'    => $plugin_data['Author'],
1634
			);
1635
		}
1636
1637
		return $plugins;
1638
	}
1639
1640
	/**
1641
	 * Gets and parses theme data to send with the heartbeat data
1642
	 *
1643
	 * @since 3.8.1
1644
	 *
1645
	 * @return array Array of theme data
1646
	 */
1647
	public static function get_parsed_theme_data() {
1648
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1649
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1650
1651
		$themes = array();
1652
		foreach ( $all_themes as $slug => $theme_data ) {
1653
			$theme_headers = array();
1654
			foreach ( $header_keys as $header_key ) {
1655
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1656
			}
1657
1658
			$themes[ $slug ] = array(
1659
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1660
					'slug' => $slug,
1661
					'theme_root' => $theme_data->get_theme_root_uri(),
1662
					'parent' => $theme_data->parent(),
1663
					'headers' => $theme_headers
1664
			);
1665
		}
1666
1667
		return $themes;
1668
	}
1669
1670
	/**
1671
	 * Checks whether a specific plugin is active.
1672
	 *
1673
	 * We don't want to store these in a static variable, in case
1674
	 * there are switch_to_blog() calls involved.
1675
	 */
1676
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1677
		return in_array( $plugin, self::get_active_plugins() );
1678
	}
1679
1680
	/**
1681
	 * Check if Jetpack's Open Graph tags should be used.
1682
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1683
	 *
1684
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1685
	 * @action plugins_loaded
1686
	 * @return null
1687
	 */
1688
	public function check_open_graph() {
1689
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1690
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1691
		}
1692
1693
		$active_plugins = self::get_active_plugins();
1694
1695
		if ( ! empty( $active_plugins ) ) {
1696
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1697
				if ( in_array( $plugin, $active_plugins ) ) {
1698
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1699
					break;
1700
				}
1701
			}
1702
		}
1703
1704
		/**
1705
		 * Allow the addition of Open Graph Meta Tags to all pages.
1706
		 *
1707
		 * @since 2.0.3
1708
		 *
1709
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1710
		 */
1711
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1712
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1713
		}
1714
	}
1715
1716
	/**
1717
	 * Check if Jetpack's Twitter tags should be used.
1718
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1719
	 *
1720
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1721
	 * @action plugins_loaded
1722
	 * @return null
1723
	 */
1724
	public function check_twitter_tags() {
1725
1726
		$active_plugins = self::get_active_plugins();
1727
1728
		if ( ! empty( $active_plugins ) ) {
1729
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1730
				if ( in_array( $plugin, $active_plugins ) ) {
1731
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1732
					break;
1733
				}
1734
			}
1735
		}
1736
1737
		/**
1738
		 * Allow Twitter Card Meta tags to be disabled.
1739
		 *
1740
		 * @since 2.6.0
1741
		 *
1742
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1743
		 */
1744
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1745
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1746
		}
1747
	}
1748
1749
	/**
1750
	 * Allows plugins to submit security reports.
1751
 	 *
1752
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1753
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1754
	 * @param array   $args         See definitions above
1755
	 */
1756
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $plugin_file is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1757
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1758
	}
1759
1760
/* Jetpack Options API */
1761
1762
	public static function get_option_names( $type = 'compact' ) {
1763
		return Jetpack_Options::get_option_names( $type );
1764
	}
1765
1766
	/**
1767
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1768
 	 *
1769
	 * @param string $name    Option name
1770
	 * @param mixed  $default (optional)
1771
	 */
1772
	public static function get_option( $name, $default = false ) {
1773
		return Jetpack_Options::get_option( $name, $default );
1774
	}
1775
1776
	/**
1777
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1778
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1779
	* $name must be a registered option name.
1780
	*/
1781
	public static function create_nonce( $name ) {
1782
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1783
1784
		Jetpack_Options::update_option( $name, $secret );
1785
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
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...
1786
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1787
			return new Jetpack_Error( 'missing_secrets' );
1788
1789
		return array(
1790
			'secret_1' => $secret_1,
1791
			'secret_2' => $secret_2,
1792
			'eol'      => $eol,
1793
		);
1794
	}
1795
1796
	/**
1797
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1798
 	 *
1799
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1800
	 * @param string $name  Option name
1801
	 * @param mixed  $value Option value
1802
	 */
1803
	public static function update_option( $name, $value ) {
1804
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1805
		return Jetpack_Options::update_option( $name, $value );
1806
	}
1807
1808
	/**
1809
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1810
 	 *
1811
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1812
	 * @param array $array array( option name => option value, ... )
1813
	 */
1814
	public static function update_options( $array ) {
1815
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1816
		return Jetpack_Options::update_options( $array );
1817
	}
1818
1819
	/**
1820
	 * Deletes the given option.  May be passed multiple option names as an array.
1821
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1822
	 *
1823
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1824
	 * @param string|array $names
1825
	 */
1826
	public static function delete_option( $names ) {
1827
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1828
		return Jetpack_Options::delete_option( $names );
1829
	}
1830
1831
	/**
1832
	 * Enters a user token into the user_tokens option
1833
	 *
1834
	 * @param int $user_id
1835
	 * @param string $token
1836
	 * return bool
1837
	 */
1838
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1839
		// not designed for concurrent updates
1840
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1841
		if ( ! is_array( $user_tokens ) )
1842
			$user_tokens = array();
1843
		$user_tokens[$user_id] = $token;
1844
		if ( $is_master_user ) {
1845
			$master_user = $user_id;
1846
			$options     = compact( 'user_tokens', 'master_user' );
1847
		} else {
1848
			$options = compact( 'user_tokens' );
1849
		}
1850
		return Jetpack_Options::update_options( $options );
1851
	}
1852
1853
	/**
1854
	 * Returns an array of all PHP files in the specified absolute path.
1855
	 * Equivalent to glob( "$absolute_path/*.php" ).
1856
	 *
1857
	 * @param string $absolute_path The absolute path of the directory to search.
1858
	 * @return array Array of absolute paths to the PHP files.
1859
	 */
1860
	public static function glob_php( $absolute_path ) {
1861
		if ( function_exists( 'glob' ) ) {
1862
			return glob( "$absolute_path/*.php" );
1863
		}
1864
1865
		$absolute_path = untrailingslashit( $absolute_path );
1866
		$files = array();
1867
		if ( ! $dir = @opendir( $absolute_path ) ) {
1868
			return $files;
1869
		}
1870
1871
		while ( false !== $file = readdir( $dir ) ) {
1872
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1873
				continue;
1874
			}
1875
1876
			$file = "$absolute_path/$file";
1877
1878
			if ( ! is_file( $file ) ) {
1879
				continue;
1880
			}
1881
1882
			$files[] = $file;
1883
		}
1884
1885
		closedir( $dir );
1886
1887
		return $files;
1888
	}
1889
1890
	public static function activate_new_modules( $redirect = false ) {
1891
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1892
			return;
1893
		}
1894
1895
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1896 View Code Duplication
		if ( ! $jetpack_old_version ) {
1897
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1898
			/** This action is documented in class.jetpack.php */
1899
			do_action( 'updating_jetpack_version', $version, false );
1900
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1901
		}
1902
1903
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1904
1905
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1906
			return;
1907
		}
1908
1909
		$active_modules     = Jetpack::get_active_modules();
1910
		$reactivate_modules = array();
1911
		foreach ( $active_modules as $active_module ) {
1912
			$module = Jetpack::get_module( $active_module );
1913
			if ( ! isset( $module['changed'] ) ) {
1914
				continue;
1915
			}
1916
1917
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1918
				continue;
1919
			}
1920
1921
			$reactivate_modules[] = $active_module;
1922
			Jetpack::deactivate_module( $active_module );
1923
		}
1924
1925
		$new_version = JETPACK__VERSION . ':' . time();
1926
		/** This action is documented in class.jetpack.php */
1927
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1928
		Jetpack_Options::update_options(
1929
			array(
1930
				'version'     => $new_version,
1931
				'old_version' => $jetpack_old_version,
1932
			)
1933
		);
1934
1935
		Jetpack::state( 'message', 'modules_activated' );
1936
		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...
1937
1938
		if ( $redirect ) {
1939
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1940
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1941
				$page = $_GET['page'];
1942
			}
1943
1944
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1945
			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...
1946
		}
1947
	}
1948
1949
	/**
1950
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1951
	 * Make sure to tuck away module "library" files in a sub-directory.
1952
	 */
1953
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1954
		static $modules = null;
1955
1956
		if ( ! isset( $modules ) ) {
1957
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1958
			// Use the cache if we're on the front-end and it's available...
1959
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1960
				$modules = $available_modules_option[ JETPACK__VERSION ];
1961
			} else {
1962
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1963
1964
				$modules = array();
1965
1966
				foreach ( $files as $file ) {
1967
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1968
						continue;
1969
					}
1970
1971
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1972
				}
1973
1974
				Jetpack_Options::update_option( 'available_modules', array(
1975
					JETPACK__VERSION => $modules,
1976
				) );
1977
			}
1978
		}
1979
1980
		/**
1981
		 * Filters the array of modules available to be activated.
1982
		 *
1983
		 * @since 2.4.0
1984
		 *
1985
		 * @param array $modules Array of available modules.
1986
		 * @param string $min_version Minimum version number required to use modules.
1987
		 * @param string $max_version Maximum version number required to use modules.
1988
		 */
1989
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1990
1991
		if ( ! $min_version && ! $max_version ) {
1992
			return array_keys( $mods );
1993
		}
1994
1995
		$r = array();
1996
		foreach ( $mods as $slug => $introduced ) {
1997
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1998
				continue;
1999
			}
2000
2001
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2002
				continue;
2003
			}
2004
2005
			$r[] = $slug;
2006
		}
2007
2008
		return $r;
2009
	}
2010
2011
	/**
2012
	 * Default modules loaded on activation.
2013
	 */
2014
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2015
		$return = array();
2016
2017
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2018
			$module_data = Jetpack::get_module( $module );
2019
2020
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2021
				case 'yes' :
2022
					$return[] = $module;
2023
					break;
2024
				case 'public' :
2025
					if ( Jetpack_Options::get_option( 'public' ) ) {
2026
						$return[] = $module;
2027
					}
2028
					break;
2029
				case 'no' :
2030
				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...
2031
					break;
2032
			}
2033
		}
2034
		/**
2035
		 * Filters the array of default modules.
2036
		 *
2037
		 * @since 2.5.0
2038
		 *
2039
		 * @param array $return Array of default modules.
2040
		 * @param string $min_version Minimum version number required to use modules.
2041
		 * @param string $max_version Maximum version number required to use modules.
2042
		 */
2043
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2044
	}
2045
2046
	/**
2047
	 * Checks activated modules during auto-activation to determine
2048
	 * if any of those modules are being deprecated.  If so, close
2049
	 * them out, and add any replacement modules.
2050
	 *
2051
	 * Runs at priority 99 by default.
2052
	 *
2053
	 * This is run late, so that it can still activate a module if
2054
	 * the new module is a replacement for another that the user
2055
	 * currently has active, even if something at the normal priority
2056
	 * would kibosh everything.
2057
	 *
2058
	 * @since 2.6
2059
	 * @uses jetpack_get_default_modules filter
2060
	 * @param array $modules
2061
	 * @return array
2062
	 */
2063
	function handle_deprecated_modules( $modules ) {
2064
		$deprecated_modules = array(
2065
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2066
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2067
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2068
		);
2069
2070
		// Don't activate SSO if they never completed activating WPCC.
2071
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2072
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2073
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2074
				$deprecated_modules['wpcc'] = null;
2075
			}
2076
		}
2077
2078
		foreach ( $deprecated_modules as $module => $replacement ) {
2079
			if ( Jetpack::is_module_active( $module ) ) {
2080
				self::deactivate_module( $module );
2081
				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...
2082
					$modules[] = $replacement;
2083
				}
2084
			}
2085
		}
2086
2087
		return array_unique( $modules );
2088
	}
2089
2090
	/**
2091
	 * Checks activated plugins during auto-activation to determine
2092
	 * if any of those plugins are in the list with a corresponding module
2093
	 * that is not compatible with the plugin. The module will not be allowed
2094
	 * to auto-activate.
2095
	 *
2096
	 * @since 2.6
2097
	 * @uses jetpack_get_default_modules filter
2098
	 * @param array $modules
2099
	 * @return array
2100
	 */
2101
	function filter_default_modules( $modules ) {
2102
2103
		$active_plugins = self::get_active_plugins();
2104
2105
		if ( ! empty( $active_plugins ) ) {
2106
2107
			// For each module we'd like to auto-activate...
2108
			foreach ( $modules as $key => $module ) {
2109
				// If there are potential conflicts for it...
2110
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2111
					// For each potential conflict...
2112
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2113
						// If that conflicting plugin is active...
2114
						if ( in_array( $plugin, $active_plugins ) ) {
2115
							// Remove that item from being auto-activated.
2116
							unset( $modules[ $key ] );
2117
						}
2118
					}
2119
				}
2120
			}
2121
		}
2122
2123
		return $modules;
2124
	}
2125
2126
	/**
2127
	 * Extract a module's slug from its full path.
2128
	 */
2129
	public static function get_module_slug( $file ) {
2130
		return str_replace( '.php', '', basename( $file ) );
2131
	}
2132
2133
	/**
2134
	 * Generate a module's path from its slug.
2135
	 */
2136
	public static function get_module_path( $slug ) {
2137
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2138
	}
2139
2140
	/**
2141
	 * Load module data from module file. Headers differ from WordPress
2142
	 * plugin headers to avoid them being identified as standalone
2143
	 * plugins on the WordPress plugins page.
2144
	 */
2145
	public static function get_module( $module ) {
2146
		$headers = array(
2147
			'name'                      => 'Module Name',
2148
			'description'               => 'Module Description',
2149
			'jumpstart_desc'            => 'Jumpstart Description',
2150
			'sort'                      => 'Sort Order',
2151
			'recommendation_order'      => 'Recommendation Order',
2152
			'introduced'                => 'First Introduced',
2153
			'changed'                   => 'Major Changes In',
2154
			'deactivate'                => 'Deactivate',
2155
			'free'                      => 'Free',
2156
			'requires_connection'       => 'Requires Connection',
2157
			'auto_activate'             => 'Auto Activate',
2158
			'module_tags'               => 'Module Tags',
2159
			'feature'                   => 'Feature',
2160
			'additional_search_queries' => 'Additional Search Queries',
2161
		);
2162
2163
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2164
2165
		$mod = Jetpack::get_file_data( $file, $headers );
2166
		if ( empty( $mod['name'] ) ) {
2167
			return false;
2168
		}
2169
2170
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2171
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2172
		$mod['deactivate']              = empty( $mod['deactivate'] );
2173
		$mod['free']                    = empty( $mod['free'] );
2174
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2175
2176
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2177
			$mod['auto_activate'] = 'No';
2178
		} else {
2179
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2180
		}
2181
2182
		if ( $mod['module_tags'] ) {
2183
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2184
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2185
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2186
		} else {
2187
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2188
		}
2189
2190
		if ( $mod['feature'] ) {
2191
			$mod['feature'] = explode( ',', $mod['feature'] );
2192
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2193
		} else {
2194
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2195
		}
2196
2197
		/**
2198
		 * Filters the feature array on a module.
2199
		 *
2200
		 * This filter allows you to control where each module is filtered: Recommended,
2201
		 * Jumpstart, and the default "Other" listing.
2202
		 *
2203
		 * @since 3.5.0
2204
		 *
2205
		 * @param array   $mod['feature'] The areas to feature this module:
2206
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2207
		 *     'Recommended' shows on the main Jetpack admin screen.
2208
		 *     'Other' should be the default if no other value is in the array.
2209
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2210
		 * @param array   $mod All the currently assembled module data.
2211
		 */
2212
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2213
2214
		/**
2215
		 * Filter the returned data about a module.
2216
		 *
2217
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2218
		 * so please be careful.
2219
		 *
2220
		 * @since 3.6.0
2221
		 *
2222
		 * @param array   $mod    The details of the requested module.
2223
		 * @param string  $module The slug of the module, e.g. sharedaddy
2224
		 * @param string  $file   The path to the module source file.
2225
		 */
2226
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2227
	}
2228
2229
	/**
2230
	 * Like core's get_file_data implementation, but caches the result.
2231
	 */
2232
	public static function get_file_data( $file, $headers ) {
2233
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2234
		$file_name = basename( $file );
2235
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2236
		$key              = md5( $file_name . serialize( $headers ) );
2237
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2238
2239
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2240
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2241
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2242
		}
2243
2244
		$data = get_file_data( $file, $headers );
2245
2246
		// Strip out any old Jetpack versions that are cluttering the option.
2247
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2248
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2249
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2250
2251
		return $data;
2252
	}
2253
2254
	/**
2255
	 * Return translated module tag.
2256
	 *
2257
	 * @param string $tag Tag as it appears in each module heading.
2258
	 *
2259
	 * @return mixed
2260
	 */
2261
	public static function translate_module_tag( $tag ) {
2262
		return jetpack_get_module_i18n_tag( $tag );
2263
	}
2264
2265
	/**
2266
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2267
	 *
2268
	 * @since 3.9.2
2269
	 *
2270
	 * @param array $modules
2271
	 *
2272
	 * @return string|void
2273
	 */
2274
	public static function get_translated_modules( $modules ) {
2275
		foreach ( $modules as $index => $module ) {
2276
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2277
			if ( isset( $module['name'] ) ) {
2278
				$modules[ $index ]['name'] = $i18n_module['name'];
2279
			}
2280
			if ( isset( $module['description'] ) ) {
2281
				$modules[ $index ]['description'] = $i18n_module['description'];
2282
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2283
			}
2284
		}
2285
		return $modules;
2286
	}
2287
2288
	/**
2289
	 * Get a list of activated modules as an array of module slugs.
2290
	 */
2291
	public static function get_active_modules() {
2292
		$active = Jetpack_Options::get_option( 'active_modules' );
2293
		
2294
		if ( ! is_array( $active ) ) {
2295
			$active = array();
2296
		}
2297
2298
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2299
			$active[] = 'vaultpress';
2300
		} else {
2301
			$active = array_diff( $active, array( 'vaultpress' ) );
2302
		}
2303
2304
		//If protect is active on the main site of a multisite, it should be active on all sites.
2305
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2306
			$active[] = 'protect';
2307
		}
2308
2309
		return array_unique( $active );
2310
	}
2311
2312
	/**
2313
	 * Check whether or not a Jetpack module is active.
2314
	 *
2315
	 * @param string $module The slug of a Jetpack module.
2316
	 * @return bool
2317
	 *
2318
	 * @static
2319
	 */
2320
	public static function is_module_active( $module ) {
2321
		return in_array( $module, self::get_active_modules() );
2322
	}
2323
2324
	public static function is_module( $module ) {
2325
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2326
	}
2327
2328
	/**
2329
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2330
	 *
2331
	 * @param bool $catch True to start catching, False to stop.
2332
	 *
2333
	 * @static
2334
	 */
2335
	public static function catch_errors( $catch ) {
2336
		static $display_errors, $error_reporting;
2337
2338
		if ( $catch ) {
2339
			$display_errors  = @ini_set( 'display_errors', 1 );
2340
			$error_reporting = @error_reporting( E_ALL );
2341
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2342
		} else {
2343
			@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...
2344
			@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...
2345
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2346
		}
2347
	}
2348
2349
	/**
2350
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2351
	 */
2352
	public static function catch_errors_on_shutdown() {
2353
		Jetpack::state( 'php_errors', ob_get_clean() );
2354
	}
2355
2356
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2357
		$jetpack = Jetpack::init();
2358
2359
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2360
		$modules = array_merge( $other_modules, $modules );
2361
2362
		// Look for standalone plugins and disable if active.
2363
2364
		$to_deactivate = array();
2365
		foreach ( $modules as $module ) {
2366
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2367
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2368
			}
2369
		}
2370
2371
		$deactivated = array();
2372
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2373
			list( $probable_file, $probable_title ) = $deactivate_me;
2374
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2375
				$deactivated[] = $module;
2376
			}
2377
		}
2378
2379
		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...
2380
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2381
2382
			$url = add_query_arg(
2383
				array(
2384
					'action'   => 'activate_default_modules',
2385
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2386
				),
2387
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2388
			);
2389
			wp_safe_redirect( $url );
2390
			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...
2391
		}
2392
2393
		/**
2394
		 * Fires before default modules are activated.
2395
		 *
2396
		 * @since 1.9.0
2397
		 *
2398
		 * @param string $min_version Minimum version number required to use modules.
2399
		 * @param string $max_version Maximum version number required to use modules.
2400
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2401
		 */
2402
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2403
2404
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2405
		Jetpack::restate();
2406
		Jetpack::catch_errors( true );
2407
2408
		$active = Jetpack::get_active_modules();
2409
2410
		foreach ( $modules as $module ) {
2411
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2412
				$active[] = $module;
2413
				self::update_active_modules( $active );
2414
				continue;
2415
			}
2416
2417
			if ( in_array( $module, $active ) ) {
2418
				$module_info = Jetpack::get_module( $module );
2419
				if ( ! $module_info['deactivate'] ) {
2420
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2421 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2422
						$active_state = explode( ',', $active_state );
2423
					} else {
2424
						$active_state = array();
2425
					}
2426
					$active_state[] = $module;
2427
					Jetpack::state( $state, implode( ',', $active_state ) );
2428
				}
2429
				continue;
2430
			}
2431
2432
			$file = Jetpack::get_module_path( $module );
2433
			if ( ! file_exists( $file ) ) {
2434
				continue;
2435
			}
2436
2437
			// we'll override this later if the plugin can be included without fatal error
2438
			if ( $redirect ) {
2439
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2440
			}
2441
			Jetpack::state( 'error', 'module_activation_failed' );
2442
			Jetpack::state( 'module', $module );
2443
			ob_start();
2444
			require $file;
2445
2446
			$active[] = $module;
2447
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2448 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2449
				$active_state = explode( ',', $active_state );
2450
			} else {
2451
				$active_state = array();
2452
			}
2453
			$active_state[] = $module;
2454
			Jetpack::state( $state, implode( ',', $active_state ) );
2455
			Jetpack::update_active_modules( $active );
2456
2457
			ob_end_clean();
2458
		}
2459
		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...
2460
		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...
2461
		Jetpack::catch_errors( false );
2462
		/**
2463
		 * Fires when default modules are activated.
2464
		 *
2465
		 * @since 1.9.0
2466
		 *
2467
		 * @param string $min_version Minimum version number required to use modules.
2468
		 * @param string $max_version Maximum version number required to use modules.
2469
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2470
		 */
2471
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2472
	}
2473
2474
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2475
		/**
2476
		 * Fires before a module is activated.
2477
		 *
2478
		 * @since 2.6.0
2479
		 *
2480
		 * @param string $module Module slug.
2481
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2482
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2483
		 */
2484
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2485
2486
		$jetpack = Jetpack::init();
2487
2488
		if ( ! strlen( $module ) )
2489
			return false;
2490
2491
		if ( ! Jetpack::is_module( $module ) )
2492
			return false;
2493
2494
		// If it's already active, then don't do it again
2495
		$active = Jetpack::get_active_modules();
2496
		foreach ( $active as $act ) {
2497
			if ( $act == $module )
2498
				return true;
2499
		}
2500
2501
		$module_data = Jetpack::get_module( $module );
2502
2503
		if ( ! Jetpack::is_active() ) {
2504
			if ( !Jetpack::is_development_mode() )
2505
				return false;
2506
2507
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2508
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2509
				return false;
2510
		}
2511
2512
		// Check and see if the old plugin is active
2513
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2514
			// Deactivate the old plugin
2515
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2516
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2517
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2518
				Jetpack::state( 'deactivated_plugins', $module );
2519
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2520
				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...
2521
			}
2522
		}
2523
2524
		// Protect won't work with mis-configured IPs
2525
		if ( 'protect' === $module ) {
2526
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2527
			if ( ! jetpack_protect_get_ip() ) {
2528
				error_log( 'hello' );
2529
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2530
				return false;
2531
			}
2532
		}
2533
2534
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2535
		Jetpack::state( 'module', $module );
2536
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2537
2538
		Jetpack::catch_errors( true );
2539
		ob_start();
2540
		require Jetpack::get_module_path( $module );
2541
		/** This action is documented in class.jetpack.php */
2542
		do_action( 'jetpack_activate_module', $module );
2543
		$active[] = $module;
2544
		Jetpack::update_active_modules( $active );
2545
2546
		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...
2547
		ob_end_clean();
2548
		Jetpack::catch_errors( false );
2549
2550
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2551 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2552
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2553
2554
			//Jump start is being dismissed send data to MC Stats
2555
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2556
2557
			$jetpack->do_stats( 'server_side' );
2558
		}
2559
2560
		if ( $redirect ) {
2561
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2562
		}
2563
		if ( $exit ) {
2564
			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...
2565
		}
2566
		return true;
2567
	}
2568
2569
	function activate_module_actions( $module ) {
0 ignored issues
show
Unused Code introduced by
The parameter $module is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2570
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2571
	}
2572
2573
	public static function deactivate_module( $module ) {
2574
		/**
2575
		 * Fires when a module is deactivated.
2576
		 *
2577
		 * @since 1.9.0
2578
		 *
2579
		 * @param string $module Module slug.
2580
		 */
2581
		do_action( 'jetpack_pre_deactivate_module', $module );
2582
2583
		$jetpack = Jetpack::init();
2584
2585
		$active = Jetpack::get_active_modules();
2586
		$new    = array_filter( array_diff( $active, (array) $module ) );
2587
2588
		// A flag for Jump Start so it's not shown again.
2589 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2590
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2591
2592
			//Jump start is being dismissed send data to MC Stats
2593
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2594
2595
			$jetpack->do_stats( 'server_side' );
2596
		}
2597
2598
		return self::update_active_modules( $new );
2599
	}
2600
2601
	public static function enable_module_configurable( $module ) {
2602
		$module = Jetpack::get_module_slug( $module );
2603
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2604
	}
2605
2606
	public static function module_configuration_url( $module ) {
2607
		$module = Jetpack::get_module_slug( $module );
2608
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2609
	}
2610
2611
	public static function module_configuration_load( $module, $method ) {
2612
		$module = Jetpack::get_module_slug( $module );
2613
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2614
	}
2615
2616
	public static function module_configuration_head( $module, $method ) {
2617
		$module = Jetpack::get_module_slug( $module );
2618
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2619
	}
2620
2621
	public static function module_configuration_screen( $module, $method ) {
2622
		$module = Jetpack::get_module_slug( $module );
2623
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2624
	}
2625
2626
	public static function module_configuration_activation_screen( $module, $method ) {
2627
		$module = Jetpack::get_module_slug( $module );
2628
		add_action( 'display_activate_module_setting_' . $module, $method );
2629
	}
2630
2631
/* Installation */
2632
2633
	public static function bail_on_activation( $message, $deactivate = true ) {
2634
?>
2635
<!doctype html>
2636
<html>
2637
<head>
2638
<meta charset="<?php bloginfo( 'charset' ); ?>">
2639
<style>
2640
* {
2641
	text-align: center;
2642
	margin: 0;
2643
	padding: 0;
2644
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2645
}
2646
p {
2647
	margin-top: 1em;
2648
	font-size: 18px;
2649
}
2650
</style>
2651
<body>
2652
<p><?php echo esc_html( $message ); ?></p>
2653
</body>
2654
</html>
2655
<?php
2656
		if ( $deactivate ) {
2657
			$plugins = get_option( 'active_plugins' );
2658
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2659
			$update  = false;
2660
			foreach ( $plugins as $i => $plugin ) {
2661
				if ( $plugin === $jetpack ) {
2662
					$plugins[$i] = false;
2663
					$update = true;
2664
				}
2665
			}
2666
2667
			if ( $update ) {
2668
				update_option( 'active_plugins', array_filter( $plugins ) );
2669
			}
2670
		}
2671
		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...
2672
	}
2673
2674
	/**
2675
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2676
	 * @static
2677
	 */
2678
	public static function plugin_activation( $network_wide ) {
2679
		Jetpack_Options::update_option( 'activated', 1 );
2680
2681
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2682
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2683
		}
2684
2685
		if ( $network_wide )
2686
			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...
2687
2688
		Jetpack::plugin_initialize();
2689
	}
2690
	/**
2691
	 * Runs before bumping version numbers up to a new version
2692
	 * @param  (string) $version    Version:timestamp
2693
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2694
	 * @return null              [description]
2695
	 */
2696
	public static function do_version_bump( $version, $old_version ) {
2697
2698
		if ( ! $old_version ) { // For new sites
2699
			// Setting up jetpack manage
2700
			Jetpack::activate_manage();
2701
		}
2702
	}
2703
2704
	/**
2705
	 * Sets the internal version number and activation state.
2706
	 * @static
2707
	 */
2708
	public static function plugin_initialize() {
2709
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2710
			Jetpack_Options::update_option( 'activated', 2 );
2711
		}
2712
2713 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2714
			$version = $old_version = JETPACK__VERSION . ':' . time();
2715
			/** This action is documented in class.jetpack.php */
2716
			do_action( 'updating_jetpack_version', $version, false );
2717
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2718
		}
2719
2720
		Jetpack::load_modules();
2721
2722
		Jetpack_Options::delete_option( 'do_activate' );
2723
	}
2724
2725
	/**
2726
	 * Removes all connection options
2727
	 * @static
2728
	 */
2729
	public static function plugin_deactivation( ) {
2730
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2731
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2732
			Jetpack_Network::init()->deactivate();
2733
		} else {
2734
			Jetpack::disconnect( false );
2735
			//Jetpack_Heartbeat::init()->deactivate();
2736
		}
2737
	}
2738
2739
	/**
2740
	 * Disconnects from the Jetpack servers.
2741
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2742
	 * @static
2743
	 */
2744
	public static function disconnect( $update_activated_state = true ) {
2745
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2746
		Jetpack::clean_nonces( true );
2747
2748
		// If the site is in an IDC because sync is not allowed,
2749
		// let's make sure to not disconnect the production site.
2750
		if ( ! self::validate_sync_error_idc_option() ) {
2751
			Jetpack::load_xml_rpc_client();
2752
			$xml = new Jetpack_IXR_Client();
2753
			$xml->query( 'jetpack.deregister' );
2754
		}
2755
2756
		Jetpack_Options::delete_option(
2757
			array(
2758
				'register',
2759
				'blog_token',
2760
				'user_token',
2761
				'user_tokens',
2762
				'master_user',
2763
				'time_diff',
2764
				'fallback_no_verify_ssl_certs',
2765
			)
2766
		);
2767
2768
		Jetpack_IDC::clear_all_idc_options();
2769
2770
		if ( $update_activated_state ) {
2771
			Jetpack_Options::update_option( 'activated', 4 );
2772
		}
2773
2774
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2775
			// Check then record unique disconnection if site has never been disconnected previously
2776
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2777
				$jetpack_unique_connection['disconnected'] = 1;
2778
			} else {
2779
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2780
					//track unique disconnect
2781
					$jetpack = Jetpack::init();
2782
2783
					$jetpack->stat( 'connections', 'unique-disconnect' );
2784
					$jetpack->do_stats( 'server_side' );
2785
				}
2786
				// increment number of times disconnected
2787
				$jetpack_unique_connection['disconnected'] += 1;
2788
			}
2789
2790
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2791
		}
2792
2793
		// Delete cached connected user data
2794
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2795
		delete_transient( $transient_key );
2796
2797
		// Delete all the sync related data. Since it could be taking up space.
2798
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2799
		Jetpack_Sync_Sender::get_instance()->uninstall();
2800
2801
		// Disable the Heartbeat cron
2802
		Jetpack_Heartbeat::init()->deactivate();
2803
	}
2804
2805
	/**
2806
	 * Unlinks the current user from the linked WordPress.com user
2807
	 */
2808
	public static function unlink_user( $user_id = null ) {
2809
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2810
			return false;
2811
2812
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2813
2814
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2815
			return false;
2816
2817
		if ( ! isset( $tokens[ $user_id ] ) )
2818
			return false;
2819
2820
		Jetpack::load_xml_rpc_client();
2821
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2822
		$xml->query( 'jetpack.unlink_user', $user_id );
2823
2824
		unset( $tokens[ $user_id ] );
2825
2826
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2827
2828
		/**
2829
		 * Fires after the current user has been unlinked from WordPress.com.
2830
		 *
2831
		 * @since 4.1.0
2832
		 *
2833
		 * @param int $user_id The current user's ID.
2834
		 */
2835
		do_action( 'jetpack_unlinked_user', $user_id );
2836
2837
		return true;
2838
	}
2839
2840
	/**
2841
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2842
	 */
2843
	public static function try_registration() {
2844
		// Let's get some testing in beta versions and such.
2845
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2846
			// Before attempting to connect, let's make sure that the domains are viable.
2847
			$domains_to_check = array_unique( array(
2848
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2849
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2850
			) );
2851
			foreach ( $domains_to_check as $domain ) {
2852
				$result = Jetpack_Data::is_usable_domain( $domain );
2853
				if ( is_wp_error( $result ) ) {
2854
					return $result;
2855
				}
2856
			}
2857
		}
2858
2859
		$result = Jetpack::register();
2860
2861
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2862
		if ( ! $result || is_wp_error( $result ) ) {
2863
			return $result;
2864
		} else {
2865
			return true;
2866
		}
2867
	}
2868
2869
	/**
2870
	 * Tracking an internal event log. Try not to put too much chaff in here.
2871
	 *
2872
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2873
	 */
2874
	public static function log( $code, $data = null ) {
2875
		// only grab the latest 200 entries
2876
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2877
2878
		// Append our event to the log
2879
		$log_entry = array(
2880
			'time'    => time(),
2881
			'user_id' => get_current_user_id(),
2882
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2883
			'code'    => $code,
2884
		);
2885
		// Don't bother storing it unless we've got some.
2886
		if ( ! is_null( $data ) ) {
2887
			$log_entry['data'] = $data;
2888
		}
2889
		$log[] = $log_entry;
2890
2891
		// Try add_option first, to make sure it's not autoloaded.
2892
		// @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...
2893
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2894
			Jetpack_Options::update_option( 'log', $log );
2895
		}
2896
2897
		/**
2898
		 * Fires when Jetpack logs an internal event.
2899
		 *
2900
		 * @since 3.0.0
2901
		 *
2902
		 * @param array $log_entry {
2903
		 *	Array of details about the log entry.
2904
		 *
2905
		 *	@param string time Time of the event.
2906
		 *	@param int user_id ID of the user who trigerred the event.
2907
		 *	@param int blog_id Jetpack Blog ID.
2908
		 *	@param string code Unique name for the event.
2909
		 *	@param string data Data about the event.
2910
		 * }
2911
		 */
2912
		do_action( 'jetpack_log_entry', $log_entry );
2913
	}
2914
2915
	/**
2916
	 * Get the internal event log.
2917
	 *
2918
	 * @param $event (string) - only return the specific log events
2919
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2920
	 *
2921
	 * @return array of log events || WP_Error for invalid params
2922
	 */
2923
	public static function get_log( $event = false, $num = false ) {
2924
		if ( $event && ! is_string( $event ) ) {
2925
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2926
		}
2927
2928
		if ( $num && ! is_numeric( $num ) ) {
2929
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2930
		}
2931
2932
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2933
2934
		// If nothing set - act as it did before, otherwise let's start customizing the output
2935
		if ( ! $num && ! $event ) {
2936
			return $entire_log;
2937
		} else {
2938
			$entire_log = array_reverse( $entire_log );
2939
		}
2940
2941
		$custom_log_output = array();
2942
2943
		if ( $event ) {
2944
			foreach ( $entire_log as $log_event ) {
2945
				if ( $event == $log_event[ 'code' ] ) {
2946
					$custom_log_output[] = $log_event;
2947
				}
2948
			}
2949
		} else {
2950
			$custom_log_output = $entire_log;
2951
		}
2952
2953
		if ( $num ) {
2954
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2955
		}
2956
2957
		return $custom_log_output;
2958
	}
2959
2960
	/**
2961
	 * Log modification of important settings.
2962
	 */
2963
	public static function log_settings_change( $option, $old_value, $value ) {
0 ignored issues
show
Unused Code introduced by
The parameter $old_value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
2964
		switch( $option ) {
2965
			case 'jetpack_sync_non_public_post_stati':
2966
				self::log( $option, $value );
2967
				break;
2968
		}
2969
	}
2970
2971
	/**
2972
	 * Return stat data for WPCOM sync
2973
	 */
2974
	public static function get_stat_data( $encode = true, $extended = true ) {
2975
		$data = Jetpack_Heartbeat::generate_stats_array();
2976
2977
		if ( $extended ) {
2978
			$additional_data = self::get_additional_stat_data();
2979
			$data = array_merge( $data, $additional_data );
2980
		}
2981
2982
		if ( $encode ) {
2983
			return json_encode( $data );
2984
		}
2985
2986
		return $data;
2987
	}
2988
2989
	/**
2990
	 * Get additional stat data to sync to WPCOM
2991
	 */
2992
	public static function get_additional_stat_data( $prefix = '' ) {
2993
		$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...
2994
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2995
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
2996
		$return["{$prefix}site-count"]     = 0;
2997
2998
		if ( function_exists( 'get_blog_count' ) ) {
2999
			$return["{$prefix}site-count"] = get_blog_count();
3000
		}
3001
		return $return;
3002
	}
3003
3004
	private static function get_site_user_count() {
3005
		global $wpdb;
3006
3007
		if ( function_exists( 'wp_is_large_network' ) ) {
3008
			if ( wp_is_large_network( 'users' ) ) {
3009
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3010
			}
3011
		}
3012 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3013
			// It wasn't there, so regenerate the data and save the transient
3014
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3015
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3016
		}
3017
		return $user_count;
3018
	}
3019
3020
	/* Admin Pages */
3021
3022
	function admin_init() {
3023
		// If the plugin is not connected, display a connect message.
3024
		if (
3025
			// the plugin was auto-activated and needs its candy
3026
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3027
		||
3028
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3029
			! Jetpack_Options::get_option( 'activated' )
3030
		) {
3031
			Jetpack::plugin_initialize();
3032
		}
3033
3034
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3035
			Jetpack_Connection_Banner::init();
3036
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3037
			// Upgrade: 1.1 -> 1.1.1
3038
			// Check and see if host can verify the Jetpack servers' SSL certificate
3039
			$args = array();
3040
			Jetpack_Client::_wp_remote_request(
3041
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3042
				$args,
3043
				true
3044
			);
3045
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3046
			// Show the notice on the Dashboard only for now
3047
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3048
		}
3049
3050
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3051
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3052
		}
3053
3054
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3055
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3056
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3057
3058
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3059
			// Artificially throw errors in certain whitelisted cases during plugin activation
3060
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3061
		}
3062
3063
		// Jetpack Manage Activation Screen from .com
3064
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3065
3066
		// Add custom column in wp-admin/users.php to show whether user is linked.
3067
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3068
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3069
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3070
	}
3071
3072
	function admin_body_class( $admin_body_class = '' ) {
3073
		$classes = explode( ' ', trim( $admin_body_class ) );
3074
3075
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3076
3077
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3078
		return " $admin_body_class ";
3079
	}
3080
3081
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3082
		return $admin_body_class . ' jetpack-pagestyles ';
3083
	}
3084
3085
	/**
3086
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3087
	 *
3088
	 * @return null
3089
	 */
3090
	function prepare_manage_jetpack_notice() {
3091
3092
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3093
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3094
	}
3095
3096
	function manage_activate_screen() {
3097
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3098
	}
3099
	/**
3100
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3101
	 * This function artificially throws errors for such cases (whitelisted).
3102
	 *
3103
	 * @param string $plugin The activated plugin.
3104
	 */
3105
	function throw_error_on_activate_plugin( $plugin ) {
3106
		$active_modules = Jetpack::get_active_modules();
3107
3108
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3109
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3110
			$throw = false;
3111
3112
			// Try and make sure it really was the stats plugin
3113
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3114
				if ( 'stats.php' == basename( $plugin ) ) {
3115
					$throw = true;
3116
				}
3117
			} else {
3118
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3119
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3120
					$throw = true;
3121
				}
3122
			}
3123
3124
			if ( $throw ) {
3125
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3126
			}
3127
		}
3128
	}
3129
3130
	function intercept_plugin_error_scrape_init() {
3131
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3132
	}
3133
3134
	function intercept_plugin_error_scrape( $action, $result ) {
3135
		if ( ! $result ) {
3136
			return;
3137
		}
3138
3139
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3140
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3141
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3142
			}
3143
		}
3144
	}
3145
3146
	function add_remote_request_handlers() {
3147
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3148
	}
3149
3150
	function remote_request_handlers() {
3151
		switch ( current_filter() ) {
3152
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3153
			$response = $this->upload_handler();
3154
			break;
3155
		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...
3156
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3157
			break;
3158
		}
3159
3160
		if ( ! $response ) {
3161
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3162
		}
3163
3164
		if ( is_wp_error( $response ) ) {
3165
			$status_code       = $response->get_error_data();
3166
			$error             = $response->get_error_code();
3167
			$error_description = $response->get_error_message();
3168
3169
			if ( ! is_int( $status_code ) ) {
3170
				$status_code = 400;
3171
			}
3172
3173
			status_header( $status_code );
3174
			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...
3175
		}
3176
3177
		status_header( 200 );
3178
		if ( true === $response ) {
3179
			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...
3180
		}
3181
3182
		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...
3183
	}
3184
3185
	function upload_handler() {
3186
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3187
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3188
		}
3189
3190
		$user = wp_authenticate( '', '' );
3191
		if ( ! $user || is_wp_error( $user ) ) {
3192
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3193
		}
3194
3195
		wp_set_current_user( $user->ID );
3196
3197
		if ( ! current_user_can( 'upload_files' ) ) {
3198
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3199
		}
3200
3201
		if ( empty( $_FILES ) ) {
3202
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3203
		}
3204
3205
		foreach ( array_keys( $_FILES ) as $files_key ) {
3206
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3207
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3208
			}
3209
		}
3210
3211
		$media_keys = array_keys( $_FILES['media'] );
3212
3213
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3214
		if ( ! $token || is_wp_error( $token ) ) {
3215
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3216
		}
3217
3218
		$uploaded_files = array();
3219
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3220
		unset( $GLOBALS['post'] );
3221
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3222
			$file = array();
3223
			foreach ( $media_keys as $media_key ) {
3224
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3225
			}
3226
3227
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3228
3229
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3230
			if ( $hmac_provided !== $hmac_file ) {
3231
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3232
				continue;
3233
			}
3234
3235
			$_FILES['.jetpack.upload.'] = $file;
3236
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3237
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3238
				$post_id = 0;
3239
			}
3240
			$attachment_id = media_handle_upload(
3241
				'.jetpack.upload.',
3242
				$post_id,
3243
				array(),
3244
				array(
3245
					'action' => 'jetpack_upload_file',
3246
				)
3247
			);
3248
3249
			if ( ! $attachment_id ) {
3250
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3251
			} elseif ( is_wp_error( $attachment_id ) ) {
3252
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3253
			} else {
3254
				$attachment = get_post( $attachment_id );
3255
				$uploaded_files[$index] = (object) array(
3256
					'id'   => (string) $attachment_id,
3257
					'file' => $attachment->post_title,
3258
					'url'  => wp_get_attachment_url( $attachment_id ),
3259
					'type' => $attachment->post_mime_type,
3260
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3261
				);
3262
				// Zip files uploads are not supported unless they are done for installation purposed
3263
				// lets delete them in case something goes wrong in this whole process
3264
				if ( 'application/zip' === $attachment->post_mime_type ) {
3265
					// Schedule a cleanup for 2 hours from now in case of failed install.
3266
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3267
				}
3268
			}
3269
		}
3270
		if ( ! is_null( $global_post ) ) {
3271
			$GLOBALS['post'] = $global_post;
3272
		}
3273
3274
		return $uploaded_files;
3275
	}
3276
3277
	/**
3278
	 * Add help to the Jetpack page
3279
	 *
3280
	 * @since Jetpack (1.2.3)
3281
	 * @return false if not the Jetpack page
3282
	 */
3283
	function admin_help() {
3284
		$current_screen = get_current_screen();
3285
3286
		// Overview
3287
		$current_screen->add_help_tab(
3288
			array(
3289
				'id'		=> 'home',
3290
				'title'		=> __( 'Home', 'jetpack' ),
3291
				'content'	=>
3292
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3293
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3294
					'<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>',
3295
			)
3296
		);
3297
3298
		// Screen Content
3299
		if ( current_user_can( 'manage_options' ) ) {
3300
			$current_screen->add_help_tab(
3301
				array(
3302
					'id'		=> 'settings',
3303
					'title'		=> __( 'Settings', 'jetpack' ),
3304
					'content'	=>
3305
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3306
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3307
						'<ol>' .
3308
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3309
							'<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>' .
3310
						'</ol>' .
3311
						'<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>'
3312
				)
3313
			);
3314
		}
3315
3316
		// Help Sidebar
3317
		$current_screen->set_help_sidebar(
3318
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3319
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3320
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3321
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3322
		);
3323
	}
3324
3325
	function admin_menu_css() {
3326
		wp_enqueue_style( 'jetpack-icons' );
3327
	}
3328
3329
	function admin_menu_order() {
3330
		return true;
3331
	}
3332
3333 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3334
		$jp_menu_order = array();
3335
3336
		foreach ( $menu_order as $index => $item ) {
3337
			if ( $item != 'jetpack' ) {
3338
				$jp_menu_order[] = $item;
3339
			}
3340
3341
			if ( $index == 0 ) {
3342
				$jp_menu_order[] = 'jetpack';
3343
			}
3344
		}
3345
3346
		return $jp_menu_order;
3347
	}
3348
3349
	function admin_head() {
3350 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3351
			/** This action is documented in class.jetpack-admin-page.php */
3352
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3353
	}
3354
3355
	function admin_banner_styles() {
3356
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3357
3358 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3359
			wp_register_style(
3360
				'jetpack-dops-style',
3361
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3362
				array(),
3363
				JETPACK__VERSION
3364
			);
3365
		}
3366
3367
		wp_enqueue_style(
3368
			'jetpack',
3369
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3370
			array( 'jetpack-dops-style' ),
3371
			 JETPACK__VERSION . '-20121016'
3372
		);
3373
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3374
		wp_style_add_data( 'jetpack', 'suffix', $min );
3375
	}
3376
3377
	function plugin_action_links( $actions ) {
3378
3379
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3380
3381
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3382
			return array_merge(
3383
				$jetpack_home,
3384
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3385
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3386
				$actions
3387
				);
3388
			}
3389
3390
		return array_merge( $jetpack_home, $actions );
3391
	}
3392
3393
	/**
3394
	 * This is the first banner
3395
	 * It should be visible only to user that can update the option
3396
	 * Are not connected
3397
	 *
3398
	 * @return null
3399
	 */
3400
	function admin_jetpack_manage_notice() {
3401
		$screen = get_current_screen();
3402
3403
		// Don't show the connect notice on the jetpack settings page.
3404
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3405
			return;
3406
		}
3407
3408
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3409
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3410
		/**
3411
		 * I think it would be great to have different wordsing depending on where you are
3412
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3413
		 * etc..
3414
		 */
3415
3416
		?>
3417
		<div id="message" class="updated jp-banner">
3418
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3419
				<div class="jp-banner__description-container">
3420
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3421
					<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>
3422
					<p class="jp-banner__button-container">
3423
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3424
						<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>
3425
					</p>
3426
				</div>
3427
		</div>
3428
		<?php
3429
	}
3430
3431
	/**
3432
	 * Returns the url that the user clicks to remove the notice for the big banner
3433
	 * @return (string)
3434
	 */
3435
	function opt_out_jetpack_manage_url() {
3436
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3437
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3438
	}
3439
	/**
3440
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3441
	 * @return (string)
3442
	 */
3443
	function opt_in_jetpack_manage_url() {
3444
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3445
	}
3446
3447
	function opt_in_jetpack_manage_notice() {
3448
		?>
3449
		<div class="wrap">
3450
			<div id="message" class="jetpack-message is-opt-in">
3451
				<?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' ); ?>
3452
			</div>
3453
		</div>
3454
		<?php
3455
3456
	}
3457
	/**
3458
	 * Determines whether to show the notice of not true = display notice
3459
	 * @return (bool)
3460
	 */
3461
	function can_display_jetpack_manage_notice() {
3462
		// never display the notice to users that can't do anything about it anyways
3463
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3464
			return false;
3465
3466
		// don't display if we are in development more
3467
		if( Jetpack::is_development_mode() ) {
3468
			return false;
3469
		}
3470
		// don't display if the site is private
3471
		if(  ! Jetpack_Options::get_option( 'public' ) )
3472
			return false;
3473
3474
		/**
3475
		 * Should the Jetpack Remote Site Management notice be displayed.
3476
		 *
3477
		 * @since 3.3.0
3478
		 *
3479
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3480
		 */
3481
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3482
	}
3483
3484
	/*
3485
	 * Registration flow:
3486
	 * 1 - ::admin_page_load() action=register
3487
	 * 2 - ::try_registration()
3488
	 * 3 - ::register()
3489
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3490
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3491
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3492
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3493
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3494
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3495
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3496
	 *       jetpack_id, jetpack_secret, jetpack_public
3497
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3498
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3499
	 * 5 - user logs in with WP.com account
3500
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3501
	 *		- Jetpack_Client_Server::authorize()
3502
	 *		- Jetpack_Client_Server::get_token()
3503
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3504
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3505
	 *			- which responds with access_token, token_type, scope
3506
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3507
	 *		- Jetpack::activate_default_modules()
3508
	 *     		- Deactivates deprecated plugins
3509
	 *     		- Activates all default modules
3510
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3511
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3512
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3513
	 *     Done!
3514
	 */
3515
3516
	/**
3517
	 * Handles the page load events for the Jetpack admin page
3518
	 */
3519
	function admin_page_load() {
3520
		$error = false;
3521
3522
		// Make sure we have the right body class to hook stylings for subpages off of.
3523
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3524
3525
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3526
			// Should only be used in intermediate redirects to preserve state across redirects
3527
			Jetpack::restate();
3528
		}
3529
3530
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3531
			// User clicked in the iframe to link their accounts
3532
			if ( ! Jetpack::is_user_connected() ) {
3533
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3534
				if ( isset( $_GET['notes_iframe'] ) )
3535
					$connect_url .= '&notes_iframe';
3536
				wp_redirect( $connect_url );
3537
				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...
3538
			} else {
3539
				if ( ! isset( $_GET['calypso_env'] ) ) {
3540
					Jetpack::state( 'message', 'already_authorized' );
3541
					wp_safe_redirect( Jetpack::admin_url() );
3542
				} else {
3543
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3544
					$connect_url .= '&already_authorized=true';
3545
					wp_redirect( $connect_url );
3546
				}
3547
			}
3548
		}
3549
3550
3551
		if ( isset( $_GET['action'] ) ) {
3552
			switch ( $_GET['action'] ) {
3553
			case 'authorize':
3554
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3555
					Jetpack::state( 'message', 'already_authorized' );
3556
					wp_safe_redirect( Jetpack::admin_url() );
3557
					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...
3558
				}
3559
				Jetpack::log( 'authorize' );
3560
				$client_server = new Jetpack_Client_Server;
3561
				$client_server->client_authorize();
3562
				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...
3563
			case 'register' :
3564
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3565
					$error = 'cheatin';
3566
					break;
3567
				}
3568
				check_admin_referer( 'jetpack-register' );
3569
				Jetpack::log( 'register' );
3570
				Jetpack::maybe_set_version_option();
3571
				$registered = Jetpack::try_registration();
3572
				if ( is_wp_error( $registered ) ) {
3573
					$error = $registered->get_error_code();
3574
					Jetpack::state( 'error', $error );
3575
					Jetpack::state( 'error', $registered->get_error_message() );
3576
					break;
3577
				}
3578
3579
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3580
3581
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3582
				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...
3583
			case 'activate' :
3584
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3585
					$error = 'cheatin';
3586
					break;
3587
				}
3588
3589
				$module = stripslashes( $_GET['module'] );
3590
				check_admin_referer( "jetpack_activate-$module" );
3591
				Jetpack::log( 'activate', $module );
3592
				Jetpack::activate_module( $module );
3593
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3594
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3595
				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...
3596
			case 'activate_default_modules' :
3597
				check_admin_referer( 'activate_default_modules' );
3598
				Jetpack::log( 'activate_default_modules' );
3599
				Jetpack::restate();
3600
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3601
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3602
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3603
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3604
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3605
				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...
3606
			case 'disconnect' :
3607
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3608
					$error = 'cheatin';
3609
					break;
3610
				}
3611
3612
				check_admin_referer( 'jetpack-disconnect' );
3613
				Jetpack::log( 'disconnect' );
3614
				Jetpack::disconnect();
3615
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3616
				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...
3617
			case 'reconnect' :
3618
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3619
					$error = 'cheatin';
3620
					break;
3621
				}
3622
3623
				check_admin_referer( 'jetpack-reconnect' );
3624
				Jetpack::log( 'reconnect' );
3625
				$this->disconnect();
3626
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3627
				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...
3628 View Code Duplication
			case 'deactivate' :
3629
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3630
					$error = 'cheatin';
3631
					break;
3632
				}
3633
3634
				$modules = stripslashes( $_GET['module'] );
3635
				check_admin_referer( "jetpack_deactivate-$modules" );
3636
				foreach ( explode( ',', $modules ) as $module ) {
3637
					Jetpack::log( 'deactivate', $module );
3638
					Jetpack::deactivate_module( $module );
3639
					Jetpack::state( 'message', 'module_deactivated' );
3640
				}
3641
				Jetpack::state( 'module', $modules );
3642
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3643
				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...
3644
			case 'unlink' :
3645
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3646
				check_admin_referer( 'jetpack-unlink' );
3647
				Jetpack::log( 'unlink' );
3648
				$this->unlink_user();
3649
				Jetpack::state( 'message', 'unlinked' );
3650
				if ( 'sub-unlink' == $redirect ) {
3651
					wp_safe_redirect( admin_url() );
3652
				} else {
3653
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3654
				}
3655
				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...
3656
			default:
3657
				/**
3658
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3659
				 *
3660
				 * @since 2.6.0
3661
				 *
3662
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3663
				 */
3664
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3665
			}
3666
		}
3667
3668
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3669
			self::activate_new_modules( true );
3670
		}
3671
3672
		$message_code = Jetpack::state( 'message' );
3673
		if ( Jetpack::state( 'optin-manage' ) ) {
3674
			$activated_manage = $message_code;
3675
			$message_code = 'jetpack-manage';
3676
		}
3677
3678
		switch ( $message_code ) {
3679
		case 'jetpack-manage':
3680
			$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>';
3681
			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...
3682
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3683
			}
3684
			break;
3685
3686
		}
3687
3688
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3689
3690
		if ( ! empty( $deactivated_plugins ) ) {
3691
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3692
			$deactivated_titles  = array();
3693
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3694
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3695
					continue;
3696
				}
3697
3698
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3699
			}
3700
3701
			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...
3702
				if ( $this->message ) {
3703
					$this->message .= "<br /><br />\n";
3704
				}
3705
3706
				$this->message .= wp_sprintf(
3707
					_n(
3708
						'Jetpack contains the most recent version of the old %l plugin.',
3709
						'Jetpack contains the most recent versions of the old %l plugins.',
3710
						count( $deactivated_titles ),
3711
						'jetpack'
3712
					),
3713
					$deactivated_titles
3714
				);
3715
3716
				$this->message .= "<br />\n";
3717
3718
				$this->message .= _n(
3719
					'The old version has been deactivated and can be removed from your site.',
3720
					'The old versions have been deactivated and can be removed from your site.',
3721
					count( $deactivated_titles ),
3722
					'jetpack'
3723
				);
3724
			}
3725
		}
3726
3727
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3728
3729
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3730
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3731
		}
3732
3733 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3734
			/**
3735
			 * Fires when a module configuration page is loaded.
3736
			 * The dynamic part of the hook is the configure parameter from the URL.
3737
			 *
3738
			 * @since 1.1.0
3739
			 */
3740
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3741
		}
3742
3743
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3744
	}
3745
3746
	function admin_notices() {
3747
3748
		if ( $this->error ) {
3749
?>
3750
<div id="message" class="jetpack-message jetpack-err">
3751
	<div class="squeezer">
3752
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3753
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3754
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3755
<?php	endif; ?>
3756
	</div>
3757
</div>
3758
<?php
3759
		}
3760
3761
		if ( $this->message ) {
3762
?>
3763
<div id="message" class="jetpack-message">
3764
	<div class="squeezer">
3765
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3766
	</div>
3767
</div>
3768
<?php
3769
		}
3770
3771
		if ( $this->privacy_checks ) :
3772
			$module_names = $module_slugs = array();
3773
3774
			$privacy_checks = explode( ',', $this->privacy_checks );
3775
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3776
			foreach ( $privacy_checks as $module_slug ) {
3777
				$module = Jetpack::get_module( $module_slug );
3778
				if ( ! $module ) {
3779
					continue;
3780
				}
3781
3782
				$module_slugs[] = $module_slug;
3783
				$module_names[] = "<strong>{$module['name']}</strong>";
3784
			}
3785
3786
			$module_slugs = join( ',', $module_slugs );
3787
?>
3788
<div id="message" class="jetpack-message jetpack-err">
3789
	<div class="squeezer">
3790
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3791
		<p><?php
3792
			echo wp_kses(
3793
				wptexturize(
3794
					wp_sprintf(
3795
						_nx(
3796
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3797
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3798
							count( $privacy_checks ),
3799
							'%l = list of Jetpack module/feature names',
3800
							'jetpack'
3801
						),
3802
						$module_names
3803
					)
3804
				),
3805
				array( 'strong' => true )
3806
			);
3807
3808
			echo "\n<br />\n";
3809
3810
			echo wp_kses(
3811
				sprintf(
3812
					_nx(
3813
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3814
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3815
						count( $privacy_checks ),
3816
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3817
						'jetpack'
3818
					),
3819
					wp_nonce_url(
3820
						Jetpack::admin_url(
3821
							array(
3822
								'page'   => 'jetpack',
3823
								'action' => 'deactivate',
3824
								'module' => urlencode( $module_slugs ),
3825
							)
3826
						),
3827
						"jetpack_deactivate-$module_slugs"
3828
					),
3829
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3830
				),
3831
				array( 'a' => array( 'href' => true, 'title' => true ) )
3832
			);
3833
		?></p>
3834
	</div>
3835
</div>
3836
<?php endif;
3837
	// only display the notice if the other stuff is not there
3838
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3839
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3840
			$this->opt_in_jetpack_manage_notice();
3841
		}
3842
	}
3843
3844
	/**
3845
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3846
	 */
3847
	function stat( $group, $detail ) {
3848
		if ( ! isset( $this->stats[ $group ] ) )
3849
			$this->stats[ $group ] = array();
3850
		$this->stats[ $group ][] = $detail;
3851
	}
3852
3853
	/**
3854
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3855
	 */
3856
	function do_stats( $method = '' ) {
3857
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3858
			foreach ( $this->stats as $group => $stats ) {
3859
				if ( is_array( $stats ) && count( $stats ) ) {
3860
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3861
					if ( 'server_side' === $method ) {
3862
						self::do_server_side_stat( $args );
3863
					} else {
3864
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3865
					}
3866
				}
3867
				unset( $this->stats[ $group ] );
3868
			}
3869
		}
3870
	}
3871
3872
	/**
3873
	 * Runs stats code for a one-off, server-side.
3874
	 *
3875
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3876
	 *
3877
	 * @return bool If it worked.
3878
	 */
3879
	static function do_server_side_stat( $args ) {
3880
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3881
		if ( is_wp_error( $response ) )
3882
			return false;
3883
3884
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3885
			return false;
3886
3887
		return true;
3888
	}
3889
3890
	/**
3891
	 * Builds the stats url.
3892
	 *
3893
	 * @param $args array|string The arguments to append to the URL.
3894
	 *
3895
	 * @return string The URL to be pinged.
3896
	 */
3897
	static function build_stats_url( $args ) {
3898
		$defaults = array(
3899
			'v'    => 'wpcom2',
3900
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3901
		);
3902
		$args     = wp_parse_args( $args, $defaults );
3903
		/**
3904
		 * Filter the URL used as the Stats tracking pixel.
3905
		 *
3906
		 * @since 2.3.2
3907
		 *
3908
		 * @param string $url Base URL used as the Stats tracking pixel.
3909
		 */
3910
		$base_url = apply_filters(
3911
			'jetpack_stats_base_url',
3912
			'https://pixel.wp.com/g.gif'
3913
		);
3914
		$url      = add_query_arg( $args, $base_url );
3915
		return $url;
3916
	}
3917
3918
	static function translate_current_user_to_role() {
3919
		foreach ( self::$capability_translations as $role => $cap ) {
3920
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3921
				return $role;
3922
			}
3923
		}
3924
3925
		return false;
3926
	}
3927
3928
	static function translate_role_to_cap( $role ) {
3929
		if ( ! isset( self::$capability_translations[$role] ) ) {
3930
			return false;
3931
		}
3932
3933
		return self::$capability_translations[$role];
3934
	}
3935
3936
	static function sign_role( $role ) {
3937
		if ( ! $user_id = (int) get_current_user_id() ) {
3938
			return false;
3939
		}
3940
3941
		$token = Jetpack_Data::get_access_token();
3942
		if ( ! $token || is_wp_error( $token ) ) {
3943
			return false;
3944
		}
3945
3946
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3947
	}
3948
3949
3950
	/**
3951
	 * Builds a URL to the Jetpack connection auth page
3952
	 *
3953
	 * @since 3.9.5
3954
	 *
3955
	 * @param bool $raw If true, URL will not be escaped.
3956
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3957
	 *                              If string, will be a custom redirect.
3958
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3959
	 *
3960
	 * @return string Connect URL
3961
	 */
3962
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
3963
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
3964
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3965
			if( is_network_admin() ) {
3966
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3967
			}
3968
		} else {
3969
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3970
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3971
			}
3972
3973
			$role = self::translate_current_user_to_role();
3974
			$signed_role = self::sign_role( $role );
3975
3976
			$user = wp_get_current_user();
3977
3978
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3979
			$redirect = $redirect
3980
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3981
				: $jetpack_admin_page;
3982
3983
			if( isset( $_REQUEST['is_multisite'] ) ) {
3984
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3985
			}
3986
3987
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
3988
			@list( $secret ) = explode( ':', $secrets );
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...
3989
3990
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3991
				? get_site_icon_url()
3992
				: false;
3993
3994
			/**
3995
			 * Filter the type of authorization.
3996
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
3997
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3998
			 *
3999
			 * @since 4.3.3
4000
			 *
4001
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4002
			 */
4003
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4004
4005
			$args = urlencode_deep(
4006
				array(
4007
					'response_type' => 'code',
4008
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4009
					'redirect_uri'  => add_query_arg(
4010
						array(
4011
							'action'   => 'authorize',
4012
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4013
							'redirect' => urlencode( $redirect ),
4014
						),
4015
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4016
					),
4017
					'state'         => $user->ID,
4018
					'scope'         => $signed_role,
4019
					'user_email'    => $user->user_email,
4020
					'user_login'    => $user->user_login,
4021
					'is_active'     => Jetpack::is_active(),
4022
					'jp_version'    => JETPACK__VERSION,
4023
					'auth_type'     => $auth_type,
4024
					'secret'        => $secret,
4025
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4026
					'blogname'      => get_option( 'blogname' ),
4027
					'site_url'      => site_url(),
4028
					'home_url'      => home_url(),
4029
					'site_icon'     => $site_icon,
4030
				)
4031
			);
4032
4033
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4034
		}
4035
4036
		if ( $from ) {
4037
			$url = add_query_arg( 'from', $from, $url );
4038
		}
4039
4040
		if ( isset( $_GET['calypso_env'] ) ) {
4041
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4042
		}
4043
4044
		return $raw ? $url : esc_url( $url );
4045
	}
4046
4047
	function build_reconnect_url( $raw = false ) {
4048
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4049
		return $raw ? $url : esc_url( $url );
4050
	}
4051
4052
	public static function admin_url( $args = null ) {
4053
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4054
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4055
		return $url;
4056
	}
4057
4058
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4059
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4060
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4061
	}
4062
4063
	function dismiss_jetpack_notice() {
4064
4065
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4066
			return;
4067
		}
4068
4069
		switch( $_GET['jetpack-notice'] ) {
4070
			case 'dismiss':
4071
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4072
4073
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4074
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4075
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4076
				}
4077
				break;
4078 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...
4079
4080
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4081
					// Don't show the banner again
4082
4083
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4084
					// redirect back to the page that had the notice
4085
					if ( wp_get_referer() ) {
4086
						wp_safe_redirect( wp_get_referer() );
4087
					} else {
4088
						// Take me to Jetpack
4089
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4090
					}
4091
				}
4092
				break;
4093 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...
4094
4095
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4096
					// Don't show the banner again
4097
4098
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4099
					// redirect back to the page that had the notice
4100
					if ( wp_get_referer() ) {
4101
						wp_safe_redirect( wp_get_referer() );
4102
					} else {
4103
						// Take me to Jetpack
4104
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4105
					}
4106
				}
4107
				break;
4108
			case 'jetpack-manage-opt-in':
4109
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4110
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4111
4112
					$redirection_url = Jetpack::admin_url();
4113
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4114
4115
					// Don't redirect form the Jetpack Setting Page
4116
					$referer_parsed = parse_url ( wp_get_referer() );
4117
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4118
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4119
						// Take the user to Jetpack home except when on the setting page
4120
						$redirection_url = wp_get_referer();
4121
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4122
					}
4123
					// Also update the JSON API FULL MANAGEMENT Option
4124
					Jetpack::activate_module( 'manage', false, false );
4125
4126
					// Special Message when option in.
4127
					Jetpack::state( 'optin-manage', 'true' );
4128
					// Activate the Module if not activated already
4129
4130
					// Redirect properly
4131
					wp_safe_redirect( $redirection_url );
4132
4133
				}
4134
				break;
4135
		}
4136
	}
4137
4138
	function debugger_page() {
4139
		nocache_headers();
4140
		if ( ! current_user_can( 'manage_options' ) ) {
4141
			die( '-1' );
0 ignored issues
show
Coding Style Compatibility introduced by
The method debugger_page() 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...
4142
		}
4143
		Jetpack_Debugger::jetpack_debug_display_handler();
4144
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method debugger_page() 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...
4145
	}
4146
4147
	public static function admin_screen_configure_module( $module_id ) {
4148
4149
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4150
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4151
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4152
				/**
4153
				 * Fires to diplay a custom module activation screen.
4154
				 *
4155
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4156
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4157
				 *
4158
				 * @module manage
4159
				 *
4160
				 * @since 3.8.0
4161
				 *
4162
				 * @param int $module_id Module ID.
4163
				 */
4164
				do_action( 'display_activate_module_setting_' . $module_id );
4165
			} else {
4166
				self::display_activate_module_link( $module_id );
4167
			}
4168
4169
			return false;
4170
		} ?>
4171
4172
		<div id="jp-settings-screen" style="position: relative">
4173
			<h3>
4174
			<?php
4175
				$module = Jetpack::get_module( $module_id );
4176
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4177
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4178
			?>
4179
			</h3>
4180
			<?php
4181
				/**
4182
				 * Fires within the displayed message when a feature configuation is updated.
4183
				 *
4184
				 * @since 3.4.0
4185
				 *
4186
				 * @param int $module_id Module ID.
4187
				 */
4188
				do_action( 'jetpack_notices_update_settings', $module_id );
4189
				/**
4190
				 * Fires when a feature configuation screen is loaded.
4191
				 * The dynamic part of the hook, $module_id, is the module ID.
4192
				 *
4193
				 * @since 1.1.0
4194
				 */
4195
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4196
			?>
4197
		</div><?php
4198
	}
4199
4200
	/**
4201
	 * Display link to activate the module to see the settings screen.
4202
	 * @param  string $module_id
4203
	 * @return null
4204
	 */
4205
	public static function display_activate_module_link( $module_id ) {
4206
4207
		$info =  Jetpack::get_module( $module_id );
4208
		$extra = '';
4209
		$activate_url = wp_nonce_url(
4210
				Jetpack::admin_url(
4211
					array(
4212
						'page'   => 'jetpack',
4213
						'action' => 'activate',
4214
						'module' => $module_id,
4215
					)
4216
				),
4217
				"jetpack_activate-$module_id"
4218
			);
4219
4220
		?>
4221
4222
		<div class="wrap configure-module">
4223
			<div id="jp-settings-screen">
4224
				<?php
4225
				if ( $module_id == 'json-api' ) {
4226
4227
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4228
4229
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4230
4231
					$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' );
4232
4233
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4234
				} ?>
4235
4236
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4237
				<div class="narrow">
4238
					<p><?php echo  $info['description']; ?></p>
4239
					<?php if( $extra ) { ?>
4240
					<p><?php echo esc_html( $extra ); ?></p>
4241
					<?php } ?>
4242
					<p>
4243
						<?php
4244
						if( wp_get_referer() ) {
4245
							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() );
4246
						} else {
4247
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4248
						} ?>
4249
					</p>
4250
				</div>
4251
4252
			</div>
4253
		</div>
4254
4255
		<?php
4256
	}
4257
4258
	public static function sort_modules( $a, $b ) {
4259
		if ( $a['sort'] == $b['sort'] )
4260
			return 0;
4261
4262
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4263
	}
4264
4265
	function ajax_recheck_ssl() {
4266
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4267
		$result = Jetpack::permit_ssl( true );
4268
		wp_send_json( array(
4269
			'enabled' => $result,
4270
			'message' => get_transient( 'jetpack_https_test_message' )
4271
		) );
4272
	}
4273
4274
/* Client API */
4275
4276
	/**
4277
	 * Returns the requested Jetpack API URL
4278
	 *
4279
	 * @return string
4280
	 */
4281
	public static function api_url( $relative_url ) {
4282
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4283
	}
4284
4285
	/**
4286
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4287
	 */
4288
	public static function fix_url_for_bad_hosts( $url ) {
4289
		if ( 0 !== strpos( $url, 'https://' ) ) {
4290
			return $url;
4291
		}
4292
4293
		switch ( JETPACK_CLIENT__HTTPS ) {
4294
			case 'ALWAYS' :
4295
				return $url;
4296
			case 'NEVER' :
4297
				return set_url_scheme( $url, 'http' );
4298
			// default : case 'AUTO' :
4299
		}
4300
4301
		// we now return the unmodified SSL URL by default, as a security precaution
4302
		return $url;
4303
	}
4304
4305
	/**
4306
	 * Checks to see if the URL is using SSL to connect with Jetpack
4307
	 *
4308
	 * @since 2.3.3
4309
	 * @return boolean
4310
	 */
4311
	public static function permit_ssl( $force_recheck = false ) {
4312
		// Do some fancy tests to see if ssl is being supported
4313
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4314
			$message = '';
4315
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4316
				$ssl = 0;
4317
			} else {
4318
				switch ( JETPACK_CLIENT__HTTPS ) {
4319
					case 'NEVER':
4320
						$ssl = 0;
4321
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4322
						break;
4323
					case 'ALWAYS':
4324
					case 'AUTO':
4325
					default:
4326
						$ssl = 1;
4327
						break;
4328
				}
4329
4330
				// If it's not 'NEVER', test to see
4331
				if ( $ssl ) {
4332
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4333
						$ssl = 0;
4334
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4335
					} else {
4336
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4337
						if ( is_wp_error( $response ) ) {
4338
							$ssl = 0;
4339
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4340
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4341
							$ssl = 0;
4342
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4343
						}
4344
					}
4345
				}
4346
			}
4347
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4348
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4349
		}
4350
4351
		return (bool) $ssl;
4352
	}
4353
4354
	/*
4355
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4356
	 */
4357
	public function alert_auto_ssl_fail() {
4358
		if ( ! current_user_can( 'manage_options' ) )
4359
			return;
4360
4361
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4362
		?>
4363
4364
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4365
			<div class="jp-banner__content">
4366
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4367
				<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>
4368
				<p>
4369
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4370
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4371
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4372
				</p>
4373
				<p>
4374
					<?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' ),
4375
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4376
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4377
				</p>
4378
			</div>
4379
		</div>
4380
		<style>
4381
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4382
		</style>
4383
		<script type="text/javascript">
4384
			jQuery( document ).ready( function( $ ) {
4385
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4386
					var $this = $( this );
4387
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4388
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4389
					e.preventDefault();
4390
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4391
					$.post( ajaxurl, data )
4392
					  .done( function( response ) {
4393
					  	if ( response.enabled ) {
4394
					  		$( '#jetpack-ssl-warning' ).hide();
4395
					  	} else {
4396
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4397
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4398
					  	}
4399
					  }.bind( $this ) );
4400
				} );
4401
			} );
4402
		</script>
4403
4404
		<?php
4405
	}
4406
4407
	/**
4408
	 * Returns the Jetpack XML-RPC API
4409
	 *
4410
	 * @return string
4411
	 */
4412
	public static function xmlrpc_api_url() {
4413
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4414
		return untrailingslashit( $base ) . '/xmlrpc.php';
4415
	}
4416
4417
	/**
4418
	 * Creates two secret tokens and the end of life timestamp for them.
4419
	 *
4420
	 * Note these tokens are unique per call, NOT static per site for connecting.
4421
	 *
4422
	 * @since 2.6
4423
	 * @return array
4424
	 */
4425
	public function generate_secrets( $action, $exp = 600 ) {
4426
	    $secret = wp_generate_password( 32, false ) // secret_1
4427
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4428
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4429
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4430
		Jetpack_Options::update_option( $action, $secret );
4431
	    return Jetpack_Options::get_option( $action );
4432
	}
4433
4434
	/**
4435
	 * Builds the timeout limit for queries talking with the wpcom servers.
4436
	 *
4437
	 * Based on local php max_execution_time in php.ini
4438
	 *
4439
	 * @since 2.6
4440
	 * @return int
4441
	 **/
4442
	public function get_remote_query_timeout_limit() {
4443
	    $timeout = (int) ini_get( 'max_execution_time' );
4444
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4445
		$timeout = 30;
4446
	    return intval( $timeout / 2 );
4447
	}
4448
4449
4450
	/**
4451
	 * Takes the response from the Jetpack register new site endpoint and
4452
	 * verifies it worked properly.
4453
	 *
4454
	 * @since 2.6
4455
	 * @return true or Jetpack_Error
4456
	 **/
4457
	public function validate_remote_register_response( $response ) {
4458
	    	if ( is_wp_error( $response ) ) {
4459
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4460
		}
4461
4462
		$code   = wp_remote_retrieve_response_code( $response );
4463
		$entity = wp_remote_retrieve_body( $response );
4464
		if ( $entity )
4465
			$json = json_decode( $entity );
4466
		else
4467
			$json = false;
4468
4469
		$code_type = intval( $code / 100 );
4470
		if ( 5 == $code_type ) {
4471
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4472
		} elseif ( 408 == $code ) {
4473
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4474
		} elseif ( ! empty( $json->error ) ) {
4475
			if ( 'xml_rpc-32700' == $json->error && ! function_exists( 'xml_parser_create' ) ) {
4476
				$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' );
4477
			} else {
4478
				$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4479
			}
4480
			
4481
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4482
		} elseif ( 200 != $code ) {
4483
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4484
		}
4485
4486
		// Jetpack ID error block
4487
		if ( empty( $json->jetpack_id ) ) {
4488
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4489
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4490
			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 );
4491
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4492
			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 );
4493
		}
4494
4495
	    return true;
4496
	}
4497
	/**
4498
	 * @return bool|WP_Error
4499
	 */
4500
	public static function register() {
4501
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4502
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4503
4504
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
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...
4505 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4506
			return new Jetpack_Error( 'missing_secrets' );
4507
		}
4508
4509
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4510
4511
		$gmt_offset = get_option( 'gmt_offset' );
4512
		if ( ! $gmt_offset ) {
4513
			$gmt_offset = 0;
4514
		}
4515
4516
		$stats_options = get_option( 'stats_options' );
4517
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4518
4519
		$args = array(
4520
			'method'  => 'POST',
4521
			'body'    => array(
4522
				'siteurl'         => site_url(),
4523
				'home'            => home_url(),
4524
				'gmt_offset'      => $gmt_offset,
4525
				'timezone_string' => (string) get_option( 'timezone_string' ),
4526
				'site_name'       => (string) get_option( 'blogname' ),
4527
				'secret_1'        => $secret_1,
4528
				'secret_2'        => $secret_2,
4529
				'site_lang'       => get_locale(),
4530
				'timeout'         => $timeout,
4531
				'stats_id'        => $stats_id,
4532
				'state'           => get_current_user_id(),
4533
			),
4534
			'headers' => array(
4535
				'Accept' => 'application/json',
4536
			),
4537
			'timeout' => $timeout,
4538
		);
4539
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4540
4541
4542
		// Make sure the response is valid and does not contain any Jetpack errors
4543
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
4544
		if( is_wp_error( $valid_response ) || !$valid_response ) {
4545
		    return $valid_response;
4546
		}
4547
4548
		// Grab the response values to work with
4549
		$code   = wp_remote_retrieve_response_code( $response );
4550
		$entity = wp_remote_retrieve_body( $response );
4551
4552
		if ( $entity )
4553
			$json = json_decode( $entity );
4554
		else
4555
			$json = false;
4556
4557 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4558
			return new Jetpack_Error( 'jetpack_secret', '', $code );
4559
4560
		if ( isset( $json->jetpack_public ) ) {
4561
			$jetpack_public = (int) $json->jetpack_public;
4562
		} else {
4563
			$jetpack_public = false;
4564
		}
4565
4566
		Jetpack_Options::update_options(
4567
			array(
4568
				'id'         => (int)    $json->jetpack_id,
4569
				'blog_token' => (string) $json->jetpack_secret,
4570
				'public'     => $jetpack_public,
4571
			)
4572
		);
4573
4574
		/**
4575
		 * Fires when a site is registered on WordPress.com.
4576
		 *
4577
		 * @since 3.7.0
4578
		 *
4579
		 * @param int $json->jetpack_id Jetpack Blog ID.
4580
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4581
		 * @param int|bool $jetpack_public Is the site public.
4582
		 */
4583
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
4584
4585
		// Initialize Jump Start for the first and only time.
4586
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4587
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4588
4589
			$jetpack = Jetpack::init();
4590
4591
			$jetpack->stat( 'jumpstart', 'unique-views' );
4592
			$jetpack->do_stats( 'server_side' );
4593
		};
4594
4595
		return true;
4596
	}
4597
4598
	/**
4599
	 * If the db version is showing something other that what we've got now, bump it to current.
4600
	 *
4601
	 * @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...
4602
	 */
4603
	public static function maybe_set_version_option() {
4604
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4605
		if ( JETPACK__VERSION != $version ) {
4606
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4607
4608
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4609
				/** This action is documented in class.jetpack.php */
4610
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4611
			}
4612
4613
			return true;
4614
		}
4615
		return false;
4616
	}
4617
4618
/* Client Server API */
4619
4620
	/**
4621
	 * Loads the Jetpack XML-RPC client
4622
	 */
4623
	public static function load_xml_rpc_client() {
4624
		require_once ABSPATH . WPINC . '/class-IXR.php';
4625
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4626
	}
4627
4628
	/**
4629
	 * Resets the saved XMLRPC verification in between testing requests.
4630
	 */
4631
	public function reset_xmlrpc_verification() {
4632
		$this->xmlrpc_verification = null;
4633
	}
4634
4635
	function verify_xml_rpc_signature() {
4636
		if ( $this->xmlrpc_verification ) {
4637
			return $this->xmlrpc_verification;
4638
		}
4639
4640
		// It's not for us
4641
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4642
			return false;
4643
		}
4644
4645
		@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...
4646
		if (
4647
			empty( $token_key )
4648
		||
4649
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4650
		) {
4651
			return false;
4652
		}
4653
4654
		if ( '0' === $user_id ) {
4655
			$token_type = 'blog';
4656
			$user_id = 0;
4657
		} else {
4658
			$token_type = 'user';
4659
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4660
				return false;
4661
			}
4662
			$user_id = (int) $user_id;
4663
4664
			$user = new WP_User( $user_id );
4665
			if ( ! $user || ! $user->exists() ) {
4666
				return false;
4667
			}
4668
		}
4669
4670
		$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...
4671
		if ( ! $token ) {
4672
			return false;
4673
		}
4674
4675
		$token_check = "$token_key.";
4676
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4677
			return false;
4678
		}
4679
4680
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4681
4682
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4683
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4684
			$post_data   = $_POST;
4685
			$file_hashes = array();
4686
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4687
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4688
					continue;
4689
				}
4690
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4691
				$file_hashes[$post_data_key] = $post_data_value;
4692
			}
4693
4694
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4695
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4696
				$post_data[$post_data_key] = $post_data_value;
4697
			}
4698
4699
			ksort( $post_data );
4700
4701
			$body = http_build_query( stripslashes_deep( $post_data ) );
4702
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4703
			$body = file_get_contents( 'php://input' );
4704
		} else {
4705
			$body = null;
4706
		}
4707
4708
		$signature = $jetpack_signature->sign_current_request(
4709
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4710
		);
4711
4712
		if ( ! $signature ) {
4713
			return false;
4714
		} else if ( is_wp_error( $signature ) ) {
4715
			return $signature;
4716
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4717
			return false;
4718
		}
4719
4720
		$timestamp = (int) $_GET['timestamp'];
4721
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4722
4723
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4724
			return false;
4725
		}
4726
4727
		$this->xmlrpc_verification = array(
4728
			'type'    => $token_type,
4729
			'user_id' => $token->external_user_id,
4730
		);
4731
4732
		return $this->xmlrpc_verification;
4733
	}
4734
4735
	/**
4736
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4737
	 */
4738
	function authenticate_jetpack( $user, $username, $password ) {
0 ignored issues
show
Unused Code introduced by
The parameter $username is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $password is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
4739
		if ( is_a( $user, 'WP_User' ) ) {
4740
			return $user;
4741
		}
4742
4743
		$token_details = $this->verify_xml_rpc_signature();
4744
4745
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4746
			return $user;
4747
		}
4748
4749
		if ( 'user' !== $token_details['type'] ) {
4750
			return $user;
4751
		}
4752
4753
		if ( ! $token_details['user_id'] ) {
4754
			return $user;
4755
		}
4756
4757
		nocache_headers();
4758
4759
		return new WP_User( $token_details['user_id'] );
4760
	}
4761
4762
	// Authenticates requests from Jetpack server to WP REST API endpoints.
4763
	// Uses the existing XMLRPC request signing implementation.
4764
	function wp_rest_authenticate( $error ) {
4765
		if ( is_wp_error( $error ) ) {
4766
			// A previous authentication method failed.
4767
			return $error;
4768
		}
4769
4770
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
4771
			// Nothing to do for this authentication method.
4772
			return $error;
4773
		}
4774
4775
		// Ensure that we always have the request body available.  If we don't
4776
		// do this, the signing code will try to read the request body from
4777
		// 'php://input/', but this fails in older PHP versions because the WP
4778
		// REST API code may have already read it, and this can only be done
4779
		// once prior to PHP 5.6.  The WP REST API code stores the request body
4780
		// in $HTTP_RAW_POST_DATA, so grab it from there and put it where the
4781
		// signature verification code will see it.
4782
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4783
4784
		// Only support specific request parameters that have been tested and
4785
		// are known to work with signature verification.  A different method
4786
		// can be passed to the WP REST API via the '?_method=' parameter if
4787
		// needed.
4788 View Code Duplication
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
4789
			return new WP_Error(
4790
				'rest_invalid_request',
4791
				'This request method is not supported.',
4792
				array( 'status' => 400 )
4793
			);
4794
		}
4795
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
4796
			return new WP_Error(
4797
				'rest_invalid_request',
4798
				'This request method does not support body parameters.',
4799
				array( 'status' => 400 )
4800
			);
4801
		}
4802 View Code Duplication
		if (
4803
			isset( $_SERVER['CONTENT_TYPE'] ) &&
4804
			$_SERVER['CONTENT_TYPE'] !== 'application/x-www-form-urlencoded' &&
4805
			$_SERVER['CONTENT_TYPE'] !== 'application/json'
4806
		) {
4807
			return new WP_Error(
4808
				'rest_invalid_request',
4809
				'This Content-Type is not supported.',
4810
				array( 'status' => 400 )
4811
			);
4812
		}
4813
4814
		$verified = $this->verify_xml_rpc_signature();
4815
4816
		if ( is_wp_error( $verified ) ) {
4817
			return $verified;
4818
		}
4819
4820
		if (
4821
			false === $verified ||
4822
			! isset( $verified['type'] ) ||
4823
			'user' !== $verified['type'] ||
4824
			empty( $verified['user_id'] )
4825
		) {
4826
			return new WP_Error(
4827
				'rest_invalid_signature',
4828
				'The request is not signed correctly.',
4829
				array( 'status' => 400 )
4830
			);
4831
		}
4832
4833
		// Authentication successful.
4834
		wp_set_current_user( $verified['user_id'] );
4835
		return true;
4836
	}
4837
4838
	function add_nonce( $timestamp, $nonce ) {
4839
		global $wpdb;
4840
		static $nonces_used_this_request = array();
4841
4842
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4843
			return $nonces_used_this_request["$timestamp:$nonce"];
4844
		}
4845
4846
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4847
		$timestamp = (int) $timestamp;
4848
		$nonce     = esc_sql( $nonce );
4849
4850
		// Raw query so we can avoid races: add_option will also update
4851
		$show_errors = $wpdb->show_errors( false );
4852
4853
		$old_nonce = $wpdb->get_row(
4854
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4855
		);
4856
4857
		if ( is_null( $old_nonce ) ) {
4858
			$return = $wpdb->query(
4859
				$wpdb->prepare(
4860
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4861
					"jetpack_nonce_{$timestamp}_{$nonce}",
4862
					time(),
4863
					'no'
4864
				)
4865
			);
4866
		} else {
4867
			$return = false;
4868
		}
4869
4870
		$wpdb->show_errors( $show_errors );
4871
4872
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4873
4874
		return $return;
4875
	}
4876
4877
	/**
4878
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4879
	 * Capture it here so we can verify the signature later.
4880
	 */
4881
	function xmlrpc_methods( $methods ) {
4882
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4883
		return $methods;
4884
	}
4885
4886
	function public_xmlrpc_methods( $methods ) {
4887
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4888
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4889
		}
4890
		return $methods;
4891
	}
4892
4893
	function jetpack_getOptions( $args ) {
4894
		global $wp_xmlrpc_server;
4895
4896
		$wp_xmlrpc_server->escape( $args );
4897
4898
		$username	= $args[1];
4899
		$password	= $args[2];
4900
4901
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4902
			return $wp_xmlrpc_server->error;
4903
		}
4904
4905
		$options = array();
4906
		$user_data = $this->get_connected_user_data();
4907
		if ( is_array( $user_data ) ) {
4908
			$options['jetpack_user_id'] = array(
4909
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4910
				'readonly'      => true,
4911
				'value'         => $user_data['ID'],
4912
			);
4913
			$options['jetpack_user_login'] = array(
4914
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4915
				'readonly'      => true,
4916
				'value'         => $user_data['login'],
4917
			);
4918
			$options['jetpack_user_email'] = array(
4919
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4920
				'readonly'      => true,
4921
				'value'         => $user_data['email'],
4922
			);
4923
			$options['jetpack_user_site_count'] = array(
4924
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4925
				'readonly'      => true,
4926
				'value'         => $user_data['site_count'],
4927
			);
4928
		}
4929
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4930
		$args = stripslashes_deep( $args );
4931
		return $wp_xmlrpc_server->wp_getOptions( $args );
4932
	}
4933
4934
	function xmlrpc_options( $options ) {
4935
		$jetpack_client_id = false;
4936
		if ( self::is_active() ) {
4937
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4938
		}
4939
		$options['jetpack_version'] = array(
4940
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4941
				'readonly'      => true,
4942
				'value'         => JETPACK__VERSION,
4943
		);
4944
4945
		$options['jetpack_client_id'] = array(
4946
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4947
				'readonly'      => true,
4948
				'value'         => $jetpack_client_id,
4949
		);
4950
		return $options;
4951
	}
4952
4953
	public static function clean_nonces( $all = false ) {
4954
		global $wpdb;
4955
4956
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4957
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4958
4959
		if ( true !== $all ) {
4960
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4961
			$sql_args[] = time() - 3600;
4962
		}
4963
4964
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4965
4966
		$sql = $wpdb->prepare( $sql, $sql_args );
4967
4968
		for ( $i = 0; $i < 1000; $i++ ) {
4969
			if ( ! $wpdb->query( $sql ) ) {
4970
				break;
4971
			}
4972
		}
4973
	}
4974
4975
	/**
4976
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4977
	 * SET: state( $key, $value );
4978
	 * GET: $value = state( $key );
4979
	 *
4980
	 * @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...
4981
	 * @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...
4982
	 * @param bool $restate private
4983
	 */
4984
	public static function state( $key = null, $value = null, $restate = false ) {
4985
		static $state = array();
4986
		static $path, $domain;
4987
		if ( ! isset( $path ) ) {
4988
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4989
			$admin_url = Jetpack::admin_url();
4990
			$bits      = parse_url( $admin_url );
4991
4992
			if ( is_array( $bits ) ) {
4993
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4994
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4995
			} else {
4996
				$path = $domain = null;
4997
			}
4998
		}
4999
5000
		// Extract state from cookies and delete cookies
5001
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5002
			$yum = $_COOKIE[ 'jetpackState' ];
5003
			unset( $_COOKIE[ 'jetpackState' ] );
5004
			foreach ( $yum as $k => $v ) {
5005
				if ( strlen( $v ) )
5006
					$state[ $k ] = $v;
5007
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5008
			}
5009
		}
5010
5011
		if ( $restate ) {
5012
			foreach ( $state as $k => $v ) {
5013
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5014
			}
5015
			return;
5016
		}
5017
5018
		// Get a state variable
5019
		if ( isset( $key ) && ! isset( $value ) ) {
5020
			if ( array_key_exists( $key, $state ) )
5021
				return $state[ $key ];
5022
			return null;
5023
		}
5024
5025
		// Set a state variable
5026
		if ( isset ( $key ) && isset( $value ) ) {
5027
			if( is_array( $value ) && isset( $value[0] ) ) {
5028
				$value = $value[0];
5029
			}
5030
			$state[ $key ] = $value;
5031
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5032
		}
5033
	}
5034
5035
	public static function restate() {
5036
		Jetpack::state( null, null, true );
5037
	}
5038
5039
	public static function check_privacy( $file ) {
5040
		static $is_site_publicly_accessible = null;
5041
5042
		if ( is_null( $is_site_publicly_accessible ) ) {
5043
			$is_site_publicly_accessible = false;
5044
5045
			Jetpack::load_xml_rpc_client();
5046
			$rpc = new Jetpack_IXR_Client();
5047
5048
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5049
			if ( $success ) {
5050
				$response = $rpc->getResponse();
5051
				if ( $response ) {
5052
					$is_site_publicly_accessible = true;
5053
				}
5054
			}
5055
5056
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5057
		}
5058
5059
		if ( $is_site_publicly_accessible ) {
5060
			return;
5061
		}
5062
5063
		$module_slug = self::get_module_slug( $file );
5064
5065
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5066
		if ( ! $privacy_checks ) {
5067
			$privacy_checks = $module_slug;
5068
		} else {
5069
			$privacy_checks .= ",$module_slug";
5070
		}
5071
5072
		Jetpack::state( 'privacy_checks', $privacy_checks );
5073
	}
5074
5075
	/**
5076
	 * Helper method for multicall XMLRPC.
5077
	 */
5078
	public static function xmlrpc_async_call() {
5079
		global $blog_id;
5080
		static $clients = array();
5081
5082
		$client_blog_id = is_multisite() ? $blog_id : 0;
5083
5084
		if ( ! isset( $clients[$client_blog_id] ) ) {
5085
			Jetpack::load_xml_rpc_client();
5086
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5087
			if ( function_exists( 'ignore_user_abort' ) ) {
5088
				ignore_user_abort( true );
5089
			}
5090
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5091
		}
5092
5093
		$args = func_get_args();
5094
5095
		if ( ! empty( $args[0] ) ) {
5096
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5097
		} elseif ( is_multisite() ) {
5098
			foreach ( $clients as $client_blog_id => $client ) {
5099
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5100
					continue;
5101
				}
5102
5103
				$switch_success = switch_to_blog( $client_blog_id, true );
5104
				if ( ! $switch_success ) {
5105
					continue;
5106
				}
5107
5108
				flush();
5109
				$client->query();
5110
5111
				restore_current_blog();
5112
			}
5113
		} else {
5114
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5115
				flush();
5116
				$clients[0]->query();
5117
			}
5118
		}
5119
	}
5120
5121
	public static function staticize_subdomain( $url ) {
5122
5123
		// Extract hostname from URL
5124
		$host = parse_url( $url, PHP_URL_HOST );
5125
5126
		// Explode hostname on '.'
5127
		$exploded_host = explode( '.', $host );
5128
5129
		// Retrieve the name and TLD
5130
		if ( count( $exploded_host ) > 1 ) {
5131
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5132
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5133
			// Rebuild domain excluding subdomains
5134
			$domain = $name . '.' . $tld;
5135
		} else {
5136
			$domain = $host;
5137
		}
5138
		// Array of Automattic domains
5139
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5140
5141
		// Return $url if not an Automattic domain
5142
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5143
			return $url;
5144
		}
5145
5146
		if ( is_ssl() ) {
5147
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5148
		}
5149
5150
		srand( crc32( basename( $url ) ) );
5151
		$static_counter = rand( 0, 2 );
5152
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5153
5154
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5155
	}
5156
5157
/* JSON API Authorization */
5158
5159
	/**
5160
	 * Handles the login action for Authorizing the JSON API
5161
	 */
5162
	function login_form_json_api_authorization() {
5163
		$this->verify_json_api_authorization_request();
5164
5165
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5166
5167
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5168
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5169
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5170
	}
5171
5172
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5173
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5174
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5175
			return $url;
5176
		}
5177
5178
		$parsed_url = parse_url( $url );
5179
		$url = strtok( $url, '?' );
5180
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5181
		if ( ! empty( $parsed_url['query'] ) )
5182
			$url .= "&{$parsed_url['query']}";
5183
5184
		return $url;
5185
	}
5186
5187
	// Make sure the POSTed request is handled by the same action
5188
	function preserve_action_in_login_form_for_json_api_authorization() {
5189
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5190
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5191
	}
5192
5193
	// If someone logs in to approve API access, store the Access Code in usermeta
5194
	function store_json_api_authorization_token( $user_login, $user ) {
5195
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5196
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5197
		$token = wp_generate_password( 32, false );
5198
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5199
	}
5200
5201
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5202
	function allow_wpcom_public_api_domain( $domains ) {
5203
		$domains[] = 'public-api.wordpress.com';
5204
		return $domains;
5205
	}
5206
5207
	// Add the Access Code details to the public-api.wordpress.com redirect
5208
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5209
		return add_query_arg(
5210
			urlencode_deep(
5211
				array(
5212
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5213
					'jetpack-user-id' => (int) $user->ID,
5214
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5215
				)
5216
			),
5217
			$redirect_to
5218
		);
5219
	}
5220
5221
	// Verifies the request by checking the signature
5222
	function verify_json_api_authorization_request() {
5223
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5224
5225
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5226
		if ( ! $token || empty( $token->secret ) ) {
5227
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5228
		}
5229
5230
		$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' );
5231
5232
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5233
5234
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5235
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5236
		} else {
5237
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5238
		}
5239
5240
		if ( ! $signature ) {
5241
			wp_die( $die_error );
5242
		} else if ( is_wp_error( $signature ) ) {
5243
			wp_die( $die_error );
5244
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5245
			if ( is_ssl() ) {
5246
				// 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
5247
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5248
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $_GET['signature'] ) ) {
5249
					wp_die( $die_error );
5250
				}
5251
			} else {
5252
				wp_die( $die_error );
5253
			}
5254
		}
5255
5256
		$timestamp = (int) $_GET['timestamp'];
5257
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5258
5259
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5260
			// De-nonce the nonce, at least for 5 minutes.
5261
			// 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)
5262
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5263
			if ( $old_nonce_time < time() - 300 ) {
5264
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5265
			}
5266
		}
5267
5268
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5269
		$data_filters = array(
5270
			'state'        => 'opaque',
5271
			'client_id'    => 'int',
5272
			'client_title' => 'string',
5273
			'client_image' => 'url',
5274
		);
5275
5276
		foreach ( $data_filters as $key => $sanitation ) {
5277
			if ( ! isset( $data->$key ) ) {
5278
				wp_die( $die_error );
5279
			}
5280
5281
			switch ( $sanitation ) {
5282
			case 'int' :
5283
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5284
				break;
5285
			case 'opaque' :
5286
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5287
				break;
5288
			case 'string' :
5289
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5290
				break;
5291
			case 'url' :
5292
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5293
				break;
5294
			}
5295
		}
5296
5297
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5298
			wp_die( $die_error );
5299
		}
5300
	}
5301
5302
	function login_message_json_api_authorization( $message ) {
0 ignored issues
show
Unused Code introduced by
The parameter $message is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5303
		return '<p class="message">' . sprintf(
5304
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5305
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5306
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5307
	}
5308
5309
	/**
5310
	 * Get $content_width, but with a <s>twist</s> filter.
5311
	 */
5312
	public static function get_content_width() {
5313
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5314
		/**
5315
		 * Filter the Content Width value.
5316
		 *
5317
		 * @since 2.2.3
5318
		 *
5319
		 * @param string $content_width Content Width value.
5320
		 */
5321
		return apply_filters( 'jetpack_content_width', $content_width );
5322
	}
5323
5324
	/**
5325
	 * Centralize the function here until it gets added to core.
5326
	 *
5327
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5328
	 * @param int $size Size of the avatar image
5329
	 * @param string $default URL to a default image to use if no avatar is available
5330
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5331
	 *
5332
	 * @return array First element is the URL, second is the class.
5333
	 */
5334
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5335
		// Don't bother adding the __return_true filter if it's already there.
5336
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5337
5338
		if ( $force_display && ! $has_filter )
5339
			add_filter( 'pre_option_show_avatars', '__return_true' );
5340
5341
		$avatar = get_avatar( $id_or_email, $size, $default );
5342
5343
		if ( $force_display && ! $has_filter )
5344
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5345
5346
		// If no data, fail out.
5347
		if ( is_wp_error( $avatar ) || ! $avatar )
5348
			return array( null, null );
5349
5350
		// Pull out the URL.  If it's not there, fail out.
5351
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5352
			return array( null, null );
5353
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5354
5355
		// Pull out the class, but it's not a big deal if it's missing.
5356
		$class = '';
5357
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5358
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5359
5360
		return array( $url, $class );
5361
	}
5362
5363
	/**
5364
	 * Pings the WordPress.com Mirror Site for the specified options.
5365
	 *
5366
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5367
	 *
5368
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5369
	 */
5370
	public function get_cloud_site_options( $option_names ) {
5371
		$option_names = array_filter( (array) $option_names, 'is_string' );
5372
5373
		Jetpack::load_xml_rpc_client();
5374
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5375
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5376
		if ( $xml->isError() ) {
5377
			return array(
5378
				'error_code' => $xml->getErrorCode(),
5379
				'error_msg'  => $xml->getErrorMessage(),
5380
			);
5381
		}
5382
		$cloud_site_options = $xml->getResponse();
5383
5384
		return $cloud_site_options;
5385
	}
5386
5387
	/**
5388
	 * Checks if the site is currently in an identity crisis.
5389
	 *
5390
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5391
	 */
5392
	public static function check_identity_crisis() {
5393
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5394
			return false;
5395
		}
5396
5397
		return Jetpack_Options::get_option( 'sync_error_idc' );
5398
	}
5399
5400
	/**
5401
	 * Checks whether the home and siteurl specifically are whitelisted
5402
	 * Written so that we don't have re-check $key and $value params every time
5403
	 * we want to check if this site is whitelisted, for example in footer.php
5404
	 *
5405
	 * @since  3.8.0
5406
	 * @return bool True = already whitelisted False = not whitelisted
5407
	 */
5408
	public static function is_staging_site() {
5409
		$is_staging = false;
5410
5411
		$known_staging = array(
5412
			'urls' => array(
5413
				'#\.staging\.wpengine\.com$#i', // WP Engine
5414
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5415
				),
5416
			'constants' => array(
5417
				'IS_WPE_SNAPSHOT',      // WP Engine
5418
				'KINSTA_DEV_ENV',       // Kinsta.com
5419
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5420
				'JETPACK_STAGING_MODE', // Generic
5421
				)
5422
			);
5423
		/**
5424
		 * Filters the flags of known staging sites.
5425
		 *
5426
		 * @since 3.9.0
5427
		 *
5428
		 * @param array $known_staging {
5429
		 *     An array of arrays that each are used to check if the current site is staging.
5430
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5431
		 *     @type array $constants PHP constants of known staging/developement environments.
5432
		 *  }
5433
		 */
5434
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5435
5436
		if ( isset( $known_staging['urls'] ) ) {
5437
			foreach ( $known_staging['urls'] as $url ){
5438
				if ( preg_match( $url, site_url() ) ) {
5439
					$is_staging = true;
5440
					break;
5441
				}
5442
			}
5443
		}
5444
5445
		if ( isset( $known_staging['constants'] ) ) {
5446
			foreach ( $known_staging['constants'] as $constant ) {
5447
				if ( defined( $constant ) && constant( $constant ) ) {
5448
					$is_staging = true;
5449
				}
5450
			}
5451
		}
5452
5453
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5454
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5455
			$is_staging = true;
5456
		}
5457
5458
		/**
5459
		 * Filters is_staging_site check.
5460
		 *
5461
		 * @since 3.9.0
5462
		 *
5463
		 * @param bool $is_staging If the current site is a staging site.
5464
		 */
5465
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5466
	}
5467
5468
	/**
5469
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5470
	 *
5471
	 * @return bool
5472
	 */
5473
	public static function validate_sync_error_idc_option() {
5474
		$is_valid = false;
5475
5476
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5477
		if ( false === $idc_allowed ) {
5478
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5479
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5480
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5481
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5482
				$transient_duration = HOUR_IN_SECONDS;
5483
			} else {
5484
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5485
				$idc_allowed = '1';
5486
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5487
			}
5488
5489
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5490
		}
5491
5492
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5493
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5494
		$local_options = self::get_sync_error_idc_option();
5495
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5496
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5497
				$is_valid = true;
5498
			}
5499
		}
5500
5501
		/**
5502
		 * Filters whether the sync_error_idc option is valid.
5503
		 *
5504
		 * @since 4.4.0
5505
		 *
5506
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5507
		 */
5508
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5509
5510
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5511
			// Since the option exists, and did not validate, delete it
5512
			Jetpack_Options::delete_option( 'sync_error_idc' );
5513
		}
5514
5515
		return $is_valid;
5516
	}
5517
5518
	/**
5519
	 * Normalizes a url by doing three things:
5520
	 *  - Strips protocol
5521
	 *  - Strips www
5522
	 *  - Adds a trailing slash
5523
	 *
5524
	 * @since 4.4.0
5525
	 * @param string $url
5526
	 * @return WP_Error|string
5527
	 */
5528
	public static function normalize_url_protocol_agnostic( $url ) {
5529
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5530
		if ( ! $parsed_url ) {
5531
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5532
		}
5533
5534
		// Strip www and protocols
5535
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5536
		return $url;
5537
	}
5538
5539
	/**
5540
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5541
	 *
5542
	 * @since 4.4.0
5543
	 *
5544
	 * @param array $response
5545
	 * @return array Array of the local urls, wpcom urls, and error code
5546
	 */
5547
	public static function get_sync_error_idc_option( $response = array() ) {
5548
		$local_options = array(
5549
			'home' => get_home_url(),
5550
			'siteurl' => get_site_url(),
5551
		);
5552
5553
		$options = array_merge( $local_options, $response );
5554
5555
		$returned_values = array();
5556
		foreach( $options as $key => $option ) {
5557
			if ( 'error_code' === $key ) {
5558
				$returned_values[ $key ] = $option;
5559
				continue;
5560
			}
5561
5562
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5563
				continue;
5564
			}
5565
5566
			$returned_values[ $key ] = $normalized_url;
5567
		}
5568
5569
		return $returned_values;
5570
	}
5571
5572
	/**
5573
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5574
	 * If set to true, the site will be put into staging mode.
5575
	 *
5576
	 * @since 4.3.2
5577
	 * @return bool
5578
	 */
5579
	public static function sync_idc_optin() {
5580
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5581
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5582
		} else {
5583
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5584
		}
5585
5586
		/**
5587
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5588
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5589
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5590
		 *
5591
		 * @since 4.3.2
5592
		 *
5593
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5594
		 */
5595
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5596
	}
5597
5598
	/**
5599
	 * Maybe Use a .min.css stylesheet, maybe not.
5600
	 *
5601
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5602
	 */
5603
	public static function maybe_min_asset( $url, $path, $plugin ) {
5604
		// Short out on things trying to find actual paths.
5605
		if ( ! $path || empty( $plugin ) ) {
5606
			return $url;
5607
		}
5608
5609
		// Strip out the abspath.
5610
		$base = dirname( plugin_basename( $plugin ) );
5611
5612
		// Short out on non-Jetpack assets.
5613
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5614
			return $url;
5615
		}
5616
5617
		// File name parsing.
5618
		$file              = "{$base}/{$path}";
5619
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5620
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5621
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5622
		$extension         = array_shift( $file_name_parts_r );
5623
5624
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5625
			// Already pointing at the minified version.
5626
			if ( 'min' === $file_name_parts_r[0] ) {
5627
				return $url;
5628
			}
5629
5630
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5631
			if ( file_exists( $min_full_path ) ) {
5632
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5633
			}
5634
		}
5635
5636
		return $url;
5637
	}
5638
5639
	/**
5640
	 * Maybe inlines a stylesheet.
5641
	 *
5642
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5643
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5644
	 *
5645
	 * Attached to `style_loader_tag` filter.
5646
	 *
5647
	 * @param string $tag The tag that would link to the external asset.
5648
	 * @param string $handle The registered handle of the script in question.
5649
	 *
5650
	 * @return string
5651
	 */
5652
	public static function maybe_inline_style( $tag, $handle ) {
5653
		global $wp_styles;
5654
		$item = $wp_styles->registered[ $handle ];
5655
5656
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5657
			return $tag;
5658
		}
5659
5660
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5661
			$href = $matches[1];
5662
			// Strip off query string
5663
			if ( $pos = strpos( $href, '?' ) ) {
5664
				$href = substr( $href, 0, $pos );
5665
			}
5666
			// Strip off fragment
5667
			if ( $pos = strpos( $href, '#' ) ) {
5668
				$href = substr( $href, 0, $pos );
5669
			}
5670
		} else {
5671
			return $tag;
5672
		}
5673
5674
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5675
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5676
			return $tag;
5677
		}
5678
5679
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5680
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5681
			// And this isn't the pass that actually deals with the RTL version...
5682
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5683
				// Short out, as the RTL version will deal with it in a moment.
5684
				return $tag;
5685
			}
5686
		}
5687
5688
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5689
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5690
		if ( $css ) {
5691
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5692
			if ( empty( $item->extra['after'] ) ) {
5693
				wp_add_inline_style( $handle, $css );
5694
			} else {
5695
				array_unshift( $item->extra['after'], $css );
5696
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5697
			}
5698
		}
5699
5700
		return $tag;
5701
	}
5702
5703
	/**
5704
	 * Loads a view file from the views
5705
	 *
5706
	 * Data passed in with the $data parameter will be available in the
5707
	 * template file as $data['value']
5708
	 *
5709
	 * @param string $template - Template file to load
5710
	 * @param array $data - Any data to pass along to the template
5711
	 * @return boolean - If template file was found
5712
	 **/
5713
	public function load_view( $template, $data = array() ) {
5714
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5715
5716
		if( file_exists( $views_dir . $template ) ) {
5717
			require_once( $views_dir . $template );
5718
			return true;
5719
		}
5720
5721
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5722
		return false;
5723
	}
5724
5725
	/**
5726
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5727
	 */
5728
	public function deprecated_hooks() {
5729
		global $wp_filter;
5730
5731
		/*
5732
		 * Format:
5733
		 * deprecated_filter_name => replacement_name
5734
		 *
5735
		 * If there is no replacement, use null for replacement_name
5736
		 */
5737
		$deprecated_list = array(
5738
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5739
			'wpl_sharing_2014_1'                                     => null,
5740
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5741
			'jetpack_identity_crisis_options_to_check'               => null,
5742
			'update_option_jetpack_single_user_site'                 => null,
5743
			'audio_player_default_colors'                            => null,
5744
			'add_option_jetpack_featured_images_enabled'             => null,
5745
			'add_option_jetpack_update_details'                      => null,
5746
			'add_option_jetpack_updates'                             => null,
5747
			'add_option_jetpack_network_name'                        => null,
5748
			'add_option_jetpack_network_allow_new_registrations'     => null,
5749
			'add_option_jetpack_network_add_new_users'               => null,
5750
			'add_option_jetpack_network_site_upload_space'           => null,
5751
			'add_option_jetpack_network_upload_file_types'           => null,
5752
			'add_option_jetpack_network_enable_administration_menus' => null,
5753
			'add_option_jetpack_is_multi_site'                       => null,
5754
			'add_option_jetpack_is_main_network'                     => null,
5755
			'add_option_jetpack_main_network_site'                   => null,
5756
			'jetpack_sync_all_registered_options'                    => null,
5757
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5758
			'jetpack_is_post_mailable'                               => null,
5759
		);
5760
5761
		// This is a silly loop depth. Better way?
5762
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5763
			if ( has_action( $hook ) ) {
5764
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
5765
					foreach( $values AS $hooked ) {
5766
						if ( is_callable( $hooked['function'] ) ) {
5767
							$function_name = 'an anonymous function';
5768
						} else {
5769
							$function_name = $hooked['function'];
5770
						}
5771
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
5772
					}
5773
				}
5774
			}
5775
		}
5776
	}
5777
5778
	/**
5779
	 * Converts any url in a stylesheet, to the correct absolute url.
5780
	 *
5781
	 * Considerations:
5782
	 *  - Normal, relative URLs     `feh.png`
5783
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5784
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5785
	 *  - Absolute URLs             `http://domain.com/feh.png`
5786
	 *  - Domain root relative URLs `/feh.png`
5787
	 *
5788
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5789
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5790
	 *
5791
	 * @return mixed|string
5792
	 */
5793
	public static function absolutize_css_urls( $css, $css_file_url ) {
5794
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5795
		$css_dir = dirname( $css_file_url );
5796
		$p       = parse_url( $css_dir );
5797
		$domain  = sprintf(
5798
					'%1$s//%2$s%3$s%4$s',
5799
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5800
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5801
					$p['host'],
5802
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5803
				);
5804
5805
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5806
			$find = $replace = array();
5807
			foreach ( $matches as $match ) {
5808
				$url = trim( $match['path'], "'\" \t" );
5809
5810
				// If this is a data url, we don't want to mess with it.
5811
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5812
					continue;
5813
				}
5814
5815
				// If this is an absolute or protocol-agnostic url,
5816
				// we don't want to mess with it.
5817
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5818
					continue;
5819
				}
5820
5821
				switch ( substr( $url, 0, 1 ) ) {
5822
					case '/':
5823
						$absolute = $domain . $url;
5824
						break;
5825
					default:
5826
						$absolute = $css_dir . '/' . $url;
5827
				}
5828
5829
				$find[]    = $match[0];
5830
				$replace[] = sprintf( 'url("%s")', $absolute );
5831
			}
5832
			$css = str_replace( $find, $replace, $css );
5833
		}
5834
5835
		return $css;
5836
	}
5837
5838
	/**
5839
	 * This methods removes all of the registered css files on the front end
5840
	 * from Jetpack in favor of using a single file. In effect "imploding"
5841
	 * all the files into one file.
5842
	 *
5843
	 * Pros:
5844
	 * - Uses only ONE css asset connection instead of 15
5845
	 * - Saves a minimum of 56k
5846
	 * - Reduces server load
5847
	 * - Reduces time to first painted byte
5848
	 *
5849
	 * Cons:
5850
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5851
	 *		should not cause any issues with themes.
5852
	 * - Plugins/themes dequeuing styles no longer do anything. See
5853
	 *		jetpack_implode_frontend_css filter for a workaround
5854
	 *
5855
	 * For some situations developers may wish to disable css imploding and
5856
	 * instead operate in legacy mode where each file loads seperately and
5857
	 * can be edited individually or dequeued. This can be accomplished with
5858
	 * the following line:
5859
	 *
5860
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5861
	 *
5862
	 * @since 3.2
5863
	 **/
5864
	public function implode_frontend_css( $travis_test = false ) {
5865
		$do_implode = true;
5866
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5867
			$do_implode = false;
5868
		}
5869
5870
		/**
5871
		 * Allow CSS to be concatenated into a single jetpack.css file.
5872
		 *
5873
		 * @since 3.2.0
5874
		 *
5875
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5876
		 */
5877
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5878
5879
		// Do not use the imploded file when default behaviour was altered through the filter
5880
		if ( ! $do_implode ) {
5881
			return;
5882
		}
5883
5884
		// We do not want to use the imploded file in dev mode, or if not connected
5885
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5886
			if ( ! $travis_test ) {
5887
				return;
5888
			}
5889
		}
5890
5891
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5892
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5893
			return;
5894
		}
5895
5896
		/*
5897
		 * Now we assume Jetpack is connected and able to serve the single
5898
		 * file.
5899
		 *
5900
		 * In the future there will be a check here to serve the file locally
5901
		 * or potentially from the Jetpack CDN
5902
		 *
5903
		 * For now:
5904
		 * - Enqueue a single imploded css file
5905
		 * - Zero out the style_loader_tag for the bundled ones
5906
		 * - Be happy, drink scotch
5907
		 */
5908
5909
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5910
5911
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5912
5913
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5914
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5915
	}
5916
5917
	function concat_remove_style_loader_tag( $tag, $handle ) {
5918
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5919
			$tag = '';
5920
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5921
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5922
			}
5923
		}
5924
5925
		return $tag;
5926
	}
5927
5928
	/*
5929
	 * Check the heartbeat data
5930
	 *
5931
	 * Organizes the heartbeat data by severity.  For example, if the site
5932
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5933
	 *
5934
	 * Data will be added to "caution" array, if it either:
5935
	 *  - Out of date Jetpack version
5936
	 *  - Out of date WP version
5937
	 *  - Out of date PHP version
5938
	 *
5939
	 * $return array $filtered_data
5940
	 */
5941
	public static function jetpack_check_heartbeat_data() {
5942
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5943
5944
		$good    = array();
5945
		$caution = array();
5946
		$bad     = array();
5947
5948
		foreach ( $raw_data as $stat => $value ) {
5949
5950
			// Check jetpack version
5951
			if ( 'version' == $stat ) {
5952
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5953
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5954
					continue;
5955
				}
5956
			}
5957
5958
			// Check WP version
5959
			if ( 'wp-version' == $stat ) {
5960
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5961
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5962
					continue;
5963
				}
5964
			}
5965
5966
			// Check PHP version
5967
			if ( 'php-version' == $stat ) {
5968
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5969
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5970
					continue;
5971
				}
5972
			}
5973
5974
			// Check ID crisis
5975
			if ( 'identitycrisis' == $stat ) {
5976
				if ( 'yes' == $value ) {
5977
					$bad[ $stat ] = $value;
5978
					continue;
5979
				}
5980
			}
5981
5982
			// The rest are good :)
5983
			$good[ $stat ] = $value;
5984
		}
5985
5986
		$filtered_data = array(
5987
			'good'    => $good,
5988
			'caution' => $caution,
5989
			'bad'     => $bad
5990
		);
5991
5992
		return $filtered_data;
5993
	}
5994
5995
5996
	/*
5997
	 * This method is used to organize all options that can be reset
5998
	 * without disconnecting Jetpack.
5999
	 *
6000
	 * It is used in class.jetpack-cli.php to reset options
6001
	 *
6002
	 * @return array of options to delete.
6003
	 */
6004
	public static function get_jetpack_options_for_reset() {
6005
		$jetpack_options            = Jetpack_Options::get_option_names();
6006
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6007
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6008
6009
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6010
6011
		// A manual build of the wp options
6012
		$wp_options = array(
6013
			'sharing-options',
6014
			'disabled_likes',
6015
			'disabled_reblogs',
6016
			'jetpack_comments_likes_enabled',
6017
			'wp_mobile_excerpt',
6018
			'wp_mobile_featured_images',
6019
			'wp_mobile_app_promos',
6020
			'stats_options',
6021
			'stats_dashboard_widget',
6022
			'safecss_preview_rev',
6023
			'safecss_rev',
6024
			'safecss_revision_migrated',
6025
			'nova_menu_order',
6026
			'jetpack_portfolio',
6027
			'jetpack_portfolio_posts_per_page',
6028
			'jetpack_testimonial',
6029
			'jetpack_testimonial_posts_per_page',
6030
			'wp_mobile_custom_css',
6031
			'sharedaddy_disable_resources',
6032
			'sharing-options',
6033
			'sharing-services',
6034
			'site_icon_temp_data',
6035
			'featured-content',
6036
			'site_logo',
6037
			'jetpack_dismissed_notices',
6038
		);
6039
6040
		// Flag some Jetpack options as unsafe
6041
		$unsafe_options = array(
6042
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6043
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6044
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6045
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6046
6047
			// non_compact
6048
			'activated',
6049
6050
			// private
6051
			'register',
6052
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6053
			'user_token',                  // (string) The User Token of this site. (deprecated)
6054
			'user_tokens'
6055
		);
6056
6057
		// Remove the unsafe Jetpack options
6058
		foreach ( $unsafe_options as $unsafe_option ) {
6059
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6060
				unset( $all_jp_options[ $key ] );
6061
			}
6062
		}
6063
6064
		$options = array(
6065
			'jp_options' => $all_jp_options,
6066
			'wp_options' => $wp_options
6067
		);
6068
6069
		return $options;
6070
	}
6071
6072
	/**
6073
	 * Check if an option of a Jetpack module has been updated.
6074
	 *
6075
	 * If any module option has been updated before Jump Start has been dismissed,
6076
	 * update the 'jumpstart' option so we can hide Jump Start.
6077
	 *
6078
	 * @param string $option_name
6079
	 *
6080
	 * @return bool
6081
	 */
6082
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6083
		// Bail if Jump Start has already been dismissed
6084
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6085
			return false;
6086
		}
6087
6088
		$jetpack = Jetpack::init();
6089
6090
		// Manual build of module options
6091
		$option_names = self::get_jetpack_options_for_reset();
6092
6093
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6094
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6095
6096
			//Jump start is being dismissed send data to MC Stats
6097
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6098
6099
			$jetpack->do_stats( 'server_side' );
6100
		}
6101
6102
	}
6103
6104
	/*
6105
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6106
	 * so we can bring them directly to their site in calypso.
6107
	 *
6108
	 * @param string | url
6109
	 * @return string | url without the guff
6110
	 */
6111
	public static function build_raw_urls( $url ) {
6112
		$strip_http = '/.*?:\/\//i';
6113
		$url = preg_replace( $strip_http, '', $url  );
6114
		$url = str_replace( '/', '::', $url );
6115
		return $url;
6116
	}
6117
6118
	/**
6119
	 * Stores and prints out domains to prefetch for page speed optimization.
6120
	 *
6121
	 * @param mixed $new_urls
6122
	 */
6123
	public static function dns_prefetch( $new_urls = null ) {
6124
		static $prefetch_urls = array();
6125
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6126
			echo "\r\n";
6127
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6128
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6129
			}
6130
		} elseif ( ! empty( $new_urls ) ) {
6131
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6132
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6133
			}
6134
			foreach ( (array) $new_urls as $this_new_url ) {
6135
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6136
			}
6137
			$prefetch_urls = array_unique( $prefetch_urls );
6138
		}
6139
	}
6140
6141
	public function wp_dashboard_setup() {
6142
		if ( self::is_active() ) {
6143
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6144
			$widget_title = __( 'Site Stats', 'jetpack' );
6145
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6146
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6147
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6148
		}
6149
6150
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6151
			wp_add_dashboard_widget(
6152
				'jetpack_summary_widget',
6153
				$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...
6154
				array( __CLASS__, 'dashboard_widget' )
6155
			);
6156
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6157
6158
			// If we're inactive and not in development mode, sort our box to the top.
6159
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6160
				global $wp_meta_boxes;
6161
6162
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6163
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6164
6165
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6166
			}
6167
		}
6168
	}
6169
6170
	/**
6171
	 * @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...
6172
	 * @return mixed
6173
	 */
6174
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6175
		if ( ! is_array( $sorted ) ) {
6176
			return $sorted;
6177
		}
6178
6179
		foreach ( $sorted as $box_context => $ids ) {
6180
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6181
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6182
				continue;
6183
			}
6184
6185
			$ids_array = explode( ',', $ids );
6186
			$key = array_search( 'dashboard_stats', $ids_array );
6187
6188
			if ( false !== $key ) {
6189
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6190
				$ids_array[ $key ] = 'jetpack_summary_widget';
6191
				$sorted[ $box_context ] = implode( ',', $ids_array );
6192
				// We've found it, stop searching, and just return.
6193
				break;
6194
			}
6195
		}
6196
6197
		return $sorted;
6198
	}
6199
6200
	public static function dashboard_widget() {
6201
		/**
6202
		 * Fires when the dashboard is loaded.
6203
		 *
6204
		 * @since 3.4.0
6205
		 */
6206
		do_action( 'jetpack_dashboard_widget' );
6207
	}
6208
6209
	public static function dashboard_widget_footer() {
6210
		?>
6211
		<footer>
6212
6213
		<div class="protect">
6214
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6215
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6216
				<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>
6217
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6218
				<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' ); ?>">
6219
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6220
				</a>
6221
			<?php else : ?>
6222
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6223
			<?php endif; ?>
6224
		</div>
6225
6226
		<div class="akismet">
6227
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6228
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6229
				<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>
6230
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6231
				<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">
6232
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6233
				</a>
6234
			<?php else : ?>
6235
				<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>
6236
			<?php endif; ?>
6237
		</div>
6238
6239
		</footer>
6240
		<?php
6241
	}
6242
6243
	public function dashboard_widget_connect_to_wpcom() {
6244
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6245
			return;
6246
		}
6247
		?>
6248
		<div class="wpcom-connect">
6249
			<div class="jp-emblem">
6250
			<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">
6251
				<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"/>
6252
			</svg>
6253
			</div>
6254
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6255
			<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>
6256
6257
			<div class="actions">
6258
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6259
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6260
				</a>
6261
			</div>
6262
		</div>
6263
		<?php
6264
	}
6265
6266
	/**
6267
	 * Return string containing the Jetpack logo.
6268
	 *
6269
	 * @since 3.9.0
6270
	 *
6271
	 * @return string
6272
	 */
6273
	public static function get_jp_emblem() {
6274
		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" 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>';
6275
	}
6276
6277
	/*
6278
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6279
	 */
6280
	function jetpack_icon_user_connected( $columns ) {
6281
		$columns['user_jetpack'] = '';
6282
		return $columns;
6283
	}
6284
6285
	/*
6286
	 * Show Jetpack icon if the user is linked.
6287
	 */
6288
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6289
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6290
			$emblem_html = sprintf(
6291
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6292
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6293
				Jetpack::get_jp_emblem()
6294
			);
6295
			return $emblem_html;
6296
		}
6297
6298
		return $val;
6299
	}
6300
6301
	/*
6302
	 * Style the Jetpack user column
6303
	 */
6304
	function jetpack_user_col_style() {
6305
		global $current_screen;
6306
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6307
			<style>
6308
				.fixed .column-user_jetpack {
6309
					width: 21px;
6310
				}
6311
				.jp-emblem-user-admin svg {
6312
					width: 20px;
6313
					height: 20px;
6314
				}
6315
				.jp-emblem-user-admin path {
6316
					fill: #8cc258;
6317
				}
6318
			</style>
6319
		<?php }
6320
	}
6321
}
6322