Completed
Push — fix/markdown-auto-enable ( 3fb4e3...c54efb )
by
unknown
28:20 queued 19:51
created

Jetpack::bail_on_activation()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 40
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 3
nop 2
dl 0
loc 40
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
	);
60
61
	public $plugins_to_deactivate = array(
62
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
63
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
64
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
65
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
66
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
67
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
68
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
69
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
70
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
71
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
72
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
73
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
74
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
75
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
76
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
77
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
78
	);
79
80
	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...
81
		'administrator' => 'manage_options',
82
		'editor'        => 'edit_others_posts',
83
		'author'        => 'publish_posts',
84
		'contributor'   => 'edit_posts',
85
		'subscriber'    => 'read',
86
	);
87
88
	/**
89
	 * Map of modules that have conflicts with plugins and should not be auto-activated
90
	 * if the plugins are active.  Used by filter_default_modules
91
	 *
92
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
93
	 * change `module-slug` and add this to your plugin:
94
	 *
95
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
96
	 * function my_jetpack_get_default_modules( $modules ) {
97
	 *     return array_diff( $modules, array( 'module-slug' ) );
98
	 * }
99
	 *
100
	 * @var array
101
	 */
102
	private $conflicting_plugins = array(
103
		'comments'          => array(
104
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
105
			'Disqus'                               => 'disqus-comment-system/disqus.php',
106
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
107
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
108
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
109
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
110
		),
111
		'contact-form'      => array(
112
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
113
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
114
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
115
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
116
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
117
		),
118
		'minileven'         => array(
119
			'WPtouch'                              => 'wptouch/wptouch.php',
120
		),
121
		'latex'             => array(
122
			'LaTeX for WordPress'                  => 'latex/latex.php',
123
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
124
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
125
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
126
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
127
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
128
		),
129
		'protect'           => array(
130
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
131
			'Captcha'                              => 'captcha/captcha.php',
132
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
133
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
134
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
135
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
136
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
137
			'Security-protection'                  => 'security-protection/security-protection.php',
138
			'Login Security'                       => 'login-security/login-security.php',
139
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
140
			'Wordfence Security'                   => 'wordfence/wordfence.php',
141
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
142
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
143
		),
144
		'random-redirect'   => array(
145
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
146
		),
147
		'related-posts'     => array(
148
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
149
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
150
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
151
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
152
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
153
			'outbrain'                             => 'outbrain/outbrain.php',
154
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
155
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
156
		),
157
		'sharedaddy'        => array(
158
			'AddThis'                              => 'addthis/addthis_social_widget.php',
159
			'Add To Any'                           => 'add-to-any/add-to-any.php',
160
			'ShareThis'                            => 'share-this/sharethis.php',
161
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
162
		),
163
		'seo-tools' => array(
164
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
165
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
166
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
167
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
168
		),
169
		'verification-tools' => array(
170
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
171
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
172
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
173
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
174
		),
175
		'widget-visibility' => array(
176
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
177
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
178
		),
179
		'sitemaps' => array(
180
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
181
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
182
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
183
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
184
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
185
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
186
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
187
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
188
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
189
			'Sitemap'                              => 'sitemap/sitemap.php',
190
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
191
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
192
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
193
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
194
		),
195
	);
196
197
	/**
198
	 * Plugins for which we turn off our Facebook OG Tags implementation.
199
	 *
200
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
201
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
202
	 *
203
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
204
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
205
	 */
206
	private $open_graph_conflicting_plugins = array(
207
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
208
		                                                         // 2 Click Social Media Buttons
209
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
210
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
211
		'autodescription/autodescription.php',                   // The SEO Framework
212
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
213
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
214
		                                                         // Open Graph Meta Tags by Heateor
215
		'facebook/facebook.php',                                 // Facebook (official plugin)
216
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
217
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
218
		                                                         // Facebook Featured Image & OG Meta Tags
219
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
220
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
221
		                                                         // Facebook Open Graph Meta Tags for WordPress
222
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
223
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
224
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
225
		                                                         // Fedmich's Facebook Open Graph Meta
226
		'header-footer/plugin.php',                              // Header and Footer
227
		'network-publisher/networkpub.php',                      // Network Publisher
228
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
229
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
230
		                                                         // NextScripts SNAP
231
		'og-tags/og-tags.php',                                   // OG Tags
232
		'opengraph/opengraph.php',                               // Open Graph
233
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
234
		                                                         // Open Graph Protocol Framework
235
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
236
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
237
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
238
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
239
		'sharepress/sharepress.php',                             // SharePress
240
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
241
		'social-discussions/social-discussions.php',             // Social Discussions
242
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
243
		'socialize/socialize.php',                               // Socialize
244
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
245
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
246
		                                                         // Tweet, Like, Google +1 and Share
247
		'wordbooker/wordbooker.php',                             // Wordbooker
248
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
249
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
250
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
251
		                                                         // WP Facebook Like Send & Open Graph Meta
252
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
253
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
254
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
255
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
256
	);
257
258
	/**
259
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
260
	 */
261
	private $twitter_cards_conflicting_plugins = array(
262
	//	'twitter/twitter.php',                       // The official one handles this on its own.
263
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
264
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
265
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
266
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
267
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
268
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
269
		'twitter-cards/twitter-cards.php',           // Twitter Cards
270
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
271
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
272
	);
273
274
	/**
275
	 * Message to display in admin_notice
276
	 * @var string
277
	 */
278
	public $message = '';
279
280
	/**
281
	 * Error to display in admin_notice
282
	 * @var string
283
	 */
284
	public $error = '';
285
286
	/**
287
	 * Modules that need more privacy description.
288
	 * @var string
289
	 */
290
	public $privacy_checks = '';
291
292
	/**
293
	 * Stats to record once the page loads
294
	 *
295
	 * @var array
296
	 */
297
	public $stats = array();
298
299
	/**
300
	 * Jetpack_Sync object
301
	 */
302
	public $sync;
303
304
	/**
305
	 * Verified data for JSON authorization request
306
	 */
307
	public $json_api_authorization_request = array();
308
309
	/**
310
	 * Holds the singleton instance of this class
311
	 * @since 2.3.3
312
	 * @var Jetpack
313
	 */
314
	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...
315
316
	/**
317
	 * Singleton
318
	 * @static
319
	 */
320
	public static function init() {
321
		if ( ! self::$instance ) {
322
			self::$instance = new Jetpack;
323
324
			self::$instance->plugin_upgrade();
325
		}
326
327
		return self::$instance;
328
	}
329
330
	/**
331
	 * Must never be called statically
332
	 */
333
	function plugin_upgrade() {
334
		if ( Jetpack::is_active() ) {
335
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
336
			if ( JETPACK__VERSION != $version ) {
337
338
				// Check which active modules actually exist and remove others from active_modules list
339
				$unfiltered_modules = Jetpack::get_active_modules();
340
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
341
				if ( array_diff( $unfiltered_modules, $modules ) ) {
342
					Jetpack::update_active_modules( $modules );
343
				}
344
345
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
346
347
				// Upgrade to 4.3.0
348
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
349
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
350
				}
351
352
				// Make sure Markdown for posts gets turned back on
353
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
354
					update_option( 'wpcom_publish_posts_with_markdown', true );
355
				}
356
357
				Jetpack::maybe_set_version_option();
358
			}
359
		}
360
	}
361
362
	static function activate_manage( ) {
363
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
364
			self::activate_module( 'manage', false, false );
365
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
366
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
367
		}
368
	}
369
370
	static function update_active_modules( $modules ) {
371
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
372
373
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
374
375
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
376
			$new_active_modules = array_diff( $modules, $current_modules );
377
			foreach( $new_active_modules as $module ) {
378
				/**
379
				 * Fires when a specific module is activated.
380
				 *
381
				 * @since 1.9.0
382
				 *
383
				 * @param string $module Module slug.
384
				 * @param boolean $success whether the module was activated. @since 4.2
385
				 */
386
				do_action( 'jetpack_activate_module', $module, $success );
387
388
				/**
389
				 * Fires when a module is activated.
390
				 * The dynamic part of the filter, $module, is the module slug.
391
				 *
392
				 * @since 1.9.0
393
				 *
394
				 * @param string $module Module slug.
395
				 */
396
				do_action( "jetpack_activate_module_$module", $module );
397
			}
398
399
			$new_deactive_modules = array_diff( $current_modules, $modules );
400
			foreach( $new_deactive_modules as $module ) {
401
				/**
402
				 * Fired after a module has been deactivated.
403
				 *
404
				 * @since 4.2.0
405
				 *
406
				 * @param string $module Module slug.
407
				 * @param boolean $success whether the module was deactivated.
408
				 */
409
				do_action( 'jetpack_deactivate_module', $module, $success );
410
				/**
411
				 * Fires when a module is deactivated.
412
				 * The dynamic part of the filter, $module, is the module slug.
413
				 *
414
				 * @since 1.9.0
415
				 *
416
				 * @param string $module Module slug.
417
				 */
418
				do_action( "jetpack_deactivate_module_$module", $module );
419
			}
420
		}
421
422
		return $success;
423
	}
424
425
	static function delete_active_modules() {
426
		self::update_active_modules( array() );
427
	}
428
429
	/**
430
	 * Constructor.  Initializes WordPress hooks
431
	 */
432
	private function __construct() {
433
		/*
434
		 * Check for and alert any deprecated hooks
435
		 */
436
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
437
438
		/*
439
		 * Load things that should only be in Network Admin.
440
		 *
441
		 * For now blow away everything else until a more full
442
		 * understanding of what is needed at the network level is
443
		 * available
444
		 */
445
		if( is_multisite() ) {
446
			Jetpack_Network::init();
447
		}
448
449
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
450
451
		// Unlink user before deleting the user from .com
452
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
453
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
454
455
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
456
			@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...
457
458
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
459
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
460
461
			$this->require_jetpack_authentication();
462
463
			if ( Jetpack::is_active() ) {
464
				// Hack to preserve $HTTP_RAW_POST_DATA
465
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
466
467
				$signed = $this->verify_xml_rpc_signature();
468
				if ( $signed && ! is_wp_error( $signed ) ) {
469
					// The actual API methods.
470
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
471
				} else {
472
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
473
					// active Jetpack connection, so that additional users can link their account.
474
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
475
				}
476
			} else {
477
				// The bootstrap API methods.
478
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
479
			}
480
481
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
482
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
483
		} elseif (
484
			is_admin() &&
485
			isset( $_POST['action'] ) && (
486
				'jetpack_upload_file' == $_POST['action'] ||
487
				'jetpack_update_file' == $_POST['action']
488
			)
489
		) {
490
			$this->require_jetpack_authentication();
491
			$this->add_remote_request_handlers();
492
		} else {
493
			if ( Jetpack::is_active() ) {
494
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
495
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
496
			}
497
		}
498
499
		if ( Jetpack::is_active() ) {
500
			Jetpack_Heartbeat::init();
501
		}
502
503
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
504
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
505
506
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
507
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
508
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
509
		}
510
511
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
512
513
		add_action( 'admin_init', array( $this, 'admin_init' ) );
514
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
515
516
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
517
518
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
519
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
520
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
521
522
		// returns HTTPS support status
523
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
524
525
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
526
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
527
528
		// JITM AJAX callback function
529
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
530
531
		// Universal ajax callback for all tracking events triggered via js
532
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
533
534
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
535
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
536
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
537
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
538
539
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
540
541
		/**
542
		 * These actions run checks to load additional files.
543
		 * They check for external files or plugins, so they need to run as late as possible.
544
		 */
545
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
546
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
547
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
548
549
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
550
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
551
552
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
553
554
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
555
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
556
557
		// A filter to control all just in time messages
558
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
559
560
		// Update the Jetpack plan from API on heartbeats
561
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
562
563
		/**
564
		 * This is the hack to concatinate all css files into one.
565
		 * For description and reasoning see the implode_frontend_css method
566
		 *
567
		 * Super late priority so we catch all the registered styles
568
		 */
569
		if( !is_admin() ) {
570
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
571
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
572
		}
573
	}
574
575
	function jetpack_admin_ajax_tracks_callback() {
576
		// Check for nonce
577
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
578
			wp_die( 'Permissions check failed.' );
579
		}
580
581
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
582
			wp_die( 'No valid event name or type.' );
583
		}
584
585
		$tracks_data = array();
586
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
587
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
588
		}
589
590
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
591
		wp_send_json_success();
592
		wp_die();
593
	}
594
595
	/**
596
	 * The callback for the JITM ajax requests.
597
	 */
598
	function jetpack_jitm_ajax_callback() {
599
		// Check for nonce
600
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
601
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
602
		}
603
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
604
			$module_slug = $_REQUEST['jitmModule'];
605
			Jetpack::log( 'activate', $module_slug );
606
			Jetpack::activate_module( $module_slug, false, false );
607
			Jetpack::state( 'message', 'no_message' );
608
609
			//A Jetpack module is being activated through a JITM, track it
610
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
611
			$this->do_stats( 'server_side' );
612
613
			wp_send_json_success();
614
		}
615
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
616
			// get the hide_jitm options array
617
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
618
			$module_slug = $_REQUEST['jitmModule'];
619
620
			if( ! $jetpack_hide_jitm ) {
621
				$jetpack_hide_jitm = array(
622
					$module_slug => 'hide'
623
				);
624
			} else {
625
				$jetpack_hide_jitm[$module_slug] = 'hide';
626
			}
627
628
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
629
630
			//jitm is being dismissed forever, track it
631
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
632
			$this->do_stats( 'server_side' );
633
634
			wp_send_json_success();
635
		}
636 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
637
			$module_slug = $_REQUEST['jitmModule'];
638
639
			// User went to WordPress.com, track this
640
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
641
			$this->do_stats( 'server_side' );
642
643
			wp_send_json_success();
644
		}
645 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
646
			$track = $_REQUEST['jitmModule'];
647
648
			// User is viewing JITM, track it.
649
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
650
			$this->do_stats( 'server_side' );
651
652
			wp_send_json_success();
653
		}
654
	}
655
656
	/**
657
	 * If there are any stats that need to be pushed, but haven't been, push them now.
658
	 */
659
	function __destruct() {
660
		if ( ! empty( $this->stats ) ) {
661
			$this->do_stats( 'server_side' );
662
		}
663
	}
664
665
	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...
666
		switch( $cap ) {
667
			case 'jetpack_connect' :
668
			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...
669
				if ( Jetpack::is_development_mode() ) {
670
					$caps = array( 'do_not_allow' );
671
					break;
672
				}
673
				/**
674
				 * Pass through. If it's not development mode, these should match disconnect.
675
				 * Let users disconnect if it's development mode, just in case things glitch.
676
				 */
677
			case 'jetpack_disconnect' :
678
				/**
679
				 * In multisite, can individual site admins manage their own connection?
680
				 *
681
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
682
				 */
683
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
684
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
685
						/**
686
						 * We need to update the option name -- it's terribly unclear which
687
						 * direction the override goes.
688
						 *
689
						 * @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...
690
						 */
691
						$caps = array( 'do_not_allow' );
692
						break;
693
					}
694
				}
695
696
				$caps = array( 'manage_options' );
697
				break;
698
			case 'jetpack_manage_modules' :
699
			case 'jetpack_activate_modules' :
700
			case 'jetpack_deactivate_modules' :
701
				$caps = array( 'manage_options' );
702
				break;
703
			case 'jetpack_configure_modules' :
704
				$caps = array( 'manage_options' );
705
				break;
706
			case 'jetpack_network_admin_page':
707
			case 'jetpack_network_settings_page':
708
				$caps = array( 'manage_network_plugins' );
709
				break;
710
			case 'jetpack_network_sites_page':
711
				$caps = array( 'manage_sites' );
712
				break;
713
			case 'jetpack_admin_page' :
714
				if ( Jetpack::is_development_mode() ) {
715
					$caps = array( 'manage_options' );
716
					break;
717
				} else {
718
					$caps = array( 'read' );
719
				}
720
				break;
721
			case 'jetpack_connect_user' :
722
				if ( Jetpack::is_development_mode() ) {
723
					$caps = array( 'do_not_allow' );
724
					break;
725
				}
726
				$caps = array( 'read' );
727
				break;
728
		}
729
		return $caps;
730
	}
731
732
	function require_jetpack_authentication() {
733
		// Don't let anyone authenticate
734
		$_COOKIE = array();
735
		remove_all_filters( 'authenticate' );
736
		remove_all_actions( 'wp_login_failed' );
737
738
		if ( Jetpack::is_active() ) {
739
			// Allow Jetpack authentication
740
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
741
		}
742
	}
743
744
	/**
745
	 * Load language files
746
	 * @action plugins_loaded
747
	 */
748
	public static function plugin_textdomain() {
749
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
750
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
751
	}
752
753
	/**
754
	 * Register assets for use in various modules and the Jetpack admin page.
755
	 *
756
	 * @uses wp_script_is, wp_register_script, plugins_url
757
	 * @action wp_loaded
758
	 * @return null
759
	 */
760
	public function register_assets() {
761
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
762
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
763
		}
764
765 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
766
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
767
		}
768
769 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
770
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
771
		}
772
773 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
774
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
775
		}
776
777
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
778
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
779
780
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
781
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
782
			if ( ! is_numeric( $fb_app_id ) ) {
783
				$fb_app_id = '';
784
			}
785
			wp_localize_script(
786
				'jetpack-facebook-embed',
787
				'jpfbembed',
788
				array(
789
					'appid' => $fb_app_id,
790
					'locale' => $this->get_locale(),
791
				)
792
			);
793
		}
794
795
		/**
796
		 * As jetpack_register_genericons is by default fired off a hook,
797
		 * the hook may have already fired by this point.
798
		 * So, let's just trigger it manually.
799
		 */
800
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
801
		jetpack_register_genericons();
802
803
		/**
804
		 * Register the social logos
805
		 */
806
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
807
		jetpack_register_social_logos();
808
809 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
810
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
811
	}
812
813
	/**
814
	 * Guess locale from language code.
815
	 *
816
	 * @param string $lang Language code.
817
	 * @return string|bool
818
	 */
819 View Code Duplication
	function guess_locale_from_lang( $lang ) {
820
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
821
			return 'en_US';
822
		}
823
824
		if ( ! class_exists( 'GP_Locales' ) ) {
825
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
826
				return false;
827
			}
828
829
			require JETPACK__GLOTPRESS_LOCALES_PATH;
830
		}
831
832
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
833
			// WP.com: get_locale() returns 'it'
834
			$locale = GP_Locales::by_slug( $lang );
835
		} else {
836
			// Jetpack: get_locale() returns 'it_IT';
837
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
838
		}
839
840
		if ( ! $locale ) {
841
			return false;
842
		}
843
844
		if ( empty( $locale->facebook_locale ) ) {
845
			if ( empty( $locale->wp_locale ) ) {
846
				return false;
847
			} else {
848
				// Facebook SDK is smart enough to fall back to en_US if a
849
				// locale isn't supported. Since supported Facebook locales
850
				// can fall out of sync, we'll attempt to use the known
851
				// wp_locale value and rely on said fallback.
852
				return $locale->wp_locale;
853
			}
854
		}
855
856
		return $locale->facebook_locale;
857
	}
858
859
	/**
860
	 * Get the locale.
861
	 *
862
	 * @return string|bool
863
	 */
864
	function get_locale() {
865
		$locale = $this->guess_locale_from_lang( get_locale() );
866
867
		if ( ! $locale ) {
868
			$locale = 'en_US';
869
		}
870
871
		return $locale;
872
	}
873
874
	/**
875
	 * Device Pixels support
876
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
877
	 */
878
	function devicepx() {
879
		if ( Jetpack::is_active() ) {
880
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
881
		}
882
	}
883
884
	/**
885
	 * Return the network_site_url so that .com knows what network this site is a part of.
886
	 * @param  bool $option
887
	 * @return string
888
	 */
889
	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...
890
		return network_site_url();
891
	}
892
	/**
893
	 * Network Name.
894
	 */
895
	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...
896
		global $current_site;
897
		return $current_site->site_name;
898
	}
899
	/**
900
	 * Does the network allow new user and site registrations.
901
	 * @return string
902
	 */
903
	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...
904
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
905
	}
906
	/**
907
	 * Does the network allow admins to add new users.
908
	 * @return boolian
909
	 */
910
	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...
911
		return (bool) get_site_option( 'add_new_users' );
912
	}
913
	/**
914
	 * File upload psace left per site in MB.
915
	 *  -1 means NO LIMIT.
916
	 * @return number
917
	 */
918
	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...
919
		// value in MB
920
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
921
	}
922
923
	/**
924
	 * Network allowed file types.
925
	 * @return string
926
	 */
927
	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...
928
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
929
	}
930
931
	/**
932
	 * Maximum file upload size set by the network.
933
	 * @return number
934
	 */
935
	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...
936
		// value in KB
937
		return get_site_option( 'fileupload_maxk', 300 );
938
	}
939
940
	/**
941
	 * Lets us know if a site allows admins to manage the network.
942
	 * @return array
943
	 */
944
	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...
945
		return get_site_option( 'menu_items' );
946
	}
947
948
	/**
949
	 * If a user has been promoted to or demoted from admin, we need to clear the
950
	 * jetpack_other_linked_admins transient.
951
	 *
952
	 * @since 4.3.2
953
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
954
	 *
955
	 * @param int    $user_id   The user ID whose role changed.
956
	 * @param string $role      The new role.
957
	 * @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...
958
	 */
959
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
960
		if ( 'administrator' == $role
961
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
962
			|| is_null( $old_roles )
963
		) {
964
			delete_transient( 'jetpack_other_linked_admins' );
965
		}
966
	}
967
968
	/**
969
	 * Checks to see if there are any other users available to become primary
970
	 * Users must both:
971
	 * - Be linked to wpcom
972
	 * - Be an admin
973
	 *
974
	 * @return mixed False if no other users are linked, Int if there are.
975
	 */
976
	static function get_other_linked_admins() {
977
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
978
979
		if ( false === $other_linked_users ) {
980
			$admins = get_users( array( 'role' => 'administrator' ) );
981
			if ( count( $admins ) > 1 ) {
982
				$available = array();
983
				foreach ( $admins as $admin ) {
984
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
985
						$available[] = $admin->ID;
986
					}
987
				}
988
989
				$count_connected_admins = count( $available );
990
				if ( count( $available ) > 1 ) {
991
					$other_linked_users = $count_connected_admins;
992
				} else {
993
					$other_linked_users = 0;
994
				}
995
			} else {
996
				$other_linked_users = 0;
997
			}
998
999
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1000
		}
1001
1002
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1003
	}
1004
1005
	/**
1006
	 * Return whether we are dealing with a multi network setup or not.
1007
	 * The reason we are type casting this is because we want to avoid the situation where
1008
	 * the result is false since when is_main_network_option return false it cases
1009
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1010
	 * database which could be set to anything as opposed to what this function returns.
1011
	 * @param  bool  $option
1012
	 *
1013
	 * @return boolean
1014
	 */
1015
	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...
1016
		// return '1' or ''
1017
		return (string) (bool) Jetpack::is_multi_network();
1018
	}
1019
1020
	/**
1021
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1022
	 *
1023
	 * @param  string  $option
1024
	 * @return boolean
1025
	 */
1026
	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...
1027
		return (string) (bool) is_multisite();
1028
	}
1029
1030
	/**
1031
	 * Implemented since there is no core is multi network function
1032
	 * Right now there is no way to tell if we which network is the dominant network on the system
1033
	 *
1034
	 * @since  3.3
1035
	 * @return boolean
1036
	 */
1037
	public static function is_multi_network() {
1038
		global  $wpdb;
1039
1040
		// if we don't have a multi site setup no need to do any more
1041
		if ( ! is_multisite() ) {
1042
			return false;
1043
		}
1044
1045
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1046
		if ( $num_sites > 1 ) {
1047
			return true;
1048
		} else {
1049
			return false;
1050
		}
1051
	}
1052
1053
	/**
1054
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1055
	 * @return null
1056
	 */
1057
	function update_jetpack_main_network_site_option() {
1058
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1059
	}
1060
	/**
1061
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1062
	 *
1063
	 */
1064
	function update_jetpack_network_settings() {
1065
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1066
		// Only sync this info for the main network site.
1067
	}
1068
1069
	/**
1070
	 * Get back if the current site is single user site.
1071
	 *
1072
	 * @return bool
1073
	 */
1074
	public static function is_single_user_site() {
1075
		global $wpdb;
1076
1077 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1078
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1079
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1080
		}
1081
		return 1 === (int) $some_users;
1082
	}
1083
1084
	/**
1085
	 * Returns true if the site has file write access false otherwise.
1086
	 * @return string ( '1' | '0' )
1087
	 **/
1088
	public static function file_system_write_access() {
1089
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1090
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1091
		}
1092
1093
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1094
1095
		$filesystem_method = get_filesystem_method();
1096
		if ( $filesystem_method === 'direct' ) {
1097
			return 1;
1098
		}
1099
1100
		ob_start();
1101
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1102
		ob_end_clean();
1103
		if ( $filesystem_credentials_are_stored ) {
1104
			return 1;
1105
		}
1106
		return 0;
1107
	}
1108
1109
	/**
1110
	 * Finds out if a site is using a version control system.
1111
	 * @return string ( '1' | '0' )
1112
	 **/
1113
	public static function is_version_controlled() {
1114
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1115
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1116
	}
1117
1118
	/**
1119
	 * Determines whether the current theme supports featured images or not.
1120
	 * @return string ( '1' | '0' )
1121
	 */
1122
	public static function featured_images_enabled() {
1123
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1124
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1125
	}
1126
1127
	/**
1128
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1129
	 *
1130
	 * @deprecated 4.7 use get_avatar_url instead.
1131
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1132
	 * @param int $size Size of the avatar image
1133
	 * @param string $default URL to a default image to use if no avatar is available
1134
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1135
	 *
1136
	 * @return array
1137
	 */
1138
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1139
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1140
		return get_avatar_url( $id_or_email, array(
1141
			'size' => $size,
1142
			'default' => $default,
1143
			'force_default' => $force_display,
1144
		) );
1145
	}
1146
1147
	/**
1148
	 * jetpack_updates is saved in the following schema:
1149
	 *
1150
	 * array (
1151
	 *      'plugins'                       => (int) Number of plugin updates available.
1152
	 *      'themes'                        => (int) Number of theme updates available.
1153
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1154
	 *      'translations'                  => (int) Number of translation updates available.
1155
	 *      'total'                         => (int) Total of all available updates.
1156
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1157
	 * )
1158
	 * @return array
1159
	 */
1160
	public static function get_updates() {
1161
		$update_data = wp_get_update_data();
1162
1163
		// Stores the individual update counts as well as the total count.
1164
		if ( isset( $update_data['counts'] ) ) {
1165
			$updates = $update_data['counts'];
1166
		}
1167
1168
		// If we need to update WordPress core, let's find the latest version number.
1169 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1170
			$cur = get_preferred_from_update_core();
1171
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1172
				$updates['wp_update_version'] = $cur->current;
1173
			}
1174
		}
1175
		return isset( $updates ) ? $updates : array();
1176
	}
1177
1178
	public static function get_update_details() {
1179
		$update_details = array(
1180
			'update_core' => get_site_transient( 'update_core' ),
1181
			'update_plugins' => get_site_transient( 'update_plugins' ),
1182
			'update_themes' => get_site_transient( 'update_themes' ),
1183
		);
1184
		return $update_details;
1185
	}
1186
1187
	public static function refresh_update_data() {
1188
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1189
1190
	}
1191
1192
	public static function refresh_theme_data() {
1193
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1194
	}
1195
1196
	/**
1197
	 * Is Jetpack active?
1198
	 */
1199
	public static function is_active() {
1200
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1201
	}
1202
1203
	/**
1204
	 * Make an API call to WordPress.com for plan status
1205
	 *
1206
	 * @uses Jetpack_Options::get_option()
1207
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1208
	 * @uses update_option()
1209
	 *
1210
	 * @access public
1211
	 * @static
1212
	 *
1213
	 * @return bool True if plan is updated, false if no update
1214
	 */
1215
	public static function refresh_active_plan_from_wpcom() {
1216
		// Make the API request
1217
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1218
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1219
1220
		// Bail if there was an error or malformed response
1221
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1222
			return false;
1223
		}
1224
1225
		// Decode the results
1226
		$results = json_decode( $response['body'], true );
1227
1228
		// Bail if there were no results or plan details returned
1229
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1230
			return false;
1231
		}
1232
1233
		// Store the option and return true if updated
1234
		return update_option( 'jetpack_active_plan', $results['plan'] );
1235
	}
1236
1237
	/**
1238
	 * Get the plan that this Jetpack site is currently using
1239
	 *
1240
	 * @uses get_option()
1241
	 *
1242
	 * @access public
1243
	 * @static
1244
	 *
1245
	 * @return array Active Jetpack plan details
1246
	 */
1247
	public static function get_active_plan() {
1248
		$plan = get_option( 'jetpack_active_plan' );
1249
1250
		// Set the default options
1251
		if ( ! $plan ) {
1252
			$plan = array(
1253
				'product_slug' => 'jetpack_free',
1254
				'supports'     => array(),
1255
				'class'        => 'free',
1256
			);
1257
		}
1258
1259
		// Define what paid modules are supported by personal plans
1260
		$personal_plans = array(
1261
			'jetpack_personal',
1262
			'jetpack_personal_monthly',
1263
		);
1264
1265
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1266
			$plan['supports'] = array(
1267
				'akismet',
1268
			);
1269
			$plan['class'] = 'personal';
1270
		}
1271
1272
		// Define what paid modules are supported by premium plans
1273
		$premium_plans = array(
1274
			'jetpack_premium',
1275
			'jetpack_premium_monthly',
1276
		);
1277
1278 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1279
			$plan['supports'] = array(
1280
				'videopress',
1281
				'akismet',
1282
				'vaultpress',
1283
				'wordads',
1284
			);
1285
			$plan['class'] = 'premium';
1286
		}
1287
1288
		// Define what paid modules are supported by professional plans
1289
		$business_plans = array(
1290
			'jetpack_business',
1291
			'jetpack_business_monthly',
1292
		);
1293
1294 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1295
			$plan['supports'] = array(
1296
				'videopress',
1297
				'akismet',
1298
				'vaultpress',
1299
				'seo-tools',
1300
				'google-analytics',
1301
				'wordads',
1302
			);
1303
			$plan['class'] = 'business';
1304
		}
1305
1306
		// Make sure we have an array here in the event database data is stale
1307
		if ( ! isset( $plan['supports'] ) ) {
1308
			$plan['supports'] = array();
1309
		}
1310
1311
		return $plan;
1312
	}
1313
1314
	/**
1315
	 * Determine whether the active plan supports a particular feature
1316
	 *
1317
	 * @uses Jetpack::get_active_plan()
1318
	 *
1319
	 * @access public
1320
	 * @static
1321
	 *
1322
	 * @return bool True if plan supports feature, false if not
1323
	 */
1324
	public static function active_plan_supports( $feature ) {
1325
		$plan = Jetpack::get_active_plan();
1326
1327
		if ( in_array( $feature, $plan['supports'] ) ) {
1328
			return true;
1329
		}
1330
1331
		return false;
1332
	}
1333
1334
	/**
1335
	 * Is Jetpack in development (offline) mode?
1336
	 */
1337
	public static function is_development_mode() {
1338
		$development_mode = false;
1339
1340
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1341
			$development_mode = JETPACK_DEV_DEBUG;
1342
		} elseif ( $site_url = site_url() ) {
1343
			$development_mode = false === strpos( $site_url, '.' );
1344
		}
1345
1346
		/**
1347
		 * Filters Jetpack's development mode.
1348
		 *
1349
		 * @see https://jetpack.com/support/development-mode/
1350
		 *
1351
		 * @since 2.2.1
1352
		 *
1353
		 * @param bool $development_mode Is Jetpack's development mode active.
1354
		 */
1355
		return apply_filters( 'jetpack_development_mode', $development_mode );
1356
	}
1357
1358
	/**
1359
	* Get Jetpack development mode notice text and notice class.
1360
	*
1361
	* Mirrors the checks made in Jetpack::is_development_mode
1362
	*
1363
	*/
1364
	public static function show_development_mode_notice() {
1365
		if ( Jetpack::is_development_mode() ) {
1366
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1367
				$notice = sprintf(
1368
					/* translators: %s is a URL */
1369
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1370
					'https://jetpack.com/support/development-mode/'
1371
				);
1372
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1373
				$notice = sprintf(
1374
					/* translators: %s is a URL */
1375
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1376
					'https://jetpack.com/support/development-mode/'
1377
				);
1378
			} else {
1379
				$notice = sprintf(
1380
					/* translators: %s is a URL */
1381
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1382
					'https://jetpack.com/support/development-mode/'
1383
				);
1384
			}
1385
1386
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1387
		}
1388
1389
		// Throw up a notice if using a development version and as for feedback.
1390
		if ( Jetpack::is_development_version() ) {
1391
			/* translators: %s is a URL */
1392
			$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/' );
1393
1394
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1395
		}
1396
		// Throw up a notice if using staging mode
1397
		if ( Jetpack::is_staging_site() ) {
1398
			/* translators: %s is a URL */
1399
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1400
1401
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1402
		}
1403
	}
1404
1405
	/**
1406
	 * Whether Jetpack's version maps to a public release, or a development version.
1407
	 */
1408
	public static function is_development_version() {
1409
		/**
1410
		 * Allows filtering whether this is a development version of Jetpack.
1411
		 *
1412
		 * This filter is especially useful for tests.
1413
		 *
1414
		 * @since 4.3.0
1415
		 *
1416
		 * @param bool $development_version Is this a develoment version of Jetpack?
1417
		 */
1418
		return (bool) apply_filters(
1419
			'jetpack_development_version',
1420
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1421
		);
1422
	}
1423
1424
	/**
1425
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1426
	 */
1427
	public static function is_user_connected( $user_id = false ) {
1428
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1429
		if ( ! $user_id ) {
1430
			return false;
1431
		}
1432
1433
		return (bool) Jetpack_Data::get_access_token( $user_id );
1434
	}
1435
1436
	/**
1437
	 * Get the wpcom user data of the current|specified connected user.
1438
	 */
1439
	public static function get_connected_user_data( $user_id = null ) {
1440
		if ( ! $user_id ) {
1441
			$user_id = get_current_user_id();
1442
		}
1443
1444
		$transient_key = "jetpack_connected_user_data_$user_id";
1445
1446
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1447
			return $cached_user_data;
1448
		}
1449
1450
		Jetpack::load_xml_rpc_client();
1451
		$xml = new Jetpack_IXR_Client( array(
1452
			'user_id' => $user_id,
1453
		) );
1454
		$xml->query( 'wpcom.getUser' );
1455
		if ( ! $xml->isError() ) {
1456
			$user_data = $xml->getResponse();
1457
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1458
			return $user_data;
1459
		}
1460
1461
		return false;
1462
	}
1463
1464
	/**
1465
	 * Get the wpcom email of the current|specified connected user.
1466
	 */
1467 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1468
		if ( ! $user_id ) {
1469
			$user_id = get_current_user_id();
1470
		}
1471
		Jetpack::load_xml_rpc_client();
1472
		$xml = new Jetpack_IXR_Client( array(
1473
			'user_id' => $user_id,
1474
		) );
1475
		$xml->query( 'wpcom.getUserEmail' );
1476
		if ( ! $xml->isError() ) {
1477
			return $xml->getResponse();
1478
		}
1479
		return false;
1480
	}
1481
1482
	/**
1483
	 * Get the wpcom email of the master user.
1484
	 */
1485
	public static function get_master_user_email() {
1486
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1487
		if ( $master_user_id ) {
1488
			return self::get_connected_user_email( $master_user_id );
1489
		}
1490
		return '';
1491
	}
1492
1493
	function current_user_is_connection_owner() {
1494
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1495
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1496
	}
1497
1498
	/**
1499
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1500
	 */
1501
	function extra_oembed_providers() {
1502
		// Cloudup: https://dev.cloudup.com/#oembed
1503
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1504
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1505
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1506
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1507
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1508
	}
1509
1510
	/**
1511
	 * Synchronize connected user role changes
1512
	 */
1513
	function user_role_change( $user_id ) {
1514
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1515
		Jetpack_Sync_Users::user_role_change( $user_id );
1516
	}
1517
1518
	/**
1519
	 * Loads the currently active modules.
1520
	 */
1521
	public static function load_modules() {
1522
		if ( ! self::is_active() && !self::is_development_mode() ) {
1523
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1524
				return;
1525
			}
1526
		}
1527
1528
		$version = Jetpack_Options::get_option( 'version' );
1529 View Code Duplication
		if ( ! $version ) {
1530
			$version = $old_version = JETPACK__VERSION . ':' . time();
1531
			/** This action is documented in class.jetpack.php */
1532
			do_action( 'updating_jetpack_version', $version, false );
1533
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1534
		}
1535
		list( $version ) = explode( ':', $version );
1536
1537
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1538
1539
		$modules_data = array();
1540
1541
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1542
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1543
			$updated_modules = array();
1544
			foreach ( $modules as $module ) {
1545
				$modules_data[ $module ] = Jetpack::get_module( $module );
1546
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1547
					continue;
1548
				}
1549
1550
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1551
					continue;
1552
				}
1553
1554
				$updated_modules[] = $module;
1555
			}
1556
1557
			$modules = array_diff( $modules, $updated_modules );
1558
		}
1559
1560
		$is_development_mode = Jetpack::is_development_mode();
1561
1562
		foreach ( $modules as $index => $module ) {
1563
			// If we're in dev mode, disable modules requiring a connection
1564
			if ( $is_development_mode ) {
1565
				// Prime the pump if we need to
1566
				if ( empty( $modules_data[ $module ] ) ) {
1567
					$modules_data[ $module ] = Jetpack::get_module( $module );
1568
				}
1569
				// If the module requires a connection, but we're in local mode, don't include it.
1570
				if ( $modules_data[ $module ]['requires_connection'] ) {
1571
					continue;
1572
				}
1573
			}
1574
1575
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1576
				continue;
1577
			}
1578
1579
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1580
				unset( $modules[ $index ] );
1581
				self::update_active_modules( array_values( $modules ) );
1582
				continue;
1583
			}
1584
1585
			/**
1586
			 * Fires when a specific module is loaded.
1587
			 * The dynamic part of the hook, $module, is the module slug.
1588
			 *
1589
			 * @since 1.1.0
1590
			 */
1591
			do_action( 'jetpack_module_loaded_' . $module );
1592
		}
1593
1594
		/**
1595
		 * Fires when all the modules are loaded.
1596
		 *
1597
		 * @since 1.1.0
1598
		 */
1599
		do_action( 'jetpack_modules_loaded' );
1600
1601
		// 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.
1602
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1603
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1604
	}
1605
1606
	/**
1607
	 * Check if Jetpack's REST API compat file should be included
1608
	 * @action plugins_loaded
1609
	 * @return null
1610
	 */
1611
	public function check_rest_api_compat() {
1612
		/**
1613
		 * Filters the list of REST API compat files to be included.
1614
		 *
1615
		 * @since 2.2.5
1616
		 *
1617
		 * @param array $args Array of REST API compat files to include.
1618
		 */
1619
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1620
1621
		if ( function_exists( 'bbpress' ) )
1622
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1623
1624
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1625
			require_once $_jetpack_rest_api_compat_include;
1626
	}
1627
1628
	/**
1629
	 * Gets all plugins currently active in values, regardless of whether they're
1630
	 * traditionally activated or network activated.
1631
	 *
1632
	 * @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...
1633
	 */
1634
	public static function get_active_plugins() {
1635
		$active_plugins = (array) get_option( 'active_plugins', array() );
1636
1637
		if ( is_multisite() ) {
1638
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1639
			// whereas active_plugins stores them in the values.
1640
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1641
			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...
1642
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1643
			}
1644
		}
1645
1646
		sort( $active_plugins );
1647
1648
		return array_unique( $active_plugins );
1649
	}
1650
1651
	/**
1652
	 * Gets and parses additional plugin data to send with the heartbeat data
1653
	 *
1654
	 * @since 3.8.1
1655
	 *
1656
	 * @return array Array of plugin data
1657
	 */
1658
	public static function get_parsed_plugin_data() {
1659
		if ( ! function_exists( 'get_plugins' ) ) {
1660
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1661
		}
1662
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1663
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1664
		$active_plugins = Jetpack::get_active_plugins();
1665
1666
		$plugins = array();
1667
		foreach ( $all_plugins as $path => $plugin_data ) {
1668
			$plugins[ $path ] = array(
1669
					'is_active' => in_array( $path, $active_plugins ),
1670
					'file'      => $path,
1671
					'name'      => $plugin_data['Name'],
1672
					'version'   => $plugin_data['Version'],
1673
					'author'    => $plugin_data['Author'],
1674
			);
1675
		}
1676
1677
		return $plugins;
1678
	}
1679
1680
	/**
1681
	 * Gets and parses theme data to send with the heartbeat data
1682
	 *
1683
	 * @since 3.8.1
1684
	 *
1685
	 * @return array Array of theme data
1686
	 */
1687
	public static function get_parsed_theme_data() {
1688
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1689
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1690
1691
		$themes = array();
1692
		foreach ( $all_themes as $slug => $theme_data ) {
1693
			$theme_headers = array();
1694
			foreach ( $header_keys as $header_key ) {
1695
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1696
			}
1697
1698
			$themes[ $slug ] = array(
1699
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1700
					'slug' => $slug,
1701
					'theme_root' => $theme_data->get_theme_root_uri(),
1702
					'parent' => $theme_data->parent(),
1703
					'headers' => $theme_headers
1704
			);
1705
		}
1706
1707
		return $themes;
1708
	}
1709
1710
	/**
1711
	 * Checks whether a specific plugin is active.
1712
	 *
1713
	 * We don't want to store these in a static variable, in case
1714
	 * there are switch_to_blog() calls involved.
1715
	 */
1716
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1717
		return in_array( $plugin, self::get_active_plugins() );
1718
	}
1719
1720
	/**
1721
	 * Check if Jetpack's Open Graph tags should be used.
1722
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1723
	 *
1724
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1725
	 * @action plugins_loaded
1726
	 * @return null
1727
	 */
1728
	public function check_open_graph() {
1729
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1730
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1731
		}
1732
1733
		$active_plugins = self::get_active_plugins();
1734
1735
		if ( ! empty( $active_plugins ) ) {
1736
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1737
				if ( in_array( $plugin, $active_plugins ) ) {
1738
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1739
					break;
1740
				}
1741
			}
1742
		}
1743
1744
		/**
1745
		 * Allow the addition of Open Graph Meta Tags to all pages.
1746
		 *
1747
		 * @since 2.0.3
1748
		 *
1749
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1750
		 */
1751
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1752
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1753
		}
1754
	}
1755
1756
	/**
1757
	 * Check if Jetpack's Twitter tags should be used.
1758
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1759
	 *
1760
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1761
	 * @action plugins_loaded
1762
	 * @return null
1763
	 */
1764
	public function check_twitter_tags() {
1765
1766
		$active_plugins = self::get_active_plugins();
1767
1768
		if ( ! empty( $active_plugins ) ) {
1769
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1770
				if ( in_array( $plugin, $active_plugins ) ) {
1771
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1772
					break;
1773
				}
1774
			}
1775
		}
1776
1777
		/**
1778
		 * Allow Twitter Card Meta tags to be disabled.
1779
		 *
1780
		 * @since 2.6.0
1781
		 *
1782
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1783
		 */
1784
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1785
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1786
		}
1787
	}
1788
1789
	/**
1790
	 * Allows plugins to submit security reports.
1791
 	 *
1792
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1793
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1794
	 * @param array   $args         See definitions above
1795
	 */
1796
	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...
1797
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1798
	}
1799
1800
/* Jetpack Options API */
1801
1802
	public static function get_option_names( $type = 'compact' ) {
1803
		return Jetpack_Options::get_option_names( $type );
1804
	}
1805
1806
	/**
1807
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1808
 	 *
1809
	 * @param string $name    Option name
1810
	 * @param mixed  $default (optional)
1811
	 */
1812
	public static function get_option( $name, $default = false ) {
1813
		return Jetpack_Options::get_option( $name, $default );
1814
	}
1815
1816
	/**
1817
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1818
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1819
	* $name must be a registered option name.
1820
	*/
1821
	public static function create_nonce( $name ) {
1822
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1823
1824
		Jetpack_Options::update_option( $name, $secret );
1825
		@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...
1826
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1827
			return new Jetpack_Error( 'missing_secrets' );
1828
1829
		return array(
1830
			'secret_1' => $secret_1,
1831
			'secret_2' => $secret_2,
1832
			'eol'      => $eol,
1833
		);
1834
	}
1835
1836
	/**
1837
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1838
 	 *
1839
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1840
	 * @param string $name  Option name
1841
	 * @param mixed  $value Option value
1842
	 */
1843
	public static function update_option( $name, $value ) {
1844
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1845
		return Jetpack_Options::update_option( $name, $value );
1846
	}
1847
1848
	/**
1849
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1850
 	 *
1851
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1852
	 * @param array $array array( option name => option value, ... )
1853
	 */
1854
	public static function update_options( $array ) {
1855
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1856
		return Jetpack_Options::update_options( $array );
1857
	}
1858
1859
	/**
1860
	 * Deletes the given option.  May be passed multiple option names as an array.
1861
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1862
	 *
1863
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1864
	 * @param string|array $names
1865
	 */
1866
	public static function delete_option( $names ) {
1867
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1868
		return Jetpack_Options::delete_option( $names );
1869
	}
1870
1871
	/**
1872
	 * Enters a user token into the user_tokens option
1873
	 *
1874
	 * @param int $user_id
1875
	 * @param string $token
1876
	 * return bool
1877
	 */
1878
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1879
		// not designed for concurrent updates
1880
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1881
		if ( ! is_array( $user_tokens ) )
1882
			$user_tokens = array();
1883
		$user_tokens[$user_id] = $token;
1884
		if ( $is_master_user ) {
1885
			$master_user = $user_id;
1886
			$options     = compact( 'user_tokens', 'master_user' );
1887
		} else {
1888
			$options = compact( 'user_tokens' );
1889
		}
1890
		return Jetpack_Options::update_options( $options );
1891
	}
1892
1893
	/**
1894
	 * Returns an array of all PHP files in the specified absolute path.
1895
	 * Equivalent to glob( "$absolute_path/*.php" ).
1896
	 *
1897
	 * @param string $absolute_path The absolute path of the directory to search.
1898
	 * @return array Array of absolute paths to the PHP files.
1899
	 */
1900
	public static function glob_php( $absolute_path ) {
1901
		if ( function_exists( 'glob' ) ) {
1902
			return glob( "$absolute_path/*.php" );
1903
		}
1904
1905
		$absolute_path = untrailingslashit( $absolute_path );
1906
		$files = array();
1907
		if ( ! $dir = @opendir( $absolute_path ) ) {
1908
			return $files;
1909
		}
1910
1911
		while ( false !== $file = readdir( $dir ) ) {
1912
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1913
				continue;
1914
			}
1915
1916
			$file = "$absolute_path/$file";
1917
1918
			if ( ! is_file( $file ) ) {
1919
				continue;
1920
			}
1921
1922
			$files[] = $file;
1923
		}
1924
1925
		closedir( $dir );
1926
1927
		return $files;
1928
	}
1929
1930
	public static function activate_new_modules( $redirect = false ) {
1931
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1932
			return;
1933
		}
1934
1935
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1936 View Code Duplication
		if ( ! $jetpack_old_version ) {
1937
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1938
			/** This action is documented in class.jetpack.php */
1939
			do_action( 'updating_jetpack_version', $version, false );
1940
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1941
		}
1942
1943
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1944
1945
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1946
			return;
1947
		}
1948
1949
		$active_modules     = Jetpack::get_active_modules();
1950
		$reactivate_modules = array();
1951
		foreach ( $active_modules as $active_module ) {
1952
			$module = Jetpack::get_module( $active_module );
1953
			if ( ! isset( $module['changed'] ) ) {
1954
				continue;
1955
			}
1956
1957
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1958
				continue;
1959
			}
1960
1961
			$reactivate_modules[] = $active_module;
1962
			Jetpack::deactivate_module( $active_module );
1963
		}
1964
1965
		$new_version = JETPACK__VERSION . ':' . time();
1966
		/** This action is documented in class.jetpack.php */
1967
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1968
		Jetpack_Options::update_options(
1969
			array(
1970
				'version'     => $new_version,
1971
				'old_version' => $jetpack_old_version,
1972
			)
1973
		);
1974
1975
		Jetpack::state( 'message', 'modules_activated' );
1976
		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...
1977
1978
		if ( $redirect ) {
1979
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1980
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1981
				$page = $_GET['page'];
1982
			}
1983
1984
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1985
			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...
1986
		}
1987
	}
1988
1989
	/**
1990
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1991
	 * Make sure to tuck away module "library" files in a sub-directory.
1992
	 */
1993
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1994
		static $modules = null;
1995
1996
		if ( ! isset( $modules ) ) {
1997
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1998
			// Use the cache if we're on the front-end and it's available...
1999
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2000
				$modules = $available_modules_option[ JETPACK__VERSION ];
2001
			} else {
2002
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2003
2004
				$modules = array();
2005
2006
				foreach ( $files as $file ) {
2007
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2008
						continue;
2009
					}
2010
2011
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2012
				}
2013
2014
				Jetpack_Options::update_option( 'available_modules', array(
2015
					JETPACK__VERSION => $modules,
2016
				) );
2017
			}
2018
		}
2019
2020
		/**
2021
		 * Filters the array of modules available to be activated.
2022
		 *
2023
		 * @since 2.4.0
2024
		 *
2025
		 * @param array $modules Array of available modules.
2026
		 * @param string $min_version Minimum version number required to use modules.
2027
		 * @param string $max_version Maximum version number required to use modules.
2028
		 */
2029
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2030
2031
		if ( ! $min_version && ! $max_version ) {
2032
			return array_keys( $mods );
2033
		}
2034
2035
		$r = array();
2036
		foreach ( $mods as $slug => $introduced ) {
2037
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2038
				continue;
2039
			}
2040
2041
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2042
				continue;
2043
			}
2044
2045
			$r[] = $slug;
2046
		}
2047
2048
		return $r;
2049
	}
2050
2051
	/**
2052
	 * Default modules loaded on activation.
2053
	 */
2054
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2055
		$return = array();
2056
2057
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2058
			$module_data = Jetpack::get_module( $module );
2059
2060
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2061
				case 'yes' :
2062
					$return[] = $module;
2063
					break;
2064
				case 'public' :
2065
					if ( Jetpack_Options::get_option( 'public' ) ) {
2066
						$return[] = $module;
2067
					}
2068
					break;
2069
				case 'no' :
2070
				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...
2071
					break;
2072
			}
2073
		}
2074
		/**
2075
		 * Filters the array of default modules.
2076
		 *
2077
		 * @since 2.5.0
2078
		 *
2079
		 * @param array $return Array of default modules.
2080
		 * @param string $min_version Minimum version number required to use modules.
2081
		 * @param string $max_version Maximum version number required to use modules.
2082
		 */
2083
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2084
	}
2085
2086
	/**
2087
	 * Checks activated modules during auto-activation to determine
2088
	 * if any of those modules are being deprecated.  If so, close
2089
	 * them out, and add any replacement modules.
2090
	 *
2091
	 * Runs at priority 99 by default.
2092
	 *
2093
	 * This is run late, so that it can still activate a module if
2094
	 * the new module is a replacement for another that the user
2095
	 * currently has active, even if something at the normal priority
2096
	 * would kibosh everything.
2097
	 *
2098
	 * @since 2.6
2099
	 * @uses jetpack_get_default_modules filter
2100
	 * @param array $modules
2101
	 * @return array
2102
	 */
2103
	function handle_deprecated_modules( $modules ) {
2104
		$deprecated_modules = array(
2105
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2106
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2107
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2108
		);
2109
2110
		// Don't activate SSO if they never completed activating WPCC.
2111
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2112
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2113
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2114
				$deprecated_modules['wpcc'] = null;
2115
			}
2116
		}
2117
2118
		foreach ( $deprecated_modules as $module => $replacement ) {
2119
			if ( Jetpack::is_module_active( $module ) ) {
2120
				self::deactivate_module( $module );
2121
				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...
2122
					$modules[] = $replacement;
2123
				}
2124
			}
2125
		}
2126
2127
		return array_unique( $modules );
2128
	}
2129
2130
	/**
2131
	 * Checks activated plugins during auto-activation to determine
2132
	 * if any of those plugins are in the list with a corresponding module
2133
	 * that is not compatible with the plugin. The module will not be allowed
2134
	 * to auto-activate.
2135
	 *
2136
	 * @since 2.6
2137
	 * @uses jetpack_get_default_modules filter
2138
	 * @param array $modules
2139
	 * @return array
2140
	 */
2141
	function filter_default_modules( $modules ) {
2142
2143
		$active_plugins = self::get_active_plugins();
2144
2145
		if ( ! empty( $active_plugins ) ) {
2146
2147
			// For each module we'd like to auto-activate...
2148
			foreach ( $modules as $key => $module ) {
2149
				// If there are potential conflicts for it...
2150
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2151
					// For each potential conflict...
2152
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2153
						// If that conflicting plugin is active...
2154
						if ( in_array( $plugin, $active_plugins ) ) {
2155
							// Remove that item from being auto-activated.
2156
							unset( $modules[ $key ] );
2157
						}
2158
					}
2159
				}
2160
			}
2161
		}
2162
2163
		return $modules;
2164
	}
2165
2166
	/**
2167
	 * Extract a module's slug from its full path.
2168
	 */
2169
	public static function get_module_slug( $file ) {
2170
		return str_replace( '.php', '', basename( $file ) );
2171
	}
2172
2173
	/**
2174
	 * Generate a module's path from its slug.
2175
	 */
2176
	public static function get_module_path( $slug ) {
2177
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2178
	}
2179
2180
	/**
2181
	 * Load module data from module file. Headers differ from WordPress
2182
	 * plugin headers to avoid them being identified as standalone
2183
	 * plugins on the WordPress plugins page.
2184
	 */
2185
	public static function get_module( $module ) {
2186
		$headers = array(
2187
			'name'                      => 'Module Name',
2188
			'description'               => 'Module Description',
2189
			'jumpstart_desc'            => 'Jumpstart Description',
2190
			'sort'                      => 'Sort Order',
2191
			'recommendation_order'      => 'Recommendation Order',
2192
			'introduced'                => 'First Introduced',
2193
			'changed'                   => 'Major Changes In',
2194
			'deactivate'                => 'Deactivate',
2195
			'free'                      => 'Free',
2196
			'requires_connection'       => 'Requires Connection',
2197
			'auto_activate'             => 'Auto Activate',
2198
			'module_tags'               => 'Module Tags',
2199
			'feature'                   => 'Feature',
2200
			'additional_search_queries' => 'Additional Search Queries',
2201
		);
2202
2203
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2204
2205
		$mod = Jetpack::get_file_data( $file, $headers );
2206
		if ( empty( $mod['name'] ) ) {
2207
			return false;
2208
		}
2209
2210
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2211
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2212
		$mod['deactivate']              = empty( $mod['deactivate'] );
2213
		$mod['free']                    = empty( $mod['free'] );
2214
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2215
2216
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2217
			$mod['auto_activate'] = 'No';
2218
		} else {
2219
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2220
		}
2221
2222
		if ( $mod['module_tags'] ) {
2223
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2224
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2225
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2226
		} else {
2227
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2228
		}
2229
2230
		if ( $mod['feature'] ) {
2231
			$mod['feature'] = explode( ',', $mod['feature'] );
2232
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2233
		} else {
2234
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2235
		}
2236
2237
		/**
2238
		 * Filters the feature array on a module.
2239
		 *
2240
		 * This filter allows you to control where each module is filtered: Recommended,
2241
		 * Jumpstart, and the default "Other" listing.
2242
		 *
2243
		 * @since 3.5.0
2244
		 *
2245
		 * @param array   $mod['feature'] The areas to feature this module:
2246
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2247
		 *     'Recommended' shows on the main Jetpack admin screen.
2248
		 *     'Other' should be the default if no other value is in the array.
2249
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2250
		 * @param array   $mod All the currently assembled module data.
2251
		 */
2252
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2253
2254
		/**
2255
		 * Filter the returned data about a module.
2256
		 *
2257
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2258
		 * so please be careful.
2259
		 *
2260
		 * @since 3.6.0
2261
		 *
2262
		 * @param array   $mod    The details of the requested module.
2263
		 * @param string  $module The slug of the module, e.g. sharedaddy
2264
		 * @param string  $file   The path to the module source file.
2265
		 */
2266
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2267
	}
2268
2269
	/**
2270
	 * Like core's get_file_data implementation, but caches the result.
2271
	 */
2272
	public static function get_file_data( $file, $headers ) {
2273
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2274
		$file_name = basename( $file );
2275
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2276
		$key              = md5( $file_name . serialize( $headers ) );
2277
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2278
2279
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2280
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2281
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2282
		}
2283
2284
		$data = get_file_data( $file, $headers );
2285
2286
		// Strip out any old Jetpack versions that are cluttering the option.
2287
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2288
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2289
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2290
2291
		return $data;
2292
	}
2293
2294
	/**
2295
	 * Return translated module tag.
2296
	 *
2297
	 * @param string $tag Tag as it appears in each module heading.
2298
	 *
2299
	 * @return mixed
2300
	 */
2301
	public static function translate_module_tag( $tag ) {
2302
		return jetpack_get_module_i18n_tag( $tag );
2303
	}
2304
2305
	/**
2306
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2307
	 *
2308
	 * @since 3.9.2
2309
	 *
2310
	 * @param array $modules
2311
	 *
2312
	 * @return string|void
2313
	 */
2314
	public static function get_translated_modules( $modules ) {
2315
		foreach ( $modules as $index => $module ) {
2316
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2317
			if ( isset( $module['name'] ) ) {
2318
				$modules[ $index ]['name'] = $i18n_module['name'];
2319
			}
2320
			if ( isset( $module['description'] ) ) {
2321
				$modules[ $index ]['description'] = $i18n_module['description'];
2322
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2323
			}
2324
		}
2325
		return $modules;
2326
	}
2327
2328
	/**
2329
	 * Get a list of activated modules as an array of module slugs.
2330
	 */
2331
	public static function get_active_modules() {
2332
		$active = Jetpack_Options::get_option( 'active_modules' );
2333
2334
		if ( ! is_array( $active ) ) {
2335
			$active = array();
2336
		}
2337
2338
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2339
			$active[] = 'vaultpress';
2340
		} else {
2341
			$active = array_diff( $active, array( 'vaultpress' ) );
2342
		}
2343
2344
		//If protect is active on the main site of a multisite, it should be active on all sites.
2345
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2346
			$active[] = 'protect';
2347
		}
2348
2349
		return array_unique( $active );
2350
	}
2351
2352
	/**
2353
	 * Check whether or not a Jetpack module is active.
2354
	 *
2355
	 * @param string $module The slug of a Jetpack module.
2356
	 * @return bool
2357
	 *
2358
	 * @static
2359
	 */
2360
	public static function is_module_active( $module ) {
2361
		return in_array( $module, self::get_active_modules() );
2362
	}
2363
2364
	public static function is_module( $module ) {
2365
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2366
	}
2367
2368
	/**
2369
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2370
	 *
2371
	 * @param bool $catch True to start catching, False to stop.
2372
	 *
2373
	 * @static
2374
	 */
2375
	public static function catch_errors( $catch ) {
2376
		static $display_errors, $error_reporting;
2377
2378
		if ( $catch ) {
2379
			$display_errors  = @ini_set( 'display_errors', 1 );
2380
			$error_reporting = @error_reporting( E_ALL );
2381
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2382
		} else {
2383
			@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...
2384
			@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...
2385
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2386
		}
2387
	}
2388
2389
	/**
2390
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2391
	 */
2392
	public static function catch_errors_on_shutdown() {
2393
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2394
	}
2395
2396
	/**
2397
	 * Rewrite any string to make paths easier to read.
2398
	 *
2399
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2400
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2401
	 *
2402
	 * @param $string
2403
	 * @return mixed
2404
	 */
2405
	public static function alias_directories( $string ) {
2406
		// ABSPATH has a trailing slash.
2407
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2408
		// WP_CONTENT_DIR does not have a trailing slash.
2409
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2410
2411
		return $string;
2412
	}
2413
2414
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2415
		$jetpack = Jetpack::init();
2416
2417
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2418
		$modules = array_merge( $other_modules, $modules );
2419
2420
		// Look for standalone plugins and disable if active.
2421
2422
		$to_deactivate = array();
2423
		foreach ( $modules as $module ) {
2424
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2425
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2426
			}
2427
		}
2428
2429
		$deactivated = array();
2430
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2431
			list( $probable_file, $probable_title ) = $deactivate_me;
2432
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2433
				$deactivated[] = $module;
2434
			}
2435
		}
2436
2437
		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...
2438
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2439
2440
			$url = add_query_arg(
2441
				array(
2442
					'action'   => 'activate_default_modules',
2443
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2444
				),
2445
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2446
			);
2447
			wp_safe_redirect( $url );
2448
			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...
2449
		}
2450
2451
		/**
2452
		 * Fires before default modules are activated.
2453
		 *
2454
		 * @since 1.9.0
2455
		 *
2456
		 * @param string $min_version Minimum version number required to use modules.
2457
		 * @param string $max_version Maximum version number required to use modules.
2458
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2459
		 */
2460
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2461
2462
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2463
		Jetpack::restate();
2464
		Jetpack::catch_errors( true );
2465
2466
		$active = Jetpack::get_active_modules();
2467
2468
		foreach ( $modules as $module ) {
2469
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2470
				$active[] = $module;
2471
				self::update_active_modules( $active );
2472
				continue;
2473
			}
2474
2475
			if ( in_array( $module, $active ) ) {
2476
				$module_info = Jetpack::get_module( $module );
2477
				if ( ! $module_info['deactivate'] ) {
2478
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2479 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2480
						$active_state = explode( ',', $active_state );
2481
					} else {
2482
						$active_state = array();
2483
					}
2484
					$active_state[] = $module;
2485
					Jetpack::state( $state, implode( ',', $active_state ) );
2486
				}
2487
				continue;
2488
			}
2489
2490
			$file = Jetpack::get_module_path( $module );
2491
			if ( ! file_exists( $file ) ) {
2492
				continue;
2493
			}
2494
2495
			// we'll override this later if the plugin can be included without fatal error
2496
			if ( $redirect ) {
2497
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2498
			}
2499
			Jetpack::state( 'error', 'module_activation_failed' );
2500
			Jetpack::state( 'module', $module );
2501
			ob_start();
2502
			require $file;
2503
2504
			$active[] = $module;
2505
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2506 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2507
				$active_state = explode( ',', $active_state );
2508
			} else {
2509
				$active_state = array();
2510
			}
2511
			$active_state[] = $module;
2512
			Jetpack::state( $state, implode( ',', $active_state ) );
2513
			Jetpack::update_active_modules( $active );
2514
2515
			ob_end_clean();
2516
		}
2517
		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...
2518
		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...
2519
		Jetpack::catch_errors( false );
2520
		/**
2521
		 * Fires when default modules are activated.
2522
		 *
2523
		 * @since 1.9.0
2524
		 *
2525
		 * @param string $min_version Minimum version number required to use modules.
2526
		 * @param string $max_version Maximum version number required to use modules.
2527
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2528
		 */
2529
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2530
	}
2531
2532
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2533
		/**
2534
		 * Fires before a module is activated.
2535
		 *
2536
		 * @since 2.6.0
2537
		 *
2538
		 * @param string $module Module slug.
2539
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2540
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2541
		 */
2542
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2543
2544
		$jetpack = Jetpack::init();
2545
2546
		if ( ! strlen( $module ) )
2547
			return false;
2548
2549
		if ( ! Jetpack::is_module( $module ) )
2550
			return false;
2551
2552
		// If it's already active, then don't do it again
2553
		$active = Jetpack::get_active_modules();
2554
		foreach ( $active as $act ) {
2555
			if ( $act == $module )
2556
				return true;
2557
		}
2558
2559
		$module_data = Jetpack::get_module( $module );
2560
2561
		if ( ! Jetpack::is_active() ) {
2562
			if ( !Jetpack::is_development_mode() )
2563
				return false;
2564
2565
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2566
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2567
				return false;
2568
		}
2569
2570
		// Check and see if the old plugin is active
2571
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2572
			// Deactivate the old plugin
2573
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2574
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2575
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2576
				Jetpack::state( 'deactivated_plugins', $module );
2577
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2578
				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...
2579
			}
2580
		}
2581
2582
		// Protect won't work with mis-configured IPs
2583
		if ( 'protect' === $module ) {
2584
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2585
			if ( ! jetpack_protect_get_ip() ) {
2586
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2587
				return false;
2588
			}
2589
		}
2590
2591
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2592
		Jetpack::state( 'module', $module );
2593
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2594
2595
		Jetpack::catch_errors( true );
2596
		ob_start();
2597
		require Jetpack::get_module_path( $module );
2598
		/** This action is documented in class.jetpack.php */
2599
		do_action( 'jetpack_activate_module', $module );
2600
		$active[] = $module;
2601
		Jetpack::update_active_modules( $active );
2602
2603
		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...
2604
		ob_end_clean();
2605
		Jetpack::catch_errors( false );
2606
2607
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2608 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2609
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2610
2611
			//Jump start is being dismissed send data to MC Stats
2612
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2613
2614
			$jetpack->do_stats( 'server_side' );
2615
		}
2616
2617
		if ( $redirect ) {
2618
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2619
		}
2620
		if ( $exit ) {
2621
			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...
2622
		}
2623
		return true;
2624
	}
2625
2626
	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...
2627
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2628
	}
2629
2630
	public static function deactivate_module( $module ) {
2631
		/**
2632
		 * Fires when a module is deactivated.
2633
		 *
2634
		 * @since 1.9.0
2635
		 *
2636
		 * @param string $module Module slug.
2637
		 */
2638
		do_action( 'jetpack_pre_deactivate_module', $module );
2639
2640
		$jetpack = Jetpack::init();
2641
2642
		$active = Jetpack::get_active_modules();
2643
		$new    = array_filter( array_diff( $active, (array) $module ) );
2644
2645
		// A flag for Jump Start so it's not shown again.
2646 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2647
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2648
2649
			//Jump start is being dismissed send data to MC Stats
2650
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2651
2652
			$jetpack->do_stats( 'server_side' );
2653
		}
2654
2655
		return self::update_active_modules( $new );
2656
	}
2657
2658
	public static function enable_module_configurable( $module ) {
2659
		$module = Jetpack::get_module_slug( $module );
2660
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2661
	}
2662
2663
	public static function module_configuration_url( $module ) {
2664
		$module = Jetpack::get_module_slug( $module );
2665
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2666
	}
2667
2668
	public static function module_configuration_load( $module, $method ) {
2669
		$module = Jetpack::get_module_slug( $module );
2670
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2671
	}
2672
2673
	public static function module_configuration_head( $module, $method ) {
2674
		$module = Jetpack::get_module_slug( $module );
2675
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2676
	}
2677
2678
	public static function module_configuration_screen( $module, $method ) {
2679
		$module = Jetpack::get_module_slug( $module );
2680
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2681
	}
2682
2683
	public static function module_configuration_activation_screen( $module, $method ) {
2684
		$module = Jetpack::get_module_slug( $module );
2685
		add_action( 'display_activate_module_setting_' . $module, $method );
2686
	}
2687
2688
/* Installation */
2689
2690
	public static function bail_on_activation( $message, $deactivate = true ) {
2691
?>
2692
<!doctype html>
2693
<html>
2694
<head>
2695
<meta charset="<?php bloginfo( 'charset' ); ?>">
2696
<style>
2697
* {
2698
	text-align: center;
2699
	margin: 0;
2700
	padding: 0;
2701
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2702
}
2703
p {
2704
	margin-top: 1em;
2705
	font-size: 18px;
2706
}
2707
</style>
2708
<body>
2709
<p><?php echo esc_html( $message ); ?></p>
2710
</body>
2711
</html>
2712
<?php
2713
		if ( $deactivate ) {
2714
			$plugins = get_option( 'active_plugins' );
2715
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2716
			$update  = false;
2717
			foreach ( $plugins as $i => $plugin ) {
2718
				if ( $plugin === $jetpack ) {
2719
					$plugins[$i] = false;
2720
					$update = true;
2721
				}
2722
			}
2723
2724
			if ( $update ) {
2725
				update_option( 'active_plugins', array_filter( $plugins ) );
2726
			}
2727
		}
2728
		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...
2729
	}
2730
2731
	/**
2732
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2733
	 * @static
2734
	 */
2735
	public static function plugin_activation( $network_wide ) {
2736
		Jetpack_Options::update_option( 'activated', 1 );
2737
2738
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2739
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2740
		}
2741
2742
		if ( $network_wide )
2743
			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...
2744
2745
		Jetpack::plugin_initialize();
2746
	}
2747
	/**
2748
	 * Runs before bumping version numbers up to a new version
2749
	 * @param  (string) $version    Version:timestamp
2750
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2751
	 * @return null              [description]
2752
	 */
2753
	public static function do_version_bump( $version, $old_version ) {
2754
2755
		if ( ! $old_version ) { // For new sites
2756
			// Setting up jetpack manage
2757
			Jetpack::activate_manage();
2758
		}
2759
	}
2760
2761
	/**
2762
	 * Sets the internal version number and activation state.
2763
	 * @static
2764
	 */
2765
	public static function plugin_initialize() {
2766
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2767
			Jetpack_Options::update_option( 'activated', 2 );
2768
		}
2769
2770 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2771
			$version = $old_version = JETPACK__VERSION . ':' . time();
2772
			/** This action is documented in class.jetpack.php */
2773
			do_action( 'updating_jetpack_version', $version, false );
2774
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2775
		}
2776
2777
		Jetpack::load_modules();
2778
2779
		Jetpack_Options::delete_option( 'do_activate' );
2780
	}
2781
2782
	/**
2783
	 * Removes all connection options
2784
	 * @static
2785
	 */
2786
	public static function plugin_deactivation( ) {
2787
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2788
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2789
			Jetpack_Network::init()->deactivate();
2790
		} else {
2791
			Jetpack::disconnect( false );
2792
			//Jetpack_Heartbeat::init()->deactivate();
2793
		}
2794
	}
2795
2796
	/**
2797
	 * Disconnects from the Jetpack servers.
2798
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2799
	 * @static
2800
	 */
2801
	public static function disconnect( $update_activated_state = true ) {
2802
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2803
		Jetpack::clean_nonces( true );
2804
2805
		// If the site is in an IDC because sync is not allowed,
2806
		// let's make sure to not disconnect the production site.
2807
		if ( ! self::validate_sync_error_idc_option() ) {
2808
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2809
			Jetpack::load_xml_rpc_client();
2810
			$xml = new Jetpack_IXR_Client();
2811
			$xml->query( 'jetpack.deregister' );
2812
		}
2813
2814
		Jetpack_Options::delete_option(
2815
			array(
2816
				'register',
2817
				'blog_token',
2818
				'user_token',
2819
				'user_tokens',
2820
				'master_user',
2821
				'time_diff',
2822
				'fallback_no_verify_ssl_certs',
2823
			)
2824
		);
2825
2826
		Jetpack_IDC::clear_all_idc_options();
2827
2828
		if ( $update_activated_state ) {
2829
			Jetpack_Options::update_option( 'activated', 4 );
2830
		}
2831
2832
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2833
			// Check then record unique disconnection if site has never been disconnected previously
2834
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2835
				$jetpack_unique_connection['disconnected'] = 1;
2836
			} else {
2837
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2838
					//track unique disconnect
2839
					$jetpack = Jetpack::init();
2840
2841
					$jetpack->stat( 'connections', 'unique-disconnect' );
2842
					$jetpack->do_stats( 'server_side' );
2843
				}
2844
				// increment number of times disconnected
2845
				$jetpack_unique_connection['disconnected'] += 1;
2846
			}
2847
2848
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2849
		}
2850
2851
		// Delete cached connected user data
2852
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2853
		delete_transient( $transient_key );
2854
2855
		// Delete all the sync related data. Since it could be taking up space.
2856
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2857
		Jetpack_Sync_Sender::get_instance()->uninstall();
2858
2859
		// Disable the Heartbeat cron
2860
		Jetpack_Heartbeat::init()->deactivate();
2861
	}
2862
2863
	/**
2864
	 * Unlinks the current user from the linked WordPress.com user
2865
	 */
2866
	public static function unlink_user( $user_id = null ) {
2867
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2868
			return false;
2869
2870
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2871
2872
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2873
			return false;
2874
2875
		if ( ! isset( $tokens[ $user_id ] ) )
2876
			return false;
2877
2878
		Jetpack::load_xml_rpc_client();
2879
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2880
		$xml->query( 'jetpack.unlink_user', $user_id );
2881
2882
		unset( $tokens[ $user_id ] );
2883
2884
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2885
2886
		/**
2887
		 * Fires after the current user has been unlinked from WordPress.com.
2888
		 *
2889
		 * @since 4.1.0
2890
		 *
2891
		 * @param int $user_id The current user's ID.
2892
		 */
2893
		do_action( 'jetpack_unlinked_user', $user_id );
2894
2895
		return true;
2896
	}
2897
2898
	/**
2899
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2900
	 */
2901
	public static function try_registration() {
2902
		// Let's get some testing in beta versions and such.
2903
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2904
			// Before attempting to connect, let's make sure that the domains are viable.
2905
			$domains_to_check = array_unique( array(
2906
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2907
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2908
			) );
2909
			foreach ( $domains_to_check as $domain ) {
2910
				$result = Jetpack_Data::is_usable_domain( $domain );
2911
				if ( is_wp_error( $result ) ) {
2912
					return $result;
2913
				}
2914
			}
2915
		}
2916
2917
		$result = Jetpack::register();
2918
2919
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2920
		if ( ! $result || is_wp_error( $result ) ) {
2921
			return $result;
2922
		} else {
2923
			return true;
2924
		}
2925
	}
2926
2927
	/**
2928
	 * Tracking an internal event log. Try not to put too much chaff in here.
2929
	 *
2930
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2931
	 */
2932
	public static function log( $code, $data = null ) {
2933
		// only grab the latest 200 entries
2934
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2935
2936
		// Append our event to the log
2937
		$log_entry = array(
2938
			'time'    => time(),
2939
			'user_id' => get_current_user_id(),
2940
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2941
			'code'    => $code,
2942
		);
2943
		// Don't bother storing it unless we've got some.
2944
		if ( ! is_null( $data ) ) {
2945
			$log_entry['data'] = $data;
2946
		}
2947
		$log[] = $log_entry;
2948
2949
		// Try add_option first, to make sure it's not autoloaded.
2950
		// @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...
2951
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2952
			Jetpack_Options::update_option( 'log', $log );
2953
		}
2954
2955
		/**
2956
		 * Fires when Jetpack logs an internal event.
2957
		 *
2958
		 * @since 3.0.0
2959
		 *
2960
		 * @param array $log_entry {
2961
		 *	Array of details about the log entry.
2962
		 *
2963
		 *	@param string time Time of the event.
2964
		 *	@param int user_id ID of the user who trigerred the event.
2965
		 *	@param int blog_id Jetpack Blog ID.
2966
		 *	@param string code Unique name for the event.
2967
		 *	@param string data Data about the event.
2968
		 * }
2969
		 */
2970
		do_action( 'jetpack_log_entry', $log_entry );
2971
	}
2972
2973
	/**
2974
	 * Get the internal event log.
2975
	 *
2976
	 * @param $event (string) - only return the specific log events
2977
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2978
	 *
2979
	 * @return array of log events || WP_Error for invalid params
2980
	 */
2981
	public static function get_log( $event = false, $num = false ) {
2982
		if ( $event && ! is_string( $event ) ) {
2983
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2984
		}
2985
2986
		if ( $num && ! is_numeric( $num ) ) {
2987
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2988
		}
2989
2990
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2991
2992
		// If nothing set - act as it did before, otherwise let's start customizing the output
2993
		if ( ! $num && ! $event ) {
2994
			return $entire_log;
2995
		} else {
2996
			$entire_log = array_reverse( $entire_log );
2997
		}
2998
2999
		$custom_log_output = array();
3000
3001
		if ( $event ) {
3002
			foreach ( $entire_log as $log_event ) {
3003
				if ( $event == $log_event[ 'code' ] ) {
3004
					$custom_log_output[] = $log_event;
3005
				}
3006
			}
3007
		} else {
3008
			$custom_log_output = $entire_log;
3009
		}
3010
3011
		if ( $num ) {
3012
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3013
		}
3014
3015
		return $custom_log_output;
3016
	}
3017
3018
	/**
3019
	 * Log modification of important settings.
3020
	 */
3021
	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...
3022
		switch( $option ) {
3023
			case 'jetpack_sync_non_public_post_stati':
3024
				self::log( $option, $value );
3025
				break;
3026
		}
3027
	}
3028
3029
	/**
3030
	 * Return stat data for WPCOM sync
3031
	 */
3032
	public static function get_stat_data( $encode = true, $extended = true ) {
3033
		$data = Jetpack_Heartbeat::generate_stats_array();
3034
3035
		if ( $extended ) {
3036
			$additional_data = self::get_additional_stat_data();
3037
			$data = array_merge( $data, $additional_data );
3038
		}
3039
3040
		if ( $encode ) {
3041
			return json_encode( $data );
3042
		}
3043
3044
		return $data;
3045
	}
3046
3047
	/**
3048
	 * Get additional stat data to sync to WPCOM
3049
	 */
3050
	public static function get_additional_stat_data( $prefix = '' ) {
3051
		$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...
3052
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3053
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3054
		$return["{$prefix}site-count"]     = 0;
3055
3056
		if ( function_exists( 'get_blog_count' ) ) {
3057
			$return["{$prefix}site-count"] = get_blog_count();
3058
		}
3059
		return $return;
3060
	}
3061
3062
	private static function get_site_user_count() {
3063
		global $wpdb;
3064
3065
		if ( function_exists( 'wp_is_large_network' ) ) {
3066
			if ( wp_is_large_network( 'users' ) ) {
3067
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3068
			}
3069
		}
3070 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3071
			// It wasn't there, so regenerate the data and save the transient
3072
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3073
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3074
		}
3075
		return $user_count;
3076
	}
3077
3078
	/* Admin Pages */
3079
3080
	function admin_init() {
3081
		// If the plugin is not connected, display a connect message.
3082
		if (
3083
			// the plugin was auto-activated and needs its candy
3084
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3085
		||
3086
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3087
			! Jetpack_Options::get_option( 'activated' )
3088
		) {
3089
			Jetpack::plugin_initialize();
3090
		}
3091
3092
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3093
			Jetpack_Connection_Banner::init();
3094
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3095
			// Upgrade: 1.1 -> 1.1.1
3096
			// Check and see if host can verify the Jetpack servers' SSL certificate
3097
			$args = array();
3098
			Jetpack_Client::_wp_remote_request(
3099
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3100
				$args,
3101
				true
3102
			);
3103
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3104
			// Show the notice on the Dashboard only for now
3105
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3106
		}
3107
3108
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3109
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3110
		}
3111
3112
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3113
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3114
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3115
3116
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3117
			// Artificially throw errors in certain whitelisted cases during plugin activation
3118
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3119
		}
3120
3121
		// Jetpack Manage Activation Screen from .com
3122
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3123
3124
		// Add custom column in wp-admin/users.php to show whether user is linked.
3125
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3126
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3127
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3128
	}
3129
3130
	function admin_body_class( $admin_body_class = '' ) {
3131
		$classes = explode( ' ', trim( $admin_body_class ) );
3132
3133
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3134
3135
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3136
		return " $admin_body_class ";
3137
	}
3138
3139
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3140
		return $admin_body_class . ' jetpack-pagestyles ';
3141
	}
3142
3143
	/**
3144
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3145
	 *
3146
	 * @return null
3147
	 */
3148
	function prepare_manage_jetpack_notice() {
3149
3150
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3151
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3152
	}
3153
3154
	function manage_activate_screen() {
3155
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3156
	}
3157
	/**
3158
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3159
	 * This function artificially throws errors for such cases (whitelisted).
3160
	 *
3161
	 * @param string $plugin The activated plugin.
3162
	 */
3163
	function throw_error_on_activate_plugin( $plugin ) {
3164
		$active_modules = Jetpack::get_active_modules();
3165
3166
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3167
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3168
			$throw = false;
3169
3170
			// Try and make sure it really was the stats plugin
3171
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3172
				if ( 'stats.php' == basename( $plugin ) ) {
3173
					$throw = true;
3174
				}
3175
			} else {
3176
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3177
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3178
					$throw = true;
3179
				}
3180
			}
3181
3182
			if ( $throw ) {
3183
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3184
			}
3185
		}
3186
	}
3187
3188
	function intercept_plugin_error_scrape_init() {
3189
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3190
	}
3191
3192
	function intercept_plugin_error_scrape( $action, $result ) {
3193
		if ( ! $result ) {
3194
			return;
3195
		}
3196
3197
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3198
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3199
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3200
			}
3201
		}
3202
	}
3203
3204
	function add_remote_request_handlers() {
3205
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3206
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3207
	}
3208
3209
	function remote_request_handlers() {
3210
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3211
3212
		switch ( current_filter() ) {
3213
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3214
			$response = $this->upload_handler();
3215
			break;
3216
3217
		case 'wp_ajax_nopriv_jetpack_update_file' :
3218
			$response = $this->upload_handler( true );
3219
			break;
3220
		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...
3221
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3222
			break;
3223
		}
3224
3225
		if ( ! $response ) {
3226
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3227
		}
3228
3229
		if ( is_wp_error( $response ) ) {
3230
			$status_code       = $response->get_error_data();
3231
			$error             = $response->get_error_code();
3232
			$error_description = $response->get_error_message();
3233
3234
			if ( ! is_int( $status_code ) ) {
3235
				$status_code = 400;
3236
			}
3237
3238
			status_header( $status_code );
3239
			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...
3240
		}
3241
3242
		status_header( 200 );
3243
		if ( true === $response ) {
3244
			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...
3245
		}
3246
3247
		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...
3248
	}
3249
3250
	/**
3251
	 * Uploads a file gotten from the global $_FILES.
3252
	 * If `$update_media_item` is true and `post_id` is defined
3253
	 * the attachment file of the media item (gotten through of the post_id)
3254
	 * will be updated instead of add a new one.
3255
	 * 
3256
	 * @param  boolean $update_media_item - update media attachment
3257
	 * @return array - An array describing the uploadind files process
3258
	 */
3259
	function upload_handler( $update_media_item = false ) {
3260
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3261
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3262
		}
3263
3264
		$user = wp_authenticate( '', '' );
3265
		if ( ! $user || is_wp_error( $user ) ) {
3266
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3267
		}
3268
3269
		wp_set_current_user( $user->ID );
3270
3271
		if ( ! current_user_can( 'upload_files' ) ) {
3272
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3273
		}
3274
3275
		if ( empty( $_FILES ) ) {
3276
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3277
		}
3278
3279
		foreach ( array_keys( $_FILES ) as $files_key ) {
3280
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3281
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3282
			}
3283
		}
3284
3285
		$media_keys = array_keys( $_FILES['media'] );
3286
3287
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3288
		if ( ! $token || is_wp_error( $token ) ) {
3289
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3290
		}
3291
3292
		$uploaded_files = array();
3293
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3294
		unset( $GLOBALS['post'] );
3295
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3296
			$file = array();
3297
			foreach ( $media_keys as $media_key ) {
3298
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3299
			}
3300
3301
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3302
3303
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3304
			if ( $hmac_provided !== $hmac_file ) {
3305
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3306
				continue;
3307
			}
3308
3309
			$_FILES['.jetpack.upload.'] = $file;
3310
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3311
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3312
				$post_id = 0;
3313
			}
3314
3315
			if ( $update_media_item ) {
3316
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3317
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3318
				}
3319
3320
				$media_array = $_FILES['media'];
3321
3322
				$file_array['name'] = $media_array['name'][0]; 
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3323
				$file_array['type'] = $media_array['type'][0]; 
3324
				$file_array['tmp_name'] = $media_array['tmp_name'][0]; 
3325
				$file_array['error'] = $media_array['error'][0]; 
3326
				$file_array['size'] = $media_array['size'][0];
3327
3328
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3329
3330
				if ( is_wp_error( $edited_media_item ) ) {
3331
					return $edited_media_item;
3332
				}
3333
3334
				$response = (object) array(
3335
					'id'   => (string) $post_id,
3336
					'file' => (string) $edited_media_item->post_title,
3337
					'url'  => (string) wp_get_attachment_url( $post_id ),
3338
					'type' => (string) $edited_media_item->post_mime_type,
3339
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3340
				);
3341
3342
				return (array) array( $response );
3343
			}
3344
3345
			$attachment_id = media_handle_upload(
3346
				'.jetpack.upload.',
3347
				$post_id,
3348
				array(),
3349
				array(
3350
					'action' => 'jetpack_upload_file',
3351
				)
3352
			);
3353
3354
			if ( ! $attachment_id ) {
3355
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3356
			} elseif ( is_wp_error( $attachment_id ) ) {
3357
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3358
			} else {
3359
				$attachment = get_post( $attachment_id );
3360
				$uploaded_files[$index] = (object) array(
3361
					'id'   => (string) $attachment_id,
3362
					'file' => $attachment->post_title,
3363
					'url'  => wp_get_attachment_url( $attachment_id ),
3364
					'type' => $attachment->post_mime_type,
3365
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3366
				);
3367
				// Zip files uploads are not supported unless they are done for installation purposed
3368
				// lets delete them in case something goes wrong in this whole process
3369
				if ( 'application/zip' === $attachment->post_mime_type ) {
3370
					// Schedule a cleanup for 2 hours from now in case of failed install.
3371
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3372
				}
3373
			}
3374
		}
3375
		if ( ! is_null( $global_post ) ) {
3376
			$GLOBALS['post'] = $global_post;
3377
		}
3378
3379
		return $uploaded_files;
3380
	}
3381
3382
	/**
3383
	 * Add help to the Jetpack page
3384
	 *
3385
	 * @since Jetpack (1.2.3)
3386
	 * @return false if not the Jetpack page
3387
	 */
3388
	function admin_help() {
3389
		$current_screen = get_current_screen();
3390
3391
		// Overview
3392
		$current_screen->add_help_tab(
3393
			array(
3394
				'id'		=> 'home',
3395
				'title'		=> __( 'Home', 'jetpack' ),
3396
				'content'	=>
3397
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3398
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3399
					'<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>',
3400
			)
3401
		);
3402
3403
		// Screen Content
3404
		if ( current_user_can( 'manage_options' ) ) {
3405
			$current_screen->add_help_tab(
3406
				array(
3407
					'id'		=> 'settings',
3408
					'title'		=> __( 'Settings', 'jetpack' ),
3409
					'content'	=>
3410
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3411
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3412
						'<ol>' .
3413
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3414
							'<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>' .
3415
						'</ol>' .
3416
						'<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>'
3417
				)
3418
			);
3419
		}
3420
3421
		// Help Sidebar
3422
		$current_screen->set_help_sidebar(
3423
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3424
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3425
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3426
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3427
		);
3428
	}
3429
3430
	function admin_menu_css() {
3431
		wp_enqueue_style( 'jetpack-icons' );
3432
	}
3433
3434
	function admin_menu_order() {
3435
		return true;
3436
	}
3437
3438 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3439
		$jp_menu_order = array();
3440
3441
		foreach ( $menu_order as $index => $item ) {
3442
			if ( $item != 'jetpack' ) {
3443
				$jp_menu_order[] = $item;
3444
			}
3445
3446
			if ( $index == 0 ) {
3447
				$jp_menu_order[] = 'jetpack';
3448
			}
3449
		}
3450
3451
		return $jp_menu_order;
3452
	}
3453
3454
	function admin_head() {
3455 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3456
			/** This action is documented in class.jetpack-admin-page.php */
3457
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3458
	}
3459
3460
	function admin_banner_styles() {
3461
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3462
3463 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3464
			wp_register_style(
3465
				'jetpack-dops-style',
3466
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3467
				array(),
3468
				JETPACK__VERSION
3469
			);
3470
		}
3471
3472
		wp_enqueue_style(
3473
			'jetpack',
3474
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3475
			array( 'jetpack-dops-style' ),
3476
			 JETPACK__VERSION . '-20121016'
3477
		);
3478
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3479
		wp_style_add_data( 'jetpack', 'suffix', $min );
3480
	}
3481
3482
	function plugin_action_links( $actions ) {
3483
3484
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3485
3486
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3487
			return array_merge(
3488
				$jetpack_home,
3489
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3490
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3491
				$actions
3492
				);
3493
			}
3494
3495
		return array_merge( $jetpack_home, $actions );
3496
	}
3497
3498
	/**
3499
	 * This is the first banner
3500
	 * It should be visible only to user that can update the option
3501
	 * Are not connected
3502
	 *
3503
	 * @return null
3504
	 */
3505
	function admin_jetpack_manage_notice() {
3506
		$screen = get_current_screen();
3507
3508
		// Don't show the connect notice on the jetpack settings page.
3509
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3510
			return;
3511
		}
3512
3513
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3514
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3515
		/**
3516
		 * I think it would be great to have different wordsing depending on where you are
3517
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3518
		 * etc..
3519
		 */
3520
3521
		?>
3522
		<div id="message" class="updated jp-banner">
3523
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3524
				<div class="jp-banner__description-container">
3525
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3526
					<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>
3527
					<p class="jp-banner__button-container">
3528
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3529
						<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>
3530
					</p>
3531
				</div>
3532
		</div>
3533
		<?php
3534
	}
3535
3536
	/**
3537
	 * Returns the url that the user clicks to remove the notice for the big banner
3538
	 * @return (string)
3539
	 */
3540
	function opt_out_jetpack_manage_url() {
3541
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3542
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3543
	}
3544
	/**
3545
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3546
	 * @return (string)
3547
	 */
3548
	function opt_in_jetpack_manage_url() {
3549
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3550
	}
3551
3552
	function opt_in_jetpack_manage_notice() {
3553
		?>
3554
		<div class="wrap">
3555
			<div id="message" class="jetpack-message is-opt-in">
3556
				<?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' ); ?>
3557
			</div>
3558
		</div>
3559
		<?php
3560
3561
	}
3562
	/**
3563
	 * Determines whether to show the notice of not true = display notice
3564
	 * @return (bool)
3565
	 */
3566
	function can_display_jetpack_manage_notice() {
3567
		// never display the notice to users that can't do anything about it anyways
3568
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3569
			return false;
3570
3571
		// don't display if we are in development more
3572
		if( Jetpack::is_development_mode() ) {
3573
			return false;
3574
		}
3575
		// don't display if the site is private
3576
		if(  ! Jetpack_Options::get_option( 'public' ) )
3577
			return false;
3578
3579
		/**
3580
		 * Should the Jetpack Remote Site Management notice be displayed.
3581
		 *
3582
		 * @since 3.3.0
3583
		 *
3584
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3585
		 */
3586
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3587
	}
3588
3589
	/*
3590
	 * Registration flow:
3591
	 * 1 - ::admin_page_load() action=register
3592
	 * 2 - ::try_registration()
3593
	 * 3 - ::register()
3594
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3595
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3596
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3597
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3598
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3599
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3600
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3601
	 *       jetpack_id, jetpack_secret, jetpack_public
3602
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3603
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3604
	 * 5 - user logs in with WP.com account
3605
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3606
	 *		- Jetpack_Client_Server::authorize()
3607
	 *		- Jetpack_Client_Server::get_token()
3608
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3609
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3610
	 *			- which responds with access_token, token_type, scope
3611
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3612
	 *		- Jetpack::activate_default_modules()
3613
	 *     		- Deactivates deprecated plugins
3614
	 *     		- Activates all default modules
3615
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3616
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3617
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3618
	 *     Done!
3619
	 */
3620
3621
	/**
3622
	 * Handles the page load events for the Jetpack admin page
3623
	 */
3624
	function admin_page_load() {
3625
		$error = false;
3626
3627
		// Make sure we have the right body class to hook stylings for subpages off of.
3628
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3629
3630
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3631
			// Should only be used in intermediate redirects to preserve state across redirects
3632
			Jetpack::restate();
3633
		}
3634
3635
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3636
			// User clicked in the iframe to link their accounts
3637
			if ( ! Jetpack::is_user_connected() ) {
3638
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3639
				if ( isset( $_GET['notes_iframe'] ) )
3640
					$connect_url .= '&notes_iframe';
3641
				wp_redirect( $connect_url );
3642
				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...
3643
			} else {
3644
				if ( ! isset( $_GET['calypso_env'] ) ) {
3645
					Jetpack::state( 'message', 'already_authorized' );
3646
					wp_safe_redirect( Jetpack::admin_url() );
3647
				} else {
3648
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3649
					$connect_url .= '&already_authorized=true';
3650
					wp_redirect( $connect_url );
3651
				}
3652
			}
3653
		}
3654
3655
3656
		if ( isset( $_GET['action'] ) ) {
3657
			switch ( $_GET['action'] ) {
3658
			case 'authorize':
3659
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3660
					Jetpack::state( 'message', 'already_authorized' );
3661
					wp_safe_redirect( Jetpack::admin_url() );
3662
					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...
3663
				}
3664
				Jetpack::log( 'authorize' );
3665
				$client_server = new Jetpack_Client_Server;
3666
				$client_server->client_authorize();
3667
				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...
3668
			case 'register' :
3669
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3670
					$error = 'cheatin';
3671
					break;
3672
				}
3673
				check_admin_referer( 'jetpack-register' );
3674
				Jetpack::log( 'register' );
3675
				Jetpack::maybe_set_version_option();
3676
				$registered = Jetpack::try_registration();
3677
				if ( is_wp_error( $registered ) ) {
3678
					$error = $registered->get_error_code();
3679
					Jetpack::state( 'error', $error );
3680
					Jetpack::state( 'error', $registered->get_error_message() );
3681
					break;
3682
				}
3683
3684
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3685
3686
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3687
				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...
3688
			case 'activate' :
3689
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3690
					$error = 'cheatin';
3691
					break;
3692
				}
3693
3694
				$module = stripslashes( $_GET['module'] );
3695
				check_admin_referer( "jetpack_activate-$module" );
3696
				Jetpack::log( 'activate', $module );
3697
				Jetpack::activate_module( $module );
3698
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3699
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3700
				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...
3701
			case 'activate_default_modules' :
3702
				check_admin_referer( 'activate_default_modules' );
3703
				Jetpack::log( 'activate_default_modules' );
3704
				Jetpack::restate();
3705
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3706
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3707
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3708
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3709
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3710
				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...
3711
			case 'disconnect' :
3712
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3713
					$error = 'cheatin';
3714
					break;
3715
				}
3716
3717
				check_admin_referer( 'jetpack-disconnect' );
3718
				Jetpack::log( 'disconnect' );
3719
				Jetpack::disconnect();
3720
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3721
				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...
3722
			case 'reconnect' :
3723
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3724
					$error = 'cheatin';
3725
					break;
3726
				}
3727
3728
				check_admin_referer( 'jetpack-reconnect' );
3729
				Jetpack::log( 'reconnect' );
3730
				$this->disconnect();
3731
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3732
				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...
3733 View Code Duplication
			case 'deactivate' :
3734
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3735
					$error = 'cheatin';
3736
					break;
3737
				}
3738
3739
				$modules = stripslashes( $_GET['module'] );
3740
				check_admin_referer( "jetpack_deactivate-$modules" );
3741
				foreach ( explode( ',', $modules ) as $module ) {
3742
					Jetpack::log( 'deactivate', $module );
3743
					Jetpack::deactivate_module( $module );
3744
					Jetpack::state( 'message', 'module_deactivated' );
3745
				}
3746
				Jetpack::state( 'module', $modules );
3747
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3748
				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...
3749
			case 'unlink' :
3750
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3751
				check_admin_referer( 'jetpack-unlink' );
3752
				Jetpack::log( 'unlink' );
3753
				$this->unlink_user();
3754
				Jetpack::state( 'message', 'unlinked' );
3755
				if ( 'sub-unlink' == $redirect ) {
3756
					wp_safe_redirect( admin_url() );
3757
				} else {
3758
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3759
				}
3760
				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...
3761
			default:
3762
				/**
3763
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3764
				 *
3765
				 * @since 2.6.0
3766
				 *
3767
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3768
				 */
3769
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3770
			}
3771
		}
3772
3773
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3774
			self::activate_new_modules( true );
3775
		}
3776
3777
		$message_code = Jetpack::state( 'message' );
3778
		if ( Jetpack::state( 'optin-manage' ) ) {
3779
			$activated_manage = $message_code;
3780
			$message_code = 'jetpack-manage';
3781
		}
3782
3783
		switch ( $message_code ) {
3784
		case 'jetpack-manage':
3785
			$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>';
3786
			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...
3787
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3788
			}
3789
			break;
3790
3791
		}
3792
3793
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3794
3795
		if ( ! empty( $deactivated_plugins ) ) {
3796
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3797
			$deactivated_titles  = array();
3798
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3799
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3800
					continue;
3801
				}
3802
3803
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3804
			}
3805
3806
			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...
3807
				if ( $this->message ) {
3808
					$this->message .= "<br /><br />\n";
3809
				}
3810
3811
				$this->message .= wp_sprintf(
3812
					_n(
3813
						'Jetpack contains the most recent version of the old %l plugin.',
3814
						'Jetpack contains the most recent versions of the old %l plugins.',
3815
						count( $deactivated_titles ),
3816
						'jetpack'
3817
					),
3818
					$deactivated_titles
3819
				);
3820
3821
				$this->message .= "<br />\n";
3822
3823
				$this->message .= _n(
3824
					'The old version has been deactivated and can be removed from your site.',
3825
					'The old versions have been deactivated and can be removed from your site.',
3826
					count( $deactivated_titles ),
3827
					'jetpack'
3828
				);
3829
			}
3830
		}
3831
3832
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3833
3834
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3835
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3836
		}
3837
3838 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3839
			/**
3840
			 * Fires when a module configuration page is loaded.
3841
			 * The dynamic part of the hook is the configure parameter from the URL.
3842
			 *
3843
			 * @since 1.1.0
3844
			 */
3845
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3846
		}
3847
3848
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3849
	}
3850
3851
	function admin_notices() {
3852
3853
		if ( $this->error ) {
3854
?>
3855
<div id="message" class="jetpack-message jetpack-err">
3856
	<div class="squeezer">
3857
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3858
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3859
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3860
<?php	endif; ?>
3861
	</div>
3862
</div>
3863
<?php
3864
		}
3865
3866
		if ( $this->message ) {
3867
?>
3868
<div id="message" class="jetpack-message">
3869
	<div class="squeezer">
3870
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3871
	</div>
3872
</div>
3873
<?php
3874
		}
3875
3876
		if ( $this->privacy_checks ) :
3877
			$module_names = $module_slugs = array();
3878
3879
			$privacy_checks = explode( ',', $this->privacy_checks );
3880
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3881
			foreach ( $privacy_checks as $module_slug ) {
3882
				$module = Jetpack::get_module( $module_slug );
3883
				if ( ! $module ) {
3884
					continue;
3885
				}
3886
3887
				$module_slugs[] = $module_slug;
3888
				$module_names[] = "<strong>{$module['name']}</strong>";
3889
			}
3890
3891
			$module_slugs = join( ',', $module_slugs );
3892
?>
3893
<div id="message" class="jetpack-message jetpack-err">
3894
	<div class="squeezer">
3895
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3896
		<p><?php
3897
			echo wp_kses(
3898
				wptexturize(
3899
					wp_sprintf(
3900
						_nx(
3901
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3902
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3903
							count( $privacy_checks ),
3904
							'%l = list of Jetpack module/feature names',
3905
							'jetpack'
3906
						),
3907
						$module_names
3908
					)
3909
				),
3910
				array( 'strong' => true )
3911
			);
3912
3913
			echo "\n<br />\n";
3914
3915
			echo wp_kses(
3916
				sprintf(
3917
					_nx(
3918
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3919
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3920
						count( $privacy_checks ),
3921
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3922
						'jetpack'
3923
					),
3924
					wp_nonce_url(
3925
						Jetpack::admin_url(
3926
							array(
3927
								'page'   => 'jetpack',
3928
								'action' => 'deactivate',
3929
								'module' => urlencode( $module_slugs ),
3930
							)
3931
						),
3932
						"jetpack_deactivate-$module_slugs"
3933
					),
3934
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3935
				),
3936
				array( 'a' => array( 'href' => true, 'title' => true ) )
3937
			);
3938
		?></p>
3939
	</div>
3940
</div>
3941
<?php endif;
3942
	// only display the notice if the other stuff is not there
3943
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3944
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3945
			$this->opt_in_jetpack_manage_notice();
3946
		}
3947
	}
3948
3949
	/**
3950
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3951
	 */
3952
	function stat( $group, $detail ) {
3953
		if ( ! isset( $this->stats[ $group ] ) )
3954
			$this->stats[ $group ] = array();
3955
		$this->stats[ $group ][] = $detail;
3956
	}
3957
3958
	/**
3959
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3960
	 */
3961
	function do_stats( $method = '' ) {
3962
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3963
			foreach ( $this->stats as $group => $stats ) {
3964
				if ( is_array( $stats ) && count( $stats ) ) {
3965
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3966
					if ( 'server_side' === $method ) {
3967
						self::do_server_side_stat( $args );
3968
					} else {
3969
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3970
					}
3971
				}
3972
				unset( $this->stats[ $group ] );
3973
			}
3974
		}
3975
	}
3976
3977
	/**
3978
	 * Runs stats code for a one-off, server-side.
3979
	 *
3980
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3981
	 *
3982
	 * @return bool If it worked.
3983
	 */
3984
	static function do_server_side_stat( $args ) {
3985
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3986
		if ( is_wp_error( $response ) )
3987
			return false;
3988
3989
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3990
			return false;
3991
3992
		return true;
3993
	}
3994
3995
	/**
3996
	 * Builds the stats url.
3997
	 *
3998
	 * @param $args array|string The arguments to append to the URL.
3999
	 *
4000
	 * @return string The URL to be pinged.
4001
	 */
4002
	static function build_stats_url( $args ) {
4003
		$defaults = array(
4004
			'v'    => 'wpcom2',
4005
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4006
		);
4007
		$args     = wp_parse_args( $args, $defaults );
4008
		/**
4009
		 * Filter the URL used as the Stats tracking pixel.
4010
		 *
4011
		 * @since 2.3.2
4012
		 *
4013
		 * @param string $url Base URL used as the Stats tracking pixel.
4014
		 */
4015
		$base_url = apply_filters(
4016
			'jetpack_stats_base_url',
4017
			'https://pixel.wp.com/g.gif'
4018
		);
4019
		$url      = add_query_arg( $args, $base_url );
4020
		return $url;
4021
	}
4022
4023
	static function translate_current_user_to_role() {
4024
		foreach ( self::$capability_translations as $role => $cap ) {
4025
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4026
				return $role;
4027
			}
4028
		}
4029
4030
		return false;
4031
	}
4032
4033
	static function translate_role_to_cap( $role ) {
4034
		if ( ! isset( self::$capability_translations[$role] ) ) {
4035
			return false;
4036
		}
4037
4038
		return self::$capability_translations[$role];
4039
	}
4040
4041
	static function sign_role( $role ) {
4042
		if ( ! $user_id = (int) get_current_user_id() ) {
4043
			return false;
4044
		}
4045
4046
		$token = Jetpack_Data::get_access_token();
4047
		if ( ! $token || is_wp_error( $token ) ) {
4048
			return false;
4049
		}
4050
4051
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4052
	}
4053
4054
4055
	/**
4056
	 * Builds a URL to the Jetpack connection auth page
4057
	 *
4058
	 * @since 3.9.5
4059
	 *
4060
	 * @param bool $raw If true, URL will not be escaped.
4061
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4062
	 *                              If string, will be a custom redirect.
4063
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4064
	 *
4065
	 * @return string Connect URL
4066
	 */
4067
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4068
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4069
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4070
			if( is_network_admin() ) {
4071
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4072
			}
4073
		} else {
4074
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4075
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4076
			}
4077
4078
			$role = self::translate_current_user_to_role();
4079
			$signed_role = self::sign_role( $role );
4080
4081
			$user = wp_get_current_user();
4082
4083
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4084
			$redirect = $redirect
4085
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4086
				: $jetpack_admin_page;
4087
4088
			if( isset( $_REQUEST['is_multisite'] ) ) {
4089
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4090
			}
4091
4092
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4093
			@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...
4094
4095
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4096
				? get_site_icon_url()
4097
				: false;
4098
4099
			/**
4100
			 * Filter the type of authorization.
4101
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4102
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4103
			 *
4104
			 * @since 4.3.3
4105
			 *
4106
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4107
			 */
4108
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4109
4110
			$args = urlencode_deep(
4111
				array(
4112
					'response_type' => 'code',
4113
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4114
					'redirect_uri'  => add_query_arg(
4115
						array(
4116
							'action'   => 'authorize',
4117
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4118
							'redirect' => urlencode( $redirect ),
4119
						),
4120
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4121
					),
4122
					'state'         => $user->ID,
4123
					'scope'         => $signed_role,
4124
					'user_email'    => $user->user_email,
4125
					'user_login'    => $user->user_login,
4126
					'is_active'     => Jetpack::is_active(),
4127
					'jp_version'    => JETPACK__VERSION,
4128
					'auth_type'     => $auth_type,
4129
					'secret'        => $secret,
4130
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4131
					'blogname'      => get_option( 'blogname' ),
4132
					'site_url'      => site_url(),
4133
					'home_url'      => home_url(),
4134
					'site_icon'     => $site_icon,
4135
				)
4136
			);
4137
4138
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4139
		}
4140
4141
		if ( $from ) {
4142
			$url = add_query_arg( 'from', $from, $url );
4143
		}
4144
4145
		if ( isset( $_GET['calypso_env'] ) ) {
4146
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4147
		}
4148
4149
		return $raw ? $url : esc_url( $url );
4150
	}
4151
4152
	function build_reconnect_url( $raw = false ) {
4153
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4154
		return $raw ? $url : esc_url( $url );
4155
	}
4156
4157
	public static function admin_url( $args = null ) {
4158
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4159
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4160
		return $url;
4161
	}
4162
4163
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4164
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4165
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4166
	}
4167
4168
	function dismiss_jetpack_notice() {
4169
4170
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4171
			return;
4172
		}
4173
4174
		switch( $_GET['jetpack-notice'] ) {
4175
			case 'dismiss':
4176
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4177
4178
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4179
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4180
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4181
				}
4182
				break;
4183 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...
4184
4185
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4186
					// Don't show the banner again
4187
4188
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4189
					// redirect back to the page that had the notice
4190
					if ( wp_get_referer() ) {
4191
						wp_safe_redirect( wp_get_referer() );
4192
					} else {
4193
						// Take me to Jetpack
4194
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4195
					}
4196
				}
4197
				break;
4198 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...
4199
4200
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4201
					// Don't show the banner again
4202
4203
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4204
					// redirect back to the page that had the notice
4205
					if ( wp_get_referer() ) {
4206
						wp_safe_redirect( wp_get_referer() );
4207
					} else {
4208
						// Take me to Jetpack
4209
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4210
					}
4211
				}
4212
				break;
4213
			case 'jetpack-manage-opt-in':
4214
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4215
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4216
4217
					$redirection_url = Jetpack::admin_url();
4218
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4219
4220
					// Don't redirect form the Jetpack Setting Page
4221
					$referer_parsed = parse_url ( wp_get_referer() );
4222
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4223
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4224
						// Take the user to Jetpack home except when on the setting page
4225
						$redirection_url = wp_get_referer();
4226
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4227
					}
4228
					// Also update the JSON API FULL MANAGEMENT Option
4229
					Jetpack::activate_module( 'manage', false, false );
4230
4231
					// Special Message when option in.
4232
					Jetpack::state( 'optin-manage', 'true' );
4233
					// Activate the Module if not activated already
4234
4235
					// Redirect properly
4236
					wp_safe_redirect( $redirection_url );
4237
4238
				}
4239
				break;
4240
		}
4241
	}
4242
4243
	function debugger_page() {
4244
		nocache_headers();
4245
		if ( ! current_user_can( 'manage_options' ) ) {
4246
			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...
4247
		}
4248
		Jetpack_Debugger::jetpack_debug_display_handler();
4249
		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...
4250
	}
4251
4252
	public static function admin_screen_configure_module( $module_id ) {
4253
4254
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4255
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4256
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4257
				/**
4258
				 * Fires to diplay a custom module activation screen.
4259
				 *
4260
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4261
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4262
				 *
4263
				 * @module manage
4264
				 *
4265
				 * @since 3.8.0
4266
				 *
4267
				 * @param int $module_id Module ID.
4268
				 */
4269
				do_action( 'display_activate_module_setting_' . $module_id );
4270
			} else {
4271
				self::display_activate_module_link( $module_id );
4272
			}
4273
4274
			return false;
4275
		} ?>
4276
4277
		<div id="jp-settings-screen" style="position: relative">
4278
			<h3>
4279
			<?php
4280
				$module = Jetpack::get_module( $module_id );
4281
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4282
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4283
			?>
4284
			</h3>
4285
			<?php
4286
				/**
4287
				 * Fires within the displayed message when a feature configuation is updated.
4288
				 *
4289
				 * @since 3.4.0
4290
				 *
4291
				 * @param int $module_id Module ID.
4292
				 */
4293
				do_action( 'jetpack_notices_update_settings', $module_id );
4294
				/**
4295
				 * Fires when a feature configuation screen is loaded.
4296
				 * The dynamic part of the hook, $module_id, is the module ID.
4297
				 *
4298
				 * @since 1.1.0
4299
				 */
4300
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4301
			?>
4302
		</div><?php
4303
	}
4304
4305
	/**
4306
	 * Display link to activate the module to see the settings screen.
4307
	 * @param  string $module_id
4308
	 * @return null
4309
	 */
4310
	public static function display_activate_module_link( $module_id ) {
4311
4312
		$info =  Jetpack::get_module( $module_id );
4313
		$extra = '';
4314
		$activate_url = wp_nonce_url(
4315
				Jetpack::admin_url(
4316
					array(
4317
						'page'   => 'jetpack',
4318
						'action' => 'activate',
4319
						'module' => $module_id,
4320
					)
4321
				),
4322
				"jetpack_activate-$module_id"
4323
			);
4324
4325
		?>
4326
4327
		<div class="wrap configure-module">
4328
			<div id="jp-settings-screen">
4329
				<?php
4330
				if ( $module_id == 'json-api' ) {
4331
4332
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4333
4334
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4335
4336
					$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' );
4337
4338
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4339
				} ?>
4340
4341
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4342
				<div class="narrow">
4343
					<p><?php echo  $info['description']; ?></p>
4344
					<?php if( $extra ) { ?>
4345
					<p><?php echo esc_html( $extra ); ?></p>
4346
					<?php } ?>
4347
					<p>
4348
						<?php
4349
						if( wp_get_referer() ) {
4350
							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() );
4351
						} else {
4352
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4353
						} ?>
4354
					</p>
4355
				</div>
4356
4357
			</div>
4358
		</div>
4359
4360
		<?php
4361
	}
4362
4363
	public static function sort_modules( $a, $b ) {
4364
		if ( $a['sort'] == $b['sort'] )
4365
			return 0;
4366
4367
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4368
	}
4369
4370
	function ajax_recheck_ssl() {
4371
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4372
		$result = Jetpack::permit_ssl( true );
4373
		wp_send_json( array(
4374
			'enabled' => $result,
4375
			'message' => get_transient( 'jetpack_https_test_message' )
4376
		) );
4377
	}
4378
4379
/* Client API */
4380
4381
	/**
4382
	 * Returns the requested Jetpack API URL
4383
	 *
4384
	 * @return string
4385
	 */
4386
	public static function api_url( $relative_url ) {
4387
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4388
	}
4389
4390
	/**
4391
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4392
	 */
4393
	public static function fix_url_for_bad_hosts( $url ) {
4394
		if ( 0 !== strpos( $url, 'https://' ) ) {
4395
			return $url;
4396
		}
4397
4398
		switch ( JETPACK_CLIENT__HTTPS ) {
4399
			case 'ALWAYS' :
4400
				return $url;
4401
			case 'NEVER' :
4402
				return set_url_scheme( $url, 'http' );
4403
			// default : case 'AUTO' :
4404
		}
4405
4406
		// we now return the unmodified SSL URL by default, as a security precaution
4407
		return $url;
4408
	}
4409
4410
	/**
4411
	 * Checks to see if the URL is using SSL to connect with Jetpack
4412
	 *
4413
	 * @since 2.3.3
4414
	 * @return boolean
4415
	 */
4416
	public static function permit_ssl( $force_recheck = false ) {
4417
		// Do some fancy tests to see if ssl is being supported
4418
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4419
			$message = '';
4420
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4421
				$ssl = 0;
4422
			} else {
4423
				switch ( JETPACK_CLIENT__HTTPS ) {
4424
					case 'NEVER':
4425
						$ssl = 0;
4426
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4427
						break;
4428
					case 'ALWAYS':
4429
					case 'AUTO':
4430
					default:
4431
						$ssl = 1;
4432
						break;
4433
				}
4434
4435
				// If it's not 'NEVER', test to see
4436
				if ( $ssl ) {
4437
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4438
						$ssl = 0;
4439
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4440
					} else {
4441
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4442
						if ( is_wp_error( $response ) ) {
4443
							$ssl = 0;
4444
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4445
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4446
							$ssl = 0;
4447
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4448
						}
4449
					}
4450
				}
4451
			}
4452
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4453
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4454
		}
4455
4456
		return (bool) $ssl;
4457
	}
4458
4459
	/*
4460
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4461
	 */
4462
	public function alert_auto_ssl_fail() {
4463
		if ( ! current_user_can( 'manage_options' ) )
4464
			return;
4465
4466
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4467
		?>
4468
4469
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4470
			<div class="jp-banner__content">
4471
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4472
				<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>
4473
				<p>
4474
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4475
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4476
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4477
				</p>
4478
				<p>
4479
					<?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' ),
4480
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4481
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4482
				</p>
4483
			</div>
4484
		</div>
4485
		<style>
4486
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4487
		</style>
4488
		<script type="text/javascript">
4489
			jQuery( document ).ready( function( $ ) {
4490
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4491
					var $this = $( this );
4492
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4493
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4494
					e.preventDefault();
4495
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4496
					$.post( ajaxurl, data )
4497
					  .done( function( response ) {
4498
					  	if ( response.enabled ) {
4499
					  		$( '#jetpack-ssl-warning' ).hide();
4500
					  	} else {
4501
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4502
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4503
					  	}
4504
					  }.bind( $this ) );
4505
				} );
4506
			} );
4507
		</script>
4508
4509
		<?php
4510
	}
4511
4512
	/**
4513
	 * Returns the Jetpack XML-RPC API
4514
	 *
4515
	 * @return string
4516
	 */
4517
	public static function xmlrpc_api_url() {
4518
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4519
		return untrailingslashit( $base ) . '/xmlrpc.php';
4520
	}
4521
4522
	/**
4523
	 * Creates two secret tokens and the end of life timestamp for them.
4524
	 *
4525
	 * Note these tokens are unique per call, NOT static per site for connecting.
4526
	 *
4527
	 * @since 2.6
4528
	 * @return array
4529
	 */
4530
	public function generate_secrets( $action, $exp = 600 ) {
4531
	    $secret = wp_generate_password( 32, false ) // secret_1
4532
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4533
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4534
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4535
		Jetpack_Options::update_option( $action, $secret );
4536
	    return Jetpack_Options::get_option( $action );
4537
	}
4538
4539
	/**
4540
	 * Builds the timeout limit for queries talking with the wpcom servers.
4541
	 *
4542
	 * Based on local php max_execution_time in php.ini
4543
	 *
4544
	 * @since 2.6
4545
	 * @return int
4546
	 **/
4547
	public function get_remote_query_timeout_limit() {
4548
	    $timeout = (int) ini_get( 'max_execution_time' );
4549
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4550
				$timeout = 30;
4551
	    return intval( $timeout / 2 );
4552
	}
4553
4554
4555
	/**
4556
	 * Takes the response from the Jetpack register new site endpoint and
4557
	 * verifies it worked properly.
4558
	 *
4559
	 * @since 2.6
4560
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4561
	 **/
4562
	public function validate_remote_register_response( $response ) {
4563
	  if ( is_wp_error( $response ) ) {
4564
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4565
		}
4566
4567
		$code   = wp_remote_retrieve_response_code( $response );
4568
		$entity = wp_remote_retrieve_body( $response );
4569
		if ( $entity )
4570
			$registration_response = json_decode( $entity );
4571
		else
4572
			$registration_response = false;
4573
4574
		$code_type = intval( $code / 100 );
4575
		if ( 5 == $code_type ) {
4576
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4577
		} elseif ( 408 == $code ) {
4578
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4579
		} elseif ( ! empty( $registration_response->error ) ) {
4580
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4581
				$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' );
4582
			} else {
4583
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4584
			}
4585
4586
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4587
		} elseif ( 200 != $code ) {
4588
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4589
		}
4590
4591
		// Jetpack ID error block
4592
		if ( empty( $registration_response->jetpack_id ) ) {
4593
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4594
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4595
			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 );
4596
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4597
			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 );
4598
		}
4599
4600
	    return $registration_response;
4601
	}
4602
	/**
4603
	 * @return bool|WP_Error
4604
	 */
4605
	public static function register() {
4606
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4607
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4608
4609
		@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...
4610 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4611
			return new Jetpack_Error( 'missing_secrets' );
4612
		}
4613
4614
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4615
4616
		$gmt_offset = get_option( 'gmt_offset' );
4617
		if ( ! $gmt_offset ) {
4618
			$gmt_offset = 0;
4619
		}
4620
4621
		$stats_options = get_option( 'stats_options' );
4622
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4623
4624
		$args = array(
4625
			'method'  => 'POST',
4626
			'body'    => array(
4627
				'siteurl'         => site_url(),
4628
				'home'            => home_url(),
4629
				'gmt_offset'      => $gmt_offset,
4630
				'timezone_string' => (string) get_option( 'timezone_string' ),
4631
				'site_name'       => (string) get_option( 'blogname' ),
4632
				'secret_1'        => $secret_1,
4633
				'secret_2'        => $secret_2,
4634
				'site_lang'       => get_locale(),
4635
				'timeout'         => $timeout,
4636
				'stats_id'        => $stats_id,
4637
				'state'           => get_current_user_id(),
4638
			),
4639
			'headers' => array(
4640
				'Accept' => 'application/json',
4641
			),
4642
			'timeout' => $timeout,
4643
		);
4644
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4645
4646
		// Make sure the response is valid and does not contain any Jetpack errors
4647
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4648
		if ( is_wp_error( $registration_details ) ) {
4649
		    return $registration_details;
4650
		} elseif ( ! $registration_details ) {
4651
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
4652
		}
4653
4654 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4655
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
4656
		}
4657
4658
		if ( isset( $registration_details->jetpack_public ) ) {
4659
			$jetpack_public = (int) $registration_details->jetpack_public;
4660
		} else {
4661
			$jetpack_public = false;
4662
		}
4663
4664
		Jetpack_Options::update_options(
4665
			array(
4666
				'id'         => (int)    $registration_details->jetpack_id,
4667
				'blog_token' => (string) $registration_details->jetpack_secret,
4668
				'public'     => $jetpack_public,
4669
			)
4670
		);
4671
4672
		/**
4673
		 * Fires when a site is registered on WordPress.com.
4674
		 *
4675
		 * @since 3.7.0
4676
		 *
4677
		 * @param int $json->jetpack_id Jetpack Blog ID.
4678
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4679
		 * @param int|bool $jetpack_public Is the site public.
4680
		 */
4681
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
4682
4683
		// Initialize Jump Start for the first and only time.
4684
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4685
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4686
4687
			$jetpack = Jetpack::init();
4688
4689
			$jetpack->stat( 'jumpstart', 'unique-views' );
4690
			$jetpack->do_stats( 'server_side' );
4691
		};
4692
4693
		return true;
4694
	}
4695
4696
	/**
4697
	 * If the db version is showing something other that what we've got now, bump it to current.
4698
	 *
4699
	 * @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...
4700
	 */
4701
	public static function maybe_set_version_option() {
4702
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4703
		if ( JETPACK__VERSION != $version ) {
4704
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4705
4706
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4707
				/** This action is documented in class.jetpack.php */
4708
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4709
			}
4710
4711
			return true;
4712
		}
4713
		return false;
4714
	}
4715
4716
/* Client Server API */
4717
4718
	/**
4719
	 * Loads the Jetpack XML-RPC client
4720
	 */
4721
	public static function load_xml_rpc_client() {
4722
		require_once ABSPATH . WPINC . '/class-IXR.php';
4723
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4724
	}
4725
4726
	/**
4727
	 * Resets the saved authentication state in between testing requests.
4728
	 */
4729
	public function reset_saved_auth_state() {
4730
		$this->xmlrpc_verification = null;
4731
		$this->rest_authentication_status = null;
4732
	}
4733
4734
	function verify_xml_rpc_signature() {
4735
		if ( $this->xmlrpc_verification ) {
4736
			return $this->xmlrpc_verification;
4737
		}
4738
4739
		// It's not for us
4740
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4741
			return false;
4742
		}
4743
4744
		@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...
4745
		if (
4746
			empty( $token_key )
4747
		||
4748
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4749
		) {
4750
			return false;
4751
		}
4752
4753
		if ( '0' === $user_id ) {
4754
			$token_type = 'blog';
4755
			$user_id = 0;
4756
		} else {
4757
			$token_type = 'user';
4758
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4759
				return false;
4760
			}
4761
			$user_id = (int) $user_id;
4762
4763
			$user = new WP_User( $user_id );
4764
			if ( ! $user || ! $user->exists() ) {
4765
				return false;
4766
			}
4767
		}
4768
4769
		$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...
4770
		if ( ! $token ) {
4771
			return false;
4772
		}
4773
4774
		$token_check = "$token_key.";
4775
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4776
			return false;
4777
		}
4778
4779
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4780
4781
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4782
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4783
			$post_data   = $_POST;
4784
			$file_hashes = array();
4785
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4786
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4787
					continue;
4788
				}
4789
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4790
				$file_hashes[$post_data_key] = $post_data_value;
4791
			}
4792
4793
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4794
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4795
				$post_data[$post_data_key] = $post_data_value;
4796
			}
4797
4798
			ksort( $post_data );
4799
4800
			$body = http_build_query( stripslashes_deep( $post_data ) );
4801
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4802
			$body = file_get_contents( 'php://input' );
4803
		} else {
4804
			$body = null;
4805
		}
4806
4807
		$signature = $jetpack_signature->sign_current_request(
4808
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4809
		);
4810
4811
		if ( ! $signature ) {
4812
			return false;
4813
		} else if ( is_wp_error( $signature ) ) {
4814
			return $signature;
4815
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4816
			return false;
4817
		}
4818
4819
		$timestamp = (int) $_GET['timestamp'];
4820
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4821
4822
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4823
			return false;
4824
		}
4825
4826
		$this->xmlrpc_verification = array(
4827
			'type'    => $token_type,
4828
			'user_id' => $token->external_user_id,
4829
		);
4830
4831
		return $this->xmlrpc_verification;
4832
	}
4833
4834
	/**
4835
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4836
	 */
4837
	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...
4838
		if ( is_a( $user, 'WP_User' ) ) {
4839
			return $user;
4840
		}
4841
4842
		$token_details = $this->verify_xml_rpc_signature();
4843
4844
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4845
			return $user;
4846
		}
4847
4848
		if ( 'user' !== $token_details['type'] ) {
4849
			return $user;
4850
		}
4851
4852
		if ( ! $token_details['user_id'] ) {
4853
			return $user;
4854
		}
4855
4856
		nocache_headers();
4857
4858
		return new WP_User( $token_details['user_id'] );
4859
	}
4860
4861
	// Authenticates requests from Jetpack server to WP REST API endpoints.
4862
	// Uses the existing XMLRPC request signing implementation.
4863
	function wp_rest_authenticate( $user ) {
4864
		if ( ! empty( $user ) ) {
4865
			// Another authentication method is in effect.
4866
			return $user;
4867
		}
4868
4869
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
4870
			// Nothing to do for this authentication method.
4871
			return null;
4872
		}
4873
4874
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
4875
			// Nothing to do for this authentication method.
4876
			return null;
4877
		}
4878
4879
		// Ensure that we always have the request body available.  At this
4880
		// point, the WP REST API code to determine the request body has not
4881
		// run yet.  That code may try to read from 'php://input' later, but
4882
		// this can only be done once per request in PHP versions prior to 5.6.
4883
		// So we will go ahead and perform this read now if needed, and save
4884
		// the request body where both the Jetpack signature verification code
4885
		// and the WP REST API code can see it.
4886
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
4887
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
4888
		}
4889
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4890
4891
		// Only support specific request parameters that have been tested and
4892
		// are known to work with signature verification.  A different method
4893
		// can be passed to the WP REST API via the '?_method=' parameter if
4894
		// needed.
4895
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
4896
			$this->rest_authentication_status = new WP_Error(
4897
				'rest_invalid_request',
4898
				__( 'This request method is not supported.', 'jetpack' ),
4899
				array( 'status' => 400 )
4900
			);
4901
			return null;
4902
		}
4903
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
4904
			$this->rest_authentication_status = new WP_Error(
4905
				'rest_invalid_request',
4906
				__( 'This request method does not support body parameters.', 'jetpack' ),
4907
				array( 'status' => 400 )
4908
			);
4909
			return null;
4910
		}
4911
4912
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
4913
			$content_type = $_SERVER['CONTENT_TYPE'];
4914
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
4915
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
4916
		}
4917
4918
		if (
4919
			isset( $content_type ) &&
4920
			$content_type !== 'application/x-www-form-urlencoded' &&
4921
			$content_type !== 'application/json'
4922
		) {
4923
			$this->rest_authentication_status = new WP_Error(
4924
				'rest_invalid_request',
4925
				__( 'This Content-Type is not supported.', 'jetpack' ),
4926
				array( 'status' => 400 )
4927
			);
4928
			return null;
4929
		}
4930
4931
		$verified = $this->verify_xml_rpc_signature();
4932
4933
		if ( is_wp_error( $verified ) ) {
4934
			$this->rest_authentication_status = $verified;
4935
			return null;
4936
		}
4937
4938
		if (
4939
			$verified &&
4940
			isset( $verified['type'] ) &&
4941
			'user' === $verified['type'] &&
4942
			! empty( $verified['user_id'] )
4943
		) {
4944
			// Authentication successful.
4945
			$this->rest_authentication_status = true;
4946
			return $verified['user_id'];
4947
		}
4948
4949
		// Something else went wrong.  Probably a signature error.
4950
		$this->rest_authentication_status = new WP_Error(
4951
			'rest_invalid_signature',
4952
			__( 'The request is not signed correctly.', 'jetpack' ),
4953
			array( 'status' => 400 )
4954
		);
4955
		return null;
4956
	}
4957
4958
	/**
4959
	 * Report authentication status to the WP REST API.
4960
	 *
4961
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
4962
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
4963
	 */
4964
	public function wp_rest_authentication_errors( $value ) {
4965
		if ( $value !== null ) {
4966
			return $value;
4967
		}
4968
		return $this->rest_authentication_status;
4969
	}
4970
4971
	function add_nonce( $timestamp, $nonce ) {
4972
		global $wpdb;
4973
		static $nonces_used_this_request = array();
4974
4975
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4976
			return $nonces_used_this_request["$timestamp:$nonce"];
4977
		}
4978
4979
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4980
		$timestamp = (int) $timestamp;
4981
		$nonce     = esc_sql( $nonce );
4982
4983
		// Raw query so we can avoid races: add_option will also update
4984
		$show_errors = $wpdb->show_errors( false );
4985
4986
		$old_nonce = $wpdb->get_row(
4987
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4988
		);
4989
4990
		if ( is_null( $old_nonce ) ) {
4991
			$return = $wpdb->query(
4992
				$wpdb->prepare(
4993
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4994
					"jetpack_nonce_{$timestamp}_{$nonce}",
4995
					time(),
4996
					'no'
4997
				)
4998
			);
4999
		} else {
5000
			$return = false;
5001
		}
5002
5003
		$wpdb->show_errors( $show_errors );
5004
5005
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5006
5007
		return $return;
5008
	}
5009
5010
	/**
5011
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5012
	 * Capture it here so we can verify the signature later.
5013
	 */
5014
	function xmlrpc_methods( $methods ) {
5015
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5016
		return $methods;
5017
	}
5018
5019
	function public_xmlrpc_methods( $methods ) {
5020
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5021
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5022
		}
5023
		return $methods;
5024
	}
5025
5026
	function jetpack_getOptions( $args ) {
5027
		global $wp_xmlrpc_server;
5028
5029
		$wp_xmlrpc_server->escape( $args );
5030
5031
		$username	= $args[1];
5032
		$password	= $args[2];
5033
5034
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5035
			return $wp_xmlrpc_server->error;
5036
		}
5037
5038
		$options = array();
5039
		$user_data = $this->get_connected_user_data();
5040
		if ( is_array( $user_data ) ) {
5041
			$options['jetpack_user_id'] = array(
5042
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5043
				'readonly'      => true,
5044
				'value'         => $user_data['ID'],
5045
			);
5046
			$options['jetpack_user_login'] = array(
5047
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5048
				'readonly'      => true,
5049
				'value'         => $user_data['login'],
5050
			);
5051
			$options['jetpack_user_email'] = array(
5052
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5053
				'readonly'      => true,
5054
				'value'         => $user_data['email'],
5055
			);
5056
			$options['jetpack_user_site_count'] = array(
5057
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5058
				'readonly'      => true,
5059
				'value'         => $user_data['site_count'],
5060
			);
5061
		}
5062
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5063
		$args = stripslashes_deep( $args );
5064
		return $wp_xmlrpc_server->wp_getOptions( $args );
5065
	}
5066
5067
	function xmlrpc_options( $options ) {
5068
		$jetpack_client_id = false;
5069
		if ( self::is_active() ) {
5070
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5071
		}
5072
		$options['jetpack_version'] = array(
5073
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5074
				'readonly'      => true,
5075
				'value'         => JETPACK__VERSION,
5076
		);
5077
5078
		$options['jetpack_client_id'] = array(
5079
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5080
				'readonly'      => true,
5081
				'value'         => $jetpack_client_id,
5082
		);
5083
		return $options;
5084
	}
5085
5086
	public static function clean_nonces( $all = false ) {
5087
		global $wpdb;
5088
5089
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5090
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5091
5092
		if ( true !== $all ) {
5093
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5094
			$sql_args[] = time() - 3600;
5095
		}
5096
5097
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5098
5099
		$sql = $wpdb->prepare( $sql, $sql_args );
5100
5101
		for ( $i = 0; $i < 1000; $i++ ) {
5102
			if ( ! $wpdb->query( $sql ) ) {
5103
				break;
5104
			}
5105
		}
5106
	}
5107
5108
	/**
5109
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5110
	 * SET: state( $key, $value );
5111
	 * GET: $value = state( $key );
5112
	 *
5113
	 * @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...
5114
	 * @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...
5115
	 * @param bool $restate private
5116
	 */
5117
	public static function state( $key = null, $value = null, $restate = false ) {
5118
		static $state = array();
5119
		static $path, $domain;
5120
		if ( ! isset( $path ) ) {
5121
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5122
			$admin_url = Jetpack::admin_url();
5123
			$bits      = parse_url( $admin_url );
5124
5125
			if ( is_array( $bits ) ) {
5126
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5127
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5128
			} else {
5129
				$path = $domain = null;
5130
			}
5131
		}
5132
5133
		// Extract state from cookies and delete cookies
5134
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5135
			$yum = $_COOKIE[ 'jetpackState' ];
5136
			unset( $_COOKIE[ 'jetpackState' ] );
5137
			foreach ( $yum as $k => $v ) {
5138
				if ( strlen( $v ) )
5139
					$state[ $k ] = $v;
5140
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5141
			}
5142
		}
5143
5144
		if ( $restate ) {
5145
			foreach ( $state as $k => $v ) {
5146
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5147
			}
5148
			return;
5149
		}
5150
5151
		// Get a state variable
5152
		if ( isset( $key ) && ! isset( $value ) ) {
5153
			if ( array_key_exists( $key, $state ) )
5154
				return $state[ $key ];
5155
			return null;
5156
		}
5157
5158
		// Set a state variable
5159
		if ( isset ( $key ) && isset( $value ) ) {
5160
			if( is_array( $value ) && isset( $value[0] ) ) {
5161
				$value = $value[0];
5162
			}
5163
			$state[ $key ] = $value;
5164
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5165
		}
5166
	}
5167
5168
	public static function restate() {
5169
		Jetpack::state( null, null, true );
5170
	}
5171
5172
	public static function check_privacy( $file ) {
5173
		static $is_site_publicly_accessible = null;
5174
5175
		if ( is_null( $is_site_publicly_accessible ) ) {
5176
			$is_site_publicly_accessible = false;
5177
5178
			Jetpack::load_xml_rpc_client();
5179
			$rpc = new Jetpack_IXR_Client();
5180
5181
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5182
			if ( $success ) {
5183
				$response = $rpc->getResponse();
5184
				if ( $response ) {
5185
					$is_site_publicly_accessible = true;
5186
				}
5187
			}
5188
5189
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5190
		}
5191
5192
		if ( $is_site_publicly_accessible ) {
5193
			return;
5194
		}
5195
5196
		$module_slug = self::get_module_slug( $file );
5197
5198
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5199
		if ( ! $privacy_checks ) {
5200
			$privacy_checks = $module_slug;
5201
		} else {
5202
			$privacy_checks .= ",$module_slug";
5203
		}
5204
5205
		Jetpack::state( 'privacy_checks', $privacy_checks );
5206
	}
5207
5208
	/**
5209
	 * Helper method for multicall XMLRPC.
5210
	 */
5211
	public static function xmlrpc_async_call() {
5212
		global $blog_id;
5213
		static $clients = array();
5214
5215
		$client_blog_id = is_multisite() ? $blog_id : 0;
5216
5217
		if ( ! isset( $clients[$client_blog_id] ) ) {
5218
			Jetpack::load_xml_rpc_client();
5219
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5220
			if ( function_exists( 'ignore_user_abort' ) ) {
5221
				ignore_user_abort( true );
5222
			}
5223
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5224
		}
5225
5226
		$args = func_get_args();
5227
5228
		if ( ! empty( $args[0] ) ) {
5229
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5230
		} elseif ( is_multisite() ) {
5231
			foreach ( $clients as $client_blog_id => $client ) {
5232
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5233
					continue;
5234
				}
5235
5236
				$switch_success = switch_to_blog( $client_blog_id, true );
5237
				if ( ! $switch_success ) {
5238
					continue;
5239
				}
5240
5241
				flush();
5242
				$client->query();
5243
5244
				restore_current_blog();
5245
			}
5246
		} else {
5247
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5248
				flush();
5249
				$clients[0]->query();
5250
			}
5251
		}
5252
	}
5253
5254
	public static function staticize_subdomain( $url ) {
5255
5256
		// Extract hostname from URL
5257
		$host = parse_url( $url, PHP_URL_HOST );
5258
5259
		// Explode hostname on '.'
5260
		$exploded_host = explode( '.', $host );
5261
5262
		// Retrieve the name and TLD
5263
		if ( count( $exploded_host ) > 1 ) {
5264
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5265
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5266
			// Rebuild domain excluding subdomains
5267
			$domain = $name . '.' . $tld;
5268
		} else {
5269
			$domain = $host;
5270
		}
5271
		// Array of Automattic domains
5272
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5273
5274
		// Return $url if not an Automattic domain
5275
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5276
			return $url;
5277
		}
5278
5279
		if ( is_ssl() ) {
5280
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5281
		}
5282
5283
		srand( crc32( basename( $url ) ) );
5284
		$static_counter = rand( 0, 2 );
5285
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5286
5287
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5288
	}
5289
5290
/* JSON API Authorization */
5291
5292
	/**
5293
	 * Handles the login action for Authorizing the JSON API
5294
	 */
5295
	function login_form_json_api_authorization() {
5296
		$this->verify_json_api_authorization_request();
5297
5298
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5299
5300
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5301
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5302
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5303
	}
5304
5305
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5306
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5307
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5308
			return $url;
5309
		}
5310
5311
		$parsed_url = parse_url( $url );
5312
		$url = strtok( $url, '?' );
5313
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5314
		if ( ! empty( $parsed_url['query'] ) )
5315
			$url .= "&{$parsed_url['query']}";
5316
5317
		return $url;
5318
	}
5319
5320
	// Make sure the POSTed request is handled by the same action
5321
	function preserve_action_in_login_form_for_json_api_authorization() {
5322
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5323
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5324
	}
5325
5326
	// If someone logs in to approve API access, store the Access Code in usermeta
5327
	function store_json_api_authorization_token( $user_login, $user ) {
5328
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5329
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5330
		$token = wp_generate_password( 32, false );
5331
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5332
	}
5333
5334
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5335
	function allow_wpcom_public_api_domain( $domains ) {
5336
		$domains[] = 'public-api.wordpress.com';
5337
		return $domains;
5338
	}
5339
5340
	// Add the Access Code details to the public-api.wordpress.com redirect
5341
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5342
		return add_query_arg(
5343
			urlencode_deep(
5344
				array(
5345
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5346
					'jetpack-user-id' => (int) $user->ID,
5347
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5348
				)
5349
			),
5350
			$redirect_to
5351
		);
5352
	}
5353
5354
5355
	/**
5356
	 * Verifies the request by checking the signature
5357
	 *
5358
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5359
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5360
	 *
5361
	 * @param null|array $environment
5362
	 */
5363
	function verify_json_api_authorization_request( $environment = null ) {
5364
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5365
5366
		$environment = is_null( $environment )
5367
			? $_REQUEST
5368
			: $environment;
5369
5370
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envToken is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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