Completed
Push — enhance/plugin-list-connection... ( 80d6d5 )
by
unknown
204:48 queued 202:35
created

Jetpack::display_activate_module_link()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 52
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 33
nc 8
nop 1
dl 0
loc 52
rs 8.9408
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'jetpack-responsive-videos-style',
46
		'jetpack-social-menu',
47
		'tiled-gallery',
48
		'jetpack_display_posts_widget',
49
		'gravatar-profile-widget',
50
		'goodreads-widget',
51
		'jetpack_social_media_icons_widget',
52
		'jetpack-top-posts-widget',
53
		'jetpack_image_widget',
54
	);
55
56
	public $plugins_to_deactivate = array(
57
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
59
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
60
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
61
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
62
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
63
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
64
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
65
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
66
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
67
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
68
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
69
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
70
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
71
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
72
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
73
	);
74
75
	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...
76
		'administrator' => 'manage_options',
77
		'editor'        => 'edit_others_posts',
78
		'author'        => 'publish_posts',
79
		'contributor'   => 'edit_posts',
80
		'subscriber'    => 'read',
81
	);
82
83
	/**
84
	 * Map of modules that have conflicts with plugins and should not be auto-activated
85
	 * if the plugins are active.  Used by filter_default_modules
86
	 *
87
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
88
	 * change `module-slug` and add this to your plugin:
89
	 *
90
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
91
	 * function my_jetpack_get_default_modules( $modules ) {
92
	 *     return array_diff( $modules, array( 'module-slug' ) );
93
	 * }
94
	 *
95
	 * @var array
96
	 */
97
	private $conflicting_plugins = array(
98
		'comments'          => array(
99
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
100
			'Disqus'                               => 'disqus-comment-system/disqus.php',
101
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
102
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
103
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
104
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
105
		),
106
		'contact-form'      => array(
107
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
108
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
109
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
110
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
111
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
112
		),
113
		'minileven'         => array(
114
			'WPtouch'                              => 'wptouch/wptouch.php',
115
		),
116
		'latex'             => array(
117
			'LaTeX for WordPress'                  => 'latex/latex.php',
118
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
119
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
120
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
121
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
122
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
123
		),
124
		'protect'           => array(
125
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
126
			'Captcha'                              => 'captcha/captcha.php',
127
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
128
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
129
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
130
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
131
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
132
			'Security-protection'                  => 'security-protection/security-protection.php',
133
			'Login Security'                       => 'login-security/login-security.php',
134
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
135
			'Wordfence Security'                   => 'wordfence/wordfence.php',
136
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
137
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
138
		),
139
		'random-redirect'   => array(
140
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
141
		),
142
		'related-posts'     => array(
143
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
144
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
145
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
146
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
147
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
148
			'outbrain'                             => 'outbrain/outbrain.php',
149
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
150
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
151
		),
152
		'sharedaddy'        => array(
153
			'AddThis'                              => 'addthis/addthis_social_widget.php',
154
			'Add To Any'                           => 'add-to-any/add-to-any.php',
155
			'ShareThis'                            => 'share-this/sharethis.php',
156
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
157
		),
158
		'verification-tools' => array(
159
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
160
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
161
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
162
		),
163
		'widget-visibility' => array(
164
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
165
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
166
		),
167
		'sitemaps' => array(
168
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
169
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
170
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
171
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
172
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
173
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
174
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
175
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
176
			'Sitemap'                              => 'sitemap/sitemap.php',
177
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
178
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
179
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
180
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
181
		),
182
	);
183
184
	/**
185
	 * Plugins for which we turn off our Facebook OG Tags implementation.
186
	 *
187
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
188
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
189
	 *
190
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
191
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
192
	 */
193
	private $open_graph_conflicting_plugins = array(
194
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
195
		                                                         // 2 Click Social Media Buttons
196
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
197
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
198
		'autodescription/autodescription.php',                   // The SEO Framework
199
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
200
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
201
		                                                         // Open Graph Meta Tags by Heateor
202
		'facebook/facebook.php',                                 // Facebook (official plugin)
203
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
204
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
205
		                                                         // Facebook Featured Image & OG Meta Tags
206
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
207
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
208
		                                                         // Facebook Open Graph Meta Tags for WordPress
209
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
210
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
211
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
212
		                                                         // Fedmich's Facebook Open Graph Meta
213
		'header-footer/plugin.php',                              // Header and Footer
214
		'network-publisher/networkpub.php',                      // Network Publisher
215
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
216
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
217
		                                                         // NextScripts SNAP
218
		'og-tags/og-tags.php',                                   // OG Tags
219
		'opengraph/opengraph.php',                               // Open Graph
220
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
221
		                                                         // Open Graph Protocol Framework
222
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
223
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
224
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
225
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
226
		'sharepress/sharepress.php',                             // SharePress
227
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
228
		'social-discussions/social-discussions.php',             // Social Discussions
229
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
230
		'socialize/socialize.php',                               // Socialize
231
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
232
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
233
		                                                         // Tweet, Like, Google +1 and Share
234
		'wordbooker/wordbooker.php',                             // Wordbooker
235
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
236
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
237
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
238
		                                                         // WP Facebook Like Send & Open Graph Meta
239
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
240
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
241
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
242
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
243
	);
244
245
	/**
246
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
247
	 */
248
	private $twitter_cards_conflicting_plugins = array(
249
	//	'twitter/twitter.php',                       // The official one handles this on its own.
250
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
251
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
252
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
253
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
254
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
255
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
256
		'twitter-cards/twitter-cards.php',           // Twitter Cards
257
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
258
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
259
	);
260
261
	/**
262
	 * Message to display in admin_notice
263
	 * @var string
264
	 */
265
	public $message = '';
266
267
	/**
268
	 * Error to display in admin_notice
269
	 * @var string
270
	 */
271
	public $error = '';
272
273
	/**
274
	 * Modules that need more privacy description.
275
	 * @var string
276
	 */
277
	public $privacy_checks = '';
278
279
	/**
280
	 * Stats to record once the page loads
281
	 *
282
	 * @var array
283
	 */
284
	public $stats = array();
285
286
	/**
287
	 * Jetpack_Sync object
288
	 */
289
	public $sync;
290
291
	/**
292
	 * Verified data for JSON authorization request
293
	 */
294
	public $json_api_authorization_request = array();
295
296
	/**
297
	 * Holds the singleton instance of this class
298
	 * @since 2.3.3
299
	 * @var Jetpack
300
	 */
301
	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...
302
303
	/**
304
	 * Singleton
305
	 * @static
306
	 */
307
	public static function init() {
308
		if ( ! self::$instance ) {
309
			self::$instance = new Jetpack;
310
311
			self::$instance->plugin_upgrade();
312
		}
313
314
		return self::$instance;
315
	}
316
317
	/**
318
	 * Must never be called statically
319
	 */
320
	function plugin_upgrade() {
321
		if ( Jetpack::is_active() ) {
322
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
323
			if ( JETPACK__VERSION != $version ) {
324
325
				// Check which active modules actually exist and remove others from active_modules list
326
				$unfiltered_modules = Jetpack::get_active_modules();
327
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
328
				if ( array_diff( $unfiltered_modules, $modules ) ) {
329
					Jetpack::update_active_modules( $modules );
330
				}
331
332
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
333
334
				// Upgrade to 4.3.0
335
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
336
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
337
				}
338
339
				Jetpack::maybe_set_version_option();
340
			}
341
		}
342
	}
343
344
	static function activate_manage( ) {
345
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
346
			self::activate_module( 'manage', false, false );
347
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
348
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
349
		}
350
	}
351
352
	static function update_active_modules( $modules ) {
353
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
354
355
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
356
357
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
358
			$new_active_modules = array_diff( $modules, $current_modules );
359
			foreach( $new_active_modules as $module ) {
360
				/**
361
				 * Fires when a specific module is activated.
362
				 *
363
				 * @since 1.9.0
364
				 *
365
				 * @param string $module Module slug.
366
				 * @param boolean $success whether the module was activated. @since 4.2
367
				 */
368
				do_action( 'jetpack_activate_module', $module, $success );
369
370
				/**
371
				 * Fires when a module is activated.
372
				 * The dynamic part of the filter, $module, is the module slug.
373
				 *
374
				 * @since 1.9.0
375
				 *
376
				 * @param string $module Module slug.
377
				 */
378
				do_action( "jetpack_activate_module_$module", $module );
379
			}
380
381
			$new_deactive_modules = array_diff( $current_modules, $modules );
382
			foreach( $new_deactive_modules as $module ) {
383
				/**
384
				 * Fired after a module has been deactivated.
385
				 *
386
				 * @since 4.2.0
387
				 *
388
				 * @param string $module Module slug.
389
				 * @param boolean $success whether the module was deactivated.
390
				 */
391
				do_action( 'jetpack_deactivate_module', $module, $success );
392
				/**
393
				 * Fires when a module is deactivated.
394
				 * The dynamic part of the filter, $module, is the module slug.
395
				 *
396
				 * @since 1.9.0
397
				 *
398
				 * @param string $module Module slug.
399
				 */
400
				do_action( "jetpack_deactivate_module_$module", $module );
401
			}
402
		}
403
404
		return $success;
405
	}
406
407
	static function delete_active_modules() {
408
		self::update_active_modules( array() );
409
	}
410
411
	/**
412
	 * Constructor.  Initializes WordPress hooks
413
	 */
414
	private function __construct() {
415
		/*
416
		 * Check for and alert any deprecated hooks
417
		 */
418
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
419
420
421
		/*
422
		 * Load things that should only be in Network Admin.
423
		 *
424
		 * For now blow away everything else until a more full
425
		 * understanding of what is needed at the network level is
426
		 * available
427
		 */
428
		if( is_multisite() ) {
429
			Jetpack_Network::init();
430
		}
431
432
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
433
434
		// Unlink user before deleting the user from .com
435
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
436
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
437
438
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
439
			@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...
440
441
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
442
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
443
444
			$this->require_jetpack_authentication();
445
446
			if ( Jetpack::is_active() ) {
447
				// Hack to preserve $HTTP_RAW_POST_DATA
448
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
449
450
				$signed = $this->verify_xml_rpc_signature();
451
				if ( $signed && ! is_wp_error( $signed ) ) {
452
					// The actual API methods.
453
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
454
				} else {
455
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
456
					// active Jetpack connection, so that additional users can link their account.
457
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
458
				}
459
			} else {
460
				// The bootstrap API methods.
461
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
462
			}
463
464
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
465
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
466
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
467
			$this->require_jetpack_authentication();
468
			$this->add_remote_request_handlers();
469
		} else {
470
			if ( Jetpack::is_active() ) {
471
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
472
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
473
			}
474
		}
475
476
		if ( Jetpack::is_active() ) {
477
			Jetpack_Heartbeat::init();
478
		}
479
480
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
481
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
482
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
483
		}
484
485
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
486
487
		add_action( 'admin_init', array( $this, 'admin_init' ) );
488
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
489
490
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
491
492
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
493
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
494
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
495
496
		// returns HTTPS support status
497
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
498
499
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
500
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
501
502
		// JITM AJAX callback function
503
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
504
505
		// Universal ajax callback for all tracking events triggered via js
506
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
507
508
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
509
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
510
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
511
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
512
513
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
514
515
		/**
516
		 * These actions run checks to load additional files.
517
		 * They check for external files or plugins, so they need to run as late as possible.
518
		 */
519
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
520
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
521
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
522
523
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
524
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
525
526
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
527
528
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
529
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
530
531
		// A filter to control all just in time messages
532
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
533
534
		/**
535
		 * This is the hack to concatinate all css files into one.
536
		 * For description and reasoning see the implode_frontend_css method
537
		 *
538
		 * Super late priority so we catch all the registered styles
539
		 */
540
		if( !is_admin() ) {
541
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
542
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
543
		}
544
545
	}
546
547
	function jetpack_admin_ajax_tracks_callback() {
548
		// Check for nonce
549
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
550
			wp_die( 'Permissions check failed.' );
551
		}
552
553
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
554
			wp_die( 'No valid event name or type.' );
555
		}
556
557
		$tracks_data = array();
558
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
559
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
560
		}
561
562
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
563
		wp_send_json_success();
564
		wp_die();
565
	}
566
567
	/**
568
	 * The callback for the JITM ajax requests.
569
	 */
570
	function jetpack_jitm_ajax_callback() {
571
		// Check for nonce
572
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
573
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
574
		}
575
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
576
			$module_slug = $_REQUEST['jitmModule'];
577
			Jetpack::log( 'activate', $module_slug );
578
			Jetpack::activate_module( $module_slug, false, false );
579
			Jetpack::state( 'message', 'no_message' );
580
581
			//A Jetpack module is being activated through a JITM, track it
582
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
583
			$this->do_stats( 'server_side' );
584
585
			wp_send_json_success();
586
		}
587
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
588
			// get the hide_jitm options array
589
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
590
			$module_slug = $_REQUEST['jitmModule'];
591
592
			if( ! $jetpack_hide_jitm ) {
593
				$jetpack_hide_jitm = array(
594
					$module_slug => 'hide'
595
				);
596
			} else {
597
				$jetpack_hide_jitm[$module_slug] = 'hide';
598
			}
599
600
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
601
602
			//jitm is being dismissed forever, track it
603
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
604
			$this->do_stats( 'server_side' );
605
606
			wp_send_json_success();
607
		}
608 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
609
			$module_slug = $_REQUEST['jitmModule'];
610
611
			// User went to WordPress.com, track this
612
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
613
			$this->do_stats( 'server_side' );
614
615
			wp_send_json_success();
616
		}
617 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
618
			$track = $_REQUEST['jitmModule'];
619
620
			// User is viewing JITM, track it.
621
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
622
			$this->do_stats( 'server_side' );
623
624
			wp_send_json_success();
625
		}
626
	}
627
628
	/**
629
	 * If there are any stats that need to be pushed, but haven't been, push them now.
630
	 */
631
	function __destruct() {
632
		if ( ! empty( $this->stats ) ) {
633
			$this->do_stats( 'server_side' );
634
		}
635
	}
636
637
	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...
638
		switch( $cap ) {
639
			case 'jetpack_connect' :
640
			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...
641
				if ( Jetpack::is_development_mode() ) {
642
					$caps = array( 'do_not_allow' );
643
					break;
644
				}
645
				/**
646
				 * Pass through. If it's not development mode, these should match disconnect.
647
				 * Let users disconnect if it's development mode, just in case things glitch.
648
				 */
649
			case 'jetpack_disconnect' :
650
				/**
651
				 * In multisite, can individual site admins manage their own connection?
652
				 *
653
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
654
				 */
655
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
656
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
657
						/**
658
						 * We need to update the option name -- it's terribly unclear which
659
						 * direction the override goes.
660
						 *
661
						 * @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...
662
						 */
663
						$caps = array( 'do_not_allow' );
664
						break;
665
					}
666
				}
667
668
				$caps = array( 'manage_options' );
669
				break;
670
			case 'jetpack_manage_modules' :
671
			case 'jetpack_activate_modules' :
672
			case 'jetpack_deactivate_modules' :
673
				$caps = array( 'manage_options' );
674
				break;
675
			case 'jetpack_configure_modules' :
676
				$caps = array( 'manage_options' );
677
				break;
678
			case 'jetpack_network_admin_page':
679
			case 'jetpack_network_settings_page':
680
				$caps = array( 'manage_network_plugins' );
681
				break;
682
			case 'jetpack_network_sites_page':
683
				$caps = array( 'manage_sites' );
684
				break;
685
			case 'jetpack_admin_page' :
686
				if ( Jetpack::is_development_mode() ) {
687
					$caps = array( 'manage_options' );
688
					break;
689
				} else {
690
					$caps = array( 'read' );
691
				}
692
				break;
693
			case 'jetpack_connect_user' :
694
				if ( Jetpack::is_development_mode() ) {
695
					$caps = array( 'do_not_allow' );
696
					break;
697
				}
698
				$caps = array( 'read' );
699
				break;
700
		}
701
		return $caps;
702
	}
703
704
	function require_jetpack_authentication() {
705
		// Don't let anyone authenticate
706
		$_COOKIE = array();
707
		remove_all_filters( 'authenticate' );
708
		remove_all_actions( 'wp_login_failed' );
709
710
		if ( Jetpack::is_active() ) {
711
			// Allow Jetpack authentication
712
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
713
		}
714
	}
715
716
	/**
717
	 * Load language files
718
	 * @action plugins_loaded
719
	 */
720
	public static function plugin_textdomain() {
721
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
722
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
723
	}
724
725
	/**
726
	 * Register assets for use in various modules and the Jetpack admin page.
727
	 *
728
	 * @uses wp_script_is, wp_register_script, plugins_url
729
	 * @action wp_loaded
730
	 * @return null
731
	 */
732
	public function register_assets() {
733 View Code Duplication
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
734
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
735
		}
736
737 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
738
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
739
		}
740
741 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
742
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
743
		}
744
745 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
746
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
747
		}
748
749
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
750
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
751
752
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
753
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
754
			if ( ! is_numeric( $fb_app_id ) ) {
755
				$fb_app_id = '';
756
			}
757
			wp_localize_script(
758
				'jetpack-facebook-embed',
759
				'jpfbembed',
760
				array(
761
					'appid' => $fb_app_id,
762
					'locale' => $this->get_locale(),
763
				)
764
			);
765
		}
766
767
		/**
768
		 * As jetpack_register_genericons is by default fired off a hook,
769
		 * the hook may have already fired by this point.
770
		 * So, let's just trigger it manually.
771
		 */
772
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
773
		jetpack_register_genericons();
774
775
		/**
776
		 * Register the social logos
777
		 */
778
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
779
		jetpack_register_social_logos();
780
781 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
782
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
783
	}
784
785
	/**
786
	 * Guess locale from language code.
787
	 *
788
	 * @param string $lang Language code.
789
	 * @return string|bool
790
	 */
791
	function guess_locale_from_lang( $lang ) {
792
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
793
			return 'en_US';
794
		}
795
796
		if ( ! class_exists( 'GP_Locales' ) ) {
797
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
798
				return false;
799
			}
800
801
			require JETPACK__GLOTPRESS_LOCALES_PATH;
802
		}
803
804
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
805
			// WP.com: get_locale() returns 'it'
806
			$locale = GP_Locales::by_slug( $lang );
807
		} else {
808
			// Jetpack: get_locale() returns 'it_IT';
809
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
810
		}
811
812
		if ( ! $locale ) {
813
			return false;
814
		}
815
816
		if ( empty( $locale->facebook_locale ) ) {
817
			if ( empty( $locale->wp_locale ) ) {
818
				return false;
819
			} else {
820
				// Facebook SDK is smart enough to fall back to en_US if a
821
				// locale isn't supported. Since supported Facebook locales
822
				// can fall out of sync, we'll attempt to use the known
823
				// wp_locale value and rely on said fallback.
824
				return $locale->wp_locale;
825
			}
826
		}
827
828
		return $locale->facebook_locale;
829
	}
830
831
	/**
832
	 * Get the locale.
833
	 *
834
	 * @return string|bool
835
	 */
836
	function get_locale() {
837
		$locale = $this->guess_locale_from_lang( get_locale() );
838
839
		if ( ! $locale ) {
840
			$locale = 'en_US';
841
		}
842
843
		return $locale;
844
	}
845
846
	/**
847
	 * Device Pixels support
848
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
849
	 */
850
	function devicepx() {
851
		if ( Jetpack::is_active() ) {
852
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
853
		}
854
	}
855
856
	/**
857
	 * Return the network_site_url so that .com knows what network this site is a part of.
858
	 * @param  bool $option
859
	 * @return string
860
	 */
861
	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...
862
		return network_site_url();
863
	}
864
	/**
865
	 * Network Name.
866
	 */
867
	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...
868
		global $current_site;
869
		return $current_site->site_name;
870
	}
871
	/**
872
	 * Does the network allow new user and site registrations.
873
	 * @return string
874
	 */
875
	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...
876
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
877
	}
878
	/**
879
	 * Does the network allow admins to add new users.
880
	 * @return boolian
881
	 */
882
	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...
883
		return (bool) get_site_option( 'add_new_users' );
884
	}
885
	/**
886
	 * File upload psace left per site in MB.
887
	 *  -1 means NO LIMIT.
888
	 * @return number
889
	 */
890
	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...
891
		// value in MB
892
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
893
	}
894
895
	/**
896
	 * Network allowed file types.
897
	 * @return string
898
	 */
899
	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...
900
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
901
	}
902
903
	/**
904
	 * Maximum file upload size set by the network.
905
	 * @return number
906
	 */
907
	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...
908
		// value in KB
909
		return get_site_option( 'fileupload_maxk', 300 );
910
	}
911
912
	/**
913
	 * Lets us know if a site allows admins to manage the network.
914
	 * @return array
915
	 */
916
	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...
917
		return get_site_option( 'menu_items' );
918
	}
919
920
	/**
921
	 * If a user has been promoted to or demoted from admin, we need to clear the
922
	 * jetpack_other_linked_admins transient.
923
	 *
924
	 * @param $user_id
925
	 * @param $role
926
	 * @param $old_roles
927
	 */
928
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles ) {
929
		if ( 'administrator' == $role || ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
930
		) {
931
			delete_transient( 'jetpack_other_linked_admins' );
932
		}
933
	}
934
935
	/**
936
	 * Checks to see if there are any other users available to become primary
937
	 * Users must both:
938
	 * - Be linked to wpcom
939
	 * - Be an admin
940
	 *
941
	 * @return mixed False if no other users are linked, Int if there are.
942
	 */
943
	static function get_other_linked_admins() {
944
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
945
946
		if ( false === $other_linked_users ) {
947
			$admins = get_users( array( 'role' => 'administrator' ) );
948
			if ( count( $admins ) > 1 ) {
949
				$available = array();
950
				foreach ( $admins as $admin ) {
951
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
952
						$available[] = $admin->ID;
953
					}
954
				}
955
956
				$count_connected_admins = count( $available );
957
				if ( count( $available ) > 1 ) {
958
					$other_linked_users = $count_connected_admins;
959
				} else {
960
					$other_linked_users = 0;
961
				}
962
			} else {
963
				$other_linked_users = 0;
964
			}
965
966
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
967
		}
968
969
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
970
	}
971
972
	/**
973
	 * Return whether we are dealing with a multi network setup or not.
974
	 * The reason we are type casting this is because we want to avoid the situation where
975
	 * the result is false since when is_main_network_option return false it cases
976
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
977
	 * database which could be set to anything as opposed to what this function returns.
978
	 * @param  bool  $option
979
	 *
980
	 * @return boolean
981
	 */
982
	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...
983
		// return '1' or ''
984
		return (string) (bool) Jetpack::is_multi_network();
985
	}
986
987
	/**
988
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
989
	 *
990
	 * @param  string  $option
991
	 * @return boolean
992
	 */
993
	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...
994
		return (string) (bool) is_multisite();
995
	}
996
997
	/**
998
	 * Implemented since there is no core is multi network function
999
	 * Right now there is no way to tell if we which network is the dominant network on the system
1000
	 *
1001
	 * @since  3.3
1002
	 * @return boolean
1003
	 */
1004
	public static function is_multi_network() {
1005
		global  $wpdb;
1006
1007
		// if we don't have a multi site setup no need to do any more
1008
		if ( ! is_multisite() ) {
1009
			return false;
1010
		}
1011
1012
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1013
		if ( $num_sites > 1 ) {
1014
			return true;
1015
		} else {
1016
			return false;
1017
		}
1018
	}
1019
1020
	/**
1021
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1022
	 * @return null
1023
	 */
1024
	function update_jetpack_main_network_site_option() {
1025
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1026
	}
1027
	/**
1028
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1029
	 *
1030
	 */
1031
	function update_jetpack_network_settings() {
1032
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1033
		// Only sync this info for the main network site.
1034
	}
1035
1036
	/**
1037
	 * Get back if the current site is single user site.
1038
	 *
1039
	 * @return bool
1040
	 */
1041
	public static function is_single_user_site() {
1042
		global $wpdb;
1043
		$some_users = $wpdb->get_var( "select count(*) from (select user_id from $wpdb->usermeta where meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) as someusers" );
1044
		return 1 === (int) $some_users;
1045
	}
1046
1047
	/**
1048
	 * Returns true if the site has file write access false otherwise.
1049
	 * @return string ( '1' | '0' )
1050
	 **/
1051
	public static function file_system_write_access() {
1052
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1053
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1054
		}
1055
1056
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1057
1058
		$filesystem_method = get_filesystem_method();
1059
		if ( $filesystem_method === 'direct' ) {
1060
			return 1;
1061
		}
1062
1063
		ob_start();
1064
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1065
		ob_end_clean();
1066
		if ( $filesystem_credentials_are_stored ) {
1067
			return 1;
1068
		}
1069
		return 0;
1070
	}
1071
1072
	/**
1073
	 * Finds out if a site is using a version control system.
1074
	 * @return string ( '1' | '0' )
1075
	 **/
1076
	public static function is_version_controlled() {
1077
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1078
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1079
	}
1080
1081
	/**
1082
	 * Determines whether the current theme supports featured images or not.
1083
	 * @return string ( '1' | '0' )
1084
	 */
1085
	public static function featured_images_enabled() {
1086
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1087
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1088
	}
1089
1090
	/**
1091
	 * jetpack_updates is saved in the following schema:
1092
	 *
1093
	 * array (
1094
	 *      'plugins'                       => (int) Number of plugin updates available.
1095
	 *      'themes'                        => (int) Number of theme updates available.
1096
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1097
	 *      'translations'                  => (int) Number of translation updates available.
1098
	 *      'total'                         => (int) Total of all available updates.
1099
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1100
	 * )
1101
	 * @return array
1102
	 */
1103
	public static function get_updates() {
1104
		$update_data = wp_get_update_data();
1105
1106
		// Stores the individual update counts as well as the total count.
1107
		if ( isset( $update_data['counts'] ) ) {
1108
			$updates = $update_data['counts'];
1109
		}
1110
1111
		// If we need to update WordPress core, let's find the latest version number.
1112 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1113
			$cur = get_preferred_from_update_core();
1114
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1115
				$updates['wp_update_version'] = $cur->current;
1116
			}
1117
		}
1118
		return isset( $updates ) ? $updates : array();
1119
	}
1120
1121
	public static function get_update_details() {
1122
		$update_details = array(
1123
			'update_core' => get_site_transient( 'update_core' ),
1124
			'update_plugins' => get_site_transient( 'update_plugins' ),
1125
			'update_themes' => get_site_transient( 'update_themes' ),
1126
		);
1127
		return $update_details;
1128
	}
1129
1130
	public static function refresh_update_data() {
1131
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1132
1133
	}
1134
1135
	public static function refresh_theme_data() {
1136
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1137
	}
1138
1139
	/**
1140
	 * Is Jetpack active?
1141
	 */
1142
	public static function is_active() {
1143
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1144
	}
1145
1146
	/**
1147
	 * Is Jetpack in development (offline) mode?
1148
	 */
1149
	public static function is_development_mode() {
1150
		$development_mode = false;
1151
1152
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1153
			$development_mode = JETPACK_DEV_DEBUG;
1154
		}
1155
1156
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1157
			$development_mode = true;
1158
		}
1159
		/**
1160
		 * Filters Jetpack's development mode.
1161
		 *
1162
		 * @see https://jetpack.com/support/development-mode/
1163
		 *
1164
		 * @since 2.2.1
1165
		 *
1166
		 * @param bool $development_mode Is Jetpack's development mode active.
1167
		 */
1168
		return apply_filters( 'jetpack_development_mode', $development_mode );
1169
	}
1170
1171
	/**
1172
	* Get Jetpack development mode notice text and notice class.
1173
	*
1174
	* Mirrors the checks made in Jetpack::is_development_mode
1175
	*
1176
	*/
1177
	public static function show_development_mode_notice() {
1178
		if ( Jetpack::is_development_mode() ) {
1179
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1180
				$notice = sprintf(
1181
					/* translators: %s is a URL */
1182
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1183
					'https://jetpack.com/support/development-mode/'
1184
				);
1185
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1186
				$notice = sprintf(
1187
					/* translators: %s is a URL */
1188
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1189
					'https://jetpack.com/support/development-mode/'
1190
				);
1191
			} else {
1192
				$notice = sprintf(
1193
					/* translators: %s is a URL */
1194
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1195
					'https://jetpack.com/support/development-mode/'
1196
				);
1197
			}
1198
1199
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1200
		}
1201
1202
		// Throw up a notice if using a development version and as for feedback.
1203
		if ( Jetpack::is_development_version() ) {
1204
			/* translators: %s is a URL */
1205
			$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/' );
1206
1207
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1208
		}
1209
		// Throw up a notice if using staging mode
1210
		if ( Jetpack::is_staging_site() ) {
1211
			/* translators: %s is a URL */
1212
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1213
1214
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1215
		}
1216
	}
1217
1218
	/**
1219
	 * Whether Jetpack's version maps to a public release, or a development version.
1220
	 */
1221
	public static function is_development_version() {
1222
		/**
1223
		 * Allows filtering whether this is a development version of Jetpack.
1224
		 *
1225
		 * This filter is especially useful for tests.
1226
		 *
1227
		 * @since 4.3.0
1228
		 *
1229
		 * @param bool $development_version Is this a develoment version of Jetpack?
1230
		 */
1231
		return (bool) apply_filters(
1232
			'jetpack_development_version',
1233
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1234
		);
1235
	}
1236
1237
	/**
1238
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1239
	 */
1240
	public static function is_user_connected( $user_id = false ) {
1241
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1242
		if ( ! $user_id ) {
1243
			return false;
1244
		}
1245
1246
		return (bool) Jetpack_Data::get_access_token( $user_id );
1247
	}
1248
1249
	/**
1250
	 * Get the wpcom user data of the current|specified connected user.
1251
	 */
1252
	public static function get_connected_user_data( $user_id = null ) {
1253
		if ( ! $user_id ) {
1254
			$user_id = get_current_user_id();
1255
		}
1256
1257
		$transient_key = "jetpack_connected_user_data_$user_id";
1258
1259
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1260
			return $cached_user_data;
1261
		}
1262
1263
		Jetpack::load_xml_rpc_client();
1264
		$xml = new Jetpack_IXR_Client( array(
1265
			'user_id' => $user_id,
1266
		) );
1267
		$xml->query( 'wpcom.getUser' );
1268
		if ( ! $xml->isError() ) {
1269
			$user_data = $xml->getResponse();
1270
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1271
			return $user_data;
1272
		}
1273
1274
		return false;
1275
	}
1276
1277
	/**
1278
	 * Get the wpcom email of the current|specified connected user.
1279
	 */
1280 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1281
		if ( ! $user_id ) {
1282
			$user_id = get_current_user_id();
1283
		}
1284
		Jetpack::load_xml_rpc_client();
1285
		$xml = new Jetpack_IXR_Client( array(
1286
			'user_id' => $user_id,
1287
		) );
1288
		$xml->query( 'wpcom.getUserEmail' );
1289
		if ( ! $xml->isError() ) {
1290
			return $xml->getResponse();
1291
		}
1292
		return false;
1293
	}
1294
1295
	/**
1296
	 * Get the wpcom email of the master user.
1297
	 */
1298
	public static function get_master_user_email() {
1299
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1300
		if ( $master_user_id ) {
1301
			return self::get_connected_user_email( $master_user_id );
1302
		}
1303
		return '';
1304
	}
1305
1306
	function current_user_is_connection_owner() {
1307
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1308
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1309
	}
1310
1311
	/**
1312
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1313
	 */
1314
	function extra_oembed_providers() {
1315
		// Cloudup: https://dev.cloudup.com/#oembed
1316
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1317
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1318
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1319
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1320
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1321
	}
1322
1323
	/**
1324
	 * Synchronize connected user role changes
1325
	 */
1326
	function user_role_change( $user_id ) {
1327
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1328
		Jetpack_Sync_Users::user_role_change( $user_id );
1329
	}
1330
1331
	/**
1332
	 * Loads the currently active modules.
1333
	 */
1334
	public static function load_modules() {
1335
		if ( ! self::is_active() && !self::is_development_mode() ) {
1336
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1337
				return;
1338
			}
1339
		}
1340
1341
		$version = Jetpack_Options::get_option( 'version' );
1342 View Code Duplication
		if ( ! $version ) {
1343
			$version = $old_version = JETPACK__VERSION . ':' . time();
1344
			/** This action is documented in class.jetpack.php */
1345
			do_action( 'updating_jetpack_version', $version, false );
1346
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1347
		}
1348
		list( $version ) = explode( ':', $version );
1349
1350
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1351
1352
		$modules_data = array();
1353
1354
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1355
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1356
			$updated_modules = array();
1357
			foreach ( $modules as $module ) {
1358
				$modules_data[ $module ] = Jetpack::get_module( $module );
1359
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1360
					continue;
1361
				}
1362
1363
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1364
					continue;
1365
				}
1366
1367
				$updated_modules[] = $module;
1368
			}
1369
1370
			$modules = array_diff( $modules, $updated_modules );
1371
		}
1372
1373
		$is_development_mode = Jetpack::is_development_mode();
1374
1375
		foreach ( $modules as $index => $module ) {
1376
			// If we're in dev mode, disable modules requiring a connection
1377
			if ( $is_development_mode ) {
1378
				// Prime the pump if we need to
1379
				if ( empty( $modules_data[ $module ] ) ) {
1380
					$modules_data[ $module ] = Jetpack::get_module( $module );
1381
				}
1382
				// If the module requires a connection, but we're in local mode, don't include it.
1383
				if ( $modules_data[ $module ]['requires_connection'] ) {
1384
					continue;
1385
				}
1386
			}
1387
1388
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1389
				continue;
1390
			}
1391
1392
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1393
				unset( $modules[ $index ] );
1394
				self::update_active_modules( array_values( $modules ) );
1395
				continue;
1396
			}
1397
1398
			/**
1399
			 * Fires when a specific module is loaded.
1400
			 * The dynamic part of the hook, $module, is the module slug.
1401
			 *
1402
			 * @since 1.1.0
1403
			 */
1404
			do_action( 'jetpack_module_loaded_' . $module );
1405
		}
1406
1407
		/**
1408
		 * Fires when all the modules are loaded.
1409
		 *
1410
		 * @since 1.1.0
1411
		 */
1412
		do_action( 'jetpack_modules_loaded' );
1413
1414
		// 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.
1415
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1416
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1417
	}
1418
1419
	/**
1420
	 * Check if Jetpack's REST API compat file should be included
1421
	 * @action plugins_loaded
1422
	 * @return null
1423
	 */
1424
	public function check_rest_api_compat() {
1425
		/**
1426
		 * Filters the list of REST API compat files to be included.
1427
		 *
1428
		 * @since 2.2.5
1429
		 *
1430
		 * @param array $args Array of REST API compat files to include.
1431
		 */
1432
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1433
1434
		if ( function_exists( 'bbpress' ) )
1435
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1436
1437
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1438
			require_once $_jetpack_rest_api_compat_include;
1439
	}
1440
1441
	/**
1442
	 * Gets all plugins currently active in values, regardless of whether they're
1443
	 * traditionally activated or network activated.
1444
	 *
1445
	 * @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...
1446
	 */
1447
	public static function get_active_plugins() {
1448
		$active_plugins = (array) get_option( 'active_plugins', array() );
1449
1450
		if ( is_multisite() ) {
1451
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1452
			// whereas active_plugins stores them in the values.
1453
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1454
			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...
1455
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1456
			}
1457
		}
1458
1459
		sort( $active_plugins );
1460
1461
		return array_unique( $active_plugins );
1462
	}
1463
1464
	/**
1465
	 * Gets and parses additional plugin data to send with the heartbeat data
1466
	 *
1467
	 * @since 3.8.1
1468
	 *
1469
	 * @return array Array of plugin data
1470
	 */
1471
	public static function get_parsed_plugin_data() {
1472
		if ( ! function_exists( 'get_plugins' ) ) {
1473
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1474
		}
1475
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1476
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1477
		$active_plugins = Jetpack::get_active_plugins();
1478
1479
		$plugins = array();
1480
		foreach ( $all_plugins as $path => $plugin_data ) {
1481
			$plugins[ $path ] = array(
1482
					'is_active' => in_array( $path, $active_plugins ),
1483
					'file'      => $path,
1484
					'name'      => $plugin_data['Name'],
1485
					'version'   => $plugin_data['Version'],
1486
					'author'    => $plugin_data['Author'],
1487
			);
1488
		}
1489
1490
		return $plugins;
1491
	}
1492
1493
	/**
1494
	 * Gets and parses theme data to send with the heartbeat data
1495
	 *
1496
	 * @since 3.8.1
1497
	 *
1498
	 * @return array Array of theme data
1499
	 */
1500
	public static function get_parsed_theme_data() {
1501
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1502
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1503
1504
		$themes = array();
1505
		foreach ( $all_themes as $slug => $theme_data ) {
1506
			$theme_headers = array();
1507
			foreach ( $header_keys as $header_key ) {
1508
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1509
			}
1510
1511
			$themes[ $slug ] = array(
1512
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1513
					'slug' => $slug,
1514
					'theme_root' => $theme_data->get_theme_root_uri(),
1515
					'parent' => $theme_data->parent(),
1516
					'headers' => $theme_headers
1517
			);
1518
		}
1519
1520
		return $themes;
1521
	}
1522
1523
	/**
1524
	 * Checks whether a specific plugin is active.
1525
	 *
1526
	 * We don't want to store these in a static variable, in case
1527
	 * there are switch_to_blog() calls involved.
1528
	 */
1529
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1530
		return in_array( $plugin, self::get_active_plugins() );
1531
	}
1532
1533
	/**
1534
	 * Check if Jetpack's Open Graph tags should be used.
1535
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1536
	 *
1537
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1538
	 * @action plugins_loaded
1539
	 * @return null
1540
	 */
1541
	public function check_open_graph() {
1542
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1543
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1544
		}
1545
1546
		$active_plugins = self::get_active_plugins();
1547
1548
		if ( ! empty( $active_plugins ) ) {
1549
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1550
				if ( in_array( $plugin, $active_plugins ) ) {
1551
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1552
					break;
1553
				}
1554
			}
1555
		}
1556
1557
		/**
1558
		 * Allow the addition of Open Graph Meta Tags to all pages.
1559
		 *
1560
		 * @since 2.0.3
1561
		 *
1562
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1563
		 */
1564
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1565
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1566
		}
1567
	}
1568
1569
	/**
1570
	 * Check if Jetpack's Twitter tags should be used.
1571
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1572
	 *
1573
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1574
	 * @action plugins_loaded
1575
	 * @return null
1576
	 */
1577
	public function check_twitter_tags() {
1578
1579
		$active_plugins = self::get_active_plugins();
1580
1581
		if ( ! empty( $active_plugins ) ) {
1582
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1583
				if ( in_array( $plugin, $active_plugins ) ) {
1584
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1585
					break;
1586
				}
1587
			}
1588
		}
1589
1590
		/**
1591
		 * Allow Twitter Card Meta tags to be disabled.
1592
		 *
1593
		 * @since 2.6.0
1594
		 *
1595
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1596
		 */
1597
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1598
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1599
		}
1600
	}
1601
1602
	/**
1603
	 * Allows plugins to submit security reports.
1604
 	 *
1605
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1606
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1607
	 * @param array   $args         See definitions above
1608
	 */
1609
	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...
1610
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1611
	}
1612
1613
/* Jetpack Options API */
1614
1615
	public static function get_option_names( $type = 'compact' ) {
1616
		return Jetpack_Options::get_option_names( $type );
1617
	}
1618
1619
	/**
1620
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1621
 	 *
1622
	 * @param string $name    Option name
1623
	 * @param mixed  $default (optional)
1624
	 */
1625
	public static function get_option( $name, $default = false ) {
1626
		return Jetpack_Options::get_option( $name, $default );
1627
	}
1628
1629
	/**
1630
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1631
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1632
	* $name must be a registered option name.
1633
	*/
1634
	public static function create_nonce( $name ) {
1635
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1636
1637
		Jetpack_Options::update_option( $name, $secret );
1638
		@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...
1639
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1640
			return new Jetpack_Error( 'missing_secrets' );
1641
1642
		return array(
1643
			'secret_1' => $secret_1,
1644
			'secret_2' => $secret_2,
1645
			'eol'      => $eol,
1646
		);
1647
	}
1648
1649
	/**
1650
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1651
 	 *
1652
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1653
	 * @param string $name  Option name
1654
	 * @param mixed  $value Option value
1655
	 */
1656
	public static function update_option( $name, $value ) {
1657
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1658
		return Jetpack_Options::update_option( $name, $value );
1659
	}
1660
1661
	/**
1662
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1663
 	 *
1664
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1665
	 * @param array $array array( option name => option value, ... )
1666
	 */
1667
	public static function update_options( $array ) {
1668
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1669
		return Jetpack_Options::update_options( $array );
1670
	}
1671
1672
	/**
1673
	 * Deletes the given option.  May be passed multiple option names as an array.
1674
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1675
	 *
1676
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1677
	 * @param string|array $names
1678
	 */
1679
	public static function delete_option( $names ) {
1680
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1681
		return Jetpack_Options::delete_option( $names );
1682
	}
1683
1684
	/**
1685
	 * Enters a user token into the user_tokens option
1686
	 *
1687
	 * @param int $user_id
1688
	 * @param string $token
1689
	 * return bool
1690
	 */
1691
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1692
		// not designed for concurrent updates
1693
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1694
		if ( ! is_array( $user_tokens ) )
1695
			$user_tokens = array();
1696
		$user_tokens[$user_id] = $token;
1697
		if ( $is_master_user ) {
1698
			$master_user = $user_id;
1699
			$options     = compact( 'user_tokens', 'master_user' );
1700
		} else {
1701
			$options = compact( 'user_tokens' );
1702
		}
1703
		return Jetpack_Options::update_options( $options );
1704
	}
1705
1706
	/**
1707
	 * Returns an array of all PHP files in the specified absolute path.
1708
	 * Equivalent to glob( "$absolute_path/*.php" ).
1709
	 *
1710
	 * @param string $absolute_path The absolute path of the directory to search.
1711
	 * @return array Array of absolute paths to the PHP files.
1712
	 */
1713
	public static function glob_php( $absolute_path ) {
1714
		if ( function_exists( 'glob' ) ) {
1715
			return glob( "$absolute_path/*.php" );
1716
		}
1717
1718
		$absolute_path = untrailingslashit( $absolute_path );
1719
		$files = array();
1720
		if ( ! $dir = @opendir( $absolute_path ) ) {
1721
			return $files;
1722
		}
1723
1724
		while ( false !== $file = readdir( $dir ) ) {
1725
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1726
				continue;
1727
			}
1728
1729
			$file = "$absolute_path/$file";
1730
1731
			if ( ! is_file( $file ) ) {
1732
				continue;
1733
			}
1734
1735
			$files[] = $file;
1736
		}
1737
1738
		closedir( $dir );
1739
1740
		return $files;
1741
	}
1742
1743
	public static function activate_new_modules( $redirect = false ) {
1744
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1745
			return;
1746
		}
1747
1748
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1749 View Code Duplication
		if ( ! $jetpack_old_version ) {
1750
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1751
			/** This action is documented in class.jetpack.php */
1752
			do_action( 'updating_jetpack_version', $version, false );
1753
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1754
		}
1755
1756
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1757
1758
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1759
			return;
1760
		}
1761
1762
		$active_modules     = Jetpack::get_active_modules();
1763
		$reactivate_modules = array();
1764
		foreach ( $active_modules as $active_module ) {
1765
			$module = Jetpack::get_module( $active_module );
1766
			if ( ! isset( $module['changed'] ) ) {
1767
				continue;
1768
			}
1769
1770
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1771
				continue;
1772
			}
1773
1774
			$reactivate_modules[] = $active_module;
1775
			Jetpack::deactivate_module( $active_module );
1776
		}
1777
1778
		$new_version = JETPACK__VERSION . ':' . time();
1779
		/** This action is documented in class.jetpack.php */
1780
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1781
		Jetpack_Options::update_options(
1782
			array(
1783
				'version'     => $new_version,
1784
				'old_version' => $jetpack_old_version,
1785
			)
1786
		);
1787
1788
		Jetpack::state( 'message', 'modules_activated' );
1789
		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...
1790
1791
		if ( $redirect ) {
1792
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1793
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1794
				$page = $_GET['page'];
1795
			}
1796
1797
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1798
			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...
1799
		}
1800
	}
1801
1802
	/**
1803
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1804
	 * Make sure to tuck away module "library" files in a sub-directory.
1805
	 */
1806
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1807
		static $modules = null;
1808
1809
		if ( ! isset( $modules ) ) {
1810
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1811
			// Use the cache if we're on the front-end and it's available...
1812
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1813
				$modules = $available_modules_option[ JETPACK__VERSION ];
1814
			} else {
1815
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1816
1817
				$modules = array();
1818
1819
				foreach ( $files as $file ) {
1820
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1821
						continue;
1822
					}
1823
1824
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1825
				}
1826
1827
				Jetpack_Options::update_option( 'available_modules', array(
1828
					JETPACK__VERSION => $modules,
1829
				) );
1830
			}
1831
		}
1832
1833
		/**
1834
		 * Filters the array of modules available to be activated.
1835
		 *
1836
		 * @since 2.4.0
1837
		 *
1838
		 * @param array $modules Array of available modules.
1839
		 * @param string $min_version Minimum version number required to use modules.
1840
		 * @param string $max_version Maximum version number required to use modules.
1841
		 */
1842
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1843
1844
		if ( ! $min_version && ! $max_version ) {
1845
			return array_keys( $mods );
1846
		}
1847
1848
		$r = array();
1849
		foreach ( $mods as $slug => $introduced ) {
1850
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1851
				continue;
1852
			}
1853
1854
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1855
				continue;
1856
			}
1857
1858
			$r[] = $slug;
1859
		}
1860
1861
		return $r;
1862
	}
1863
1864
	/**
1865
	 * Default modules loaded on activation.
1866
	 */
1867
	public static function get_default_modules( $min_version = false, $max_version = false ) {
1868
		$return = array();
1869
1870
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1871
			$module_data = Jetpack::get_module( $module );
1872
1873
			switch ( strtolower( $module_data['auto_activate'] ) ) {
1874
				case 'yes' :
1875
					$return[] = $module;
1876
					break;
1877
				case 'public' :
1878
					if ( Jetpack_Options::get_option( 'public' ) ) {
1879
						$return[] = $module;
1880
					}
1881
					break;
1882
				case 'no' :
1883
				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...
1884
					break;
1885
			}
1886
		}
1887
		/**
1888
		 * Filters the array of default modules.
1889
		 *
1890
		 * @since 2.5.0
1891
		 *
1892
		 * @param array $return Array of default modules.
1893
		 * @param string $min_version Minimum version number required to use modules.
1894
		 * @param string $max_version Maximum version number required to use modules.
1895
		 */
1896
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1897
	}
1898
1899
	/**
1900
	 * Checks activated modules during auto-activation to determine
1901
	 * if any of those modules are being deprecated.  If so, close
1902
	 * them out, and add any replacement modules.
1903
	 *
1904
	 * Runs at priority 99 by default.
1905
	 *
1906
	 * This is run late, so that it can still activate a module if
1907
	 * the new module is a replacement for another that the user
1908
	 * currently has active, even if something at the normal priority
1909
	 * would kibosh everything.
1910
	 *
1911
	 * @since 2.6
1912
	 * @uses jetpack_get_default_modules filter
1913
	 * @param array $modules
1914
	 * @return array
1915
	 */
1916
	function handle_deprecated_modules( $modules ) {
1917
		$deprecated_modules = array(
1918
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
1919
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1920
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
1921
		);
1922
1923
		// Don't activate SSO if they never completed activating WPCC.
1924
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
1925
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1926
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1927
				$deprecated_modules['wpcc'] = null;
1928
			}
1929
		}
1930
1931
		foreach ( $deprecated_modules as $module => $replacement ) {
1932
			if ( Jetpack::is_module_active( $module ) ) {
1933
				self::deactivate_module( $module );
1934
				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...
1935
					$modules[] = $replacement;
1936
				}
1937
			}
1938
		}
1939
1940
		return array_unique( $modules );
1941
	}
1942
1943
	/**
1944
	 * Checks activated plugins during auto-activation to determine
1945
	 * if any of those plugins are in the list with a corresponding module
1946
	 * that is not compatible with the plugin. The module will not be allowed
1947
	 * to auto-activate.
1948
	 *
1949
	 * @since 2.6
1950
	 * @uses jetpack_get_default_modules filter
1951
	 * @param array $modules
1952
	 * @return array
1953
	 */
1954
	function filter_default_modules( $modules ) {
1955
1956
		$active_plugins = self::get_active_plugins();
1957
1958
		if ( ! empty( $active_plugins ) ) {
1959
1960
			// For each module we'd like to auto-activate...
1961
			foreach ( $modules as $key => $module ) {
1962
				// If there are potential conflicts for it...
1963
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1964
					// For each potential conflict...
1965
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1966
						// If that conflicting plugin is active...
1967
						if ( in_array( $plugin, $active_plugins ) ) {
1968
							// Remove that item from being auto-activated.
1969
							unset( $modules[ $key ] );
1970
						}
1971
					}
1972
				}
1973
			}
1974
		}
1975
1976
		return $modules;
1977
	}
1978
1979
	/**
1980
	 * Extract a module's slug from its full path.
1981
	 */
1982
	public static function get_module_slug( $file ) {
1983
		return str_replace( '.php', '', basename( $file ) );
1984
	}
1985
1986
	/**
1987
	 * Generate a module's path from its slug.
1988
	 */
1989
	public static function get_module_path( $slug ) {
1990
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
1991
	}
1992
1993
	/**
1994
	 * Load module data from module file. Headers differ from WordPress
1995
	 * plugin headers to avoid them being identified as standalone
1996
	 * plugins on the WordPress plugins page.
1997
	 */
1998
	public static function get_module( $module ) {
1999
		$headers = array(
2000
			'name'                      => 'Module Name',
2001
			'description'               => 'Module Description',
2002
			'jumpstart_desc'            => 'Jumpstart Description',
2003
			'sort'                      => 'Sort Order',
2004
			'recommendation_order'      => 'Recommendation Order',
2005
			'introduced'                => 'First Introduced',
2006
			'changed'                   => 'Major Changes In',
2007
			'deactivate'                => 'Deactivate',
2008
			'free'                      => 'Free',
2009
			'requires_connection'       => 'Requires Connection',
2010
			'auto_activate'             => 'Auto Activate',
2011
			'module_tags'               => 'Module Tags',
2012
			'feature'                   => 'Feature',
2013
			'additional_search_queries' => 'Additional Search Queries',
2014
		);
2015
2016
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2017
2018
		$mod = Jetpack::get_file_data( $file, $headers );
2019
		if ( empty( $mod['name'] ) ) {
2020
			return false;
2021
		}
2022
2023
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2024
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2025
		$mod['deactivate']              = empty( $mod['deactivate'] );
2026
		$mod['free']                    = empty( $mod['free'] );
2027
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2028
2029
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2030
			$mod['auto_activate'] = 'No';
2031
		} else {
2032
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2033
		}
2034
2035
		if ( $mod['module_tags'] ) {
2036
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2037
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2038
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2039
		} else {
2040
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2041
		}
2042
2043
		if ( $mod['feature'] ) {
2044
			$mod['feature'] = explode( ',', $mod['feature'] );
2045
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2046
		} else {
2047
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2048
		}
2049
2050
		/**
2051
		 * Filters the feature array on a module.
2052
		 *
2053
		 * This filter allows you to control where each module is filtered: Recommended,
2054
		 * Jumpstart, and the default "Other" listing.
2055
		 *
2056
		 * @since 3.5.0
2057
		 *
2058
		 * @param array   $mod['feature'] The areas to feature this module:
2059
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2060
		 *     'Recommended' shows on the main Jetpack admin screen.
2061
		 *     'Other' should be the default if no other value is in the array.
2062
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2063
		 * @param array   $mod All the currently assembled module data.
2064
		 */
2065
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2066
2067
		/**
2068
		 * Filter the returned data about a module.
2069
		 *
2070
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2071
		 * so please be careful.
2072
		 *
2073
		 * @since 3.6.0
2074
		 *
2075
		 * @param array   $mod    The details of the requested module.
2076
		 * @param string  $module The slug of the module, e.g. sharedaddy
2077
		 * @param string  $file   The path to the module source file.
2078
		 */
2079
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2080
	}
2081
2082
	/**
2083
	 * Like core's get_file_data implementation, but caches the result.
2084
	 */
2085
	public static function get_file_data( $file, $headers ) {
2086
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2087
		$file_name = basename( $file );
2088
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2089
		$key              = md5( $file_name . serialize( $headers ) );
2090
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2091
2092
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2093
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2094
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2095
		}
2096
2097
		$data = get_file_data( $file, $headers );
2098
2099
		// Strip out any old Jetpack versions that are cluttering the option.
2100
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2101
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2102
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2103
2104
		return $data;
2105
	}
2106
2107
	/**
2108
	 * Return translated module tag.
2109
	 *
2110
	 * @param string $tag Tag as it appears in each module heading.
2111
	 *
2112
	 * @return mixed
2113
	 */
2114
	public static function translate_module_tag( $tag ) {
2115
		return jetpack_get_module_i18n_tag( $tag );
2116
	}
2117
2118
	/**
2119
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2120
	 *
2121
	 * @since 3.9.2
2122
	 *
2123
	 * @param array $modules
2124
	 *
2125
	 * @return string|void
2126
	 */
2127
	public static function get_translated_modules( $modules ) {
2128
		foreach ( $modules as $index => $module ) {
2129
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2130
			if ( isset( $module['name'] ) ) {
2131
				$modules[ $index ]['name'] = $i18n_module['name'];
2132
			}
2133
			if ( isset( $module['description'] ) ) {
2134
				$modules[ $index ]['description'] = $i18n_module['description'];
2135
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2136
			}
2137
		}
2138
		return $modules;
2139
	}
2140
2141
	/**
2142
	 * Get a list of activated modules as an array of module slugs.
2143
	 */
2144
	public static function get_active_modules() {
2145
		$active = Jetpack_Options::get_option( 'active_modules' );
2146
		if ( ! is_array( $active ) )
2147
			$active = array();
2148
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2149
			$active[] = 'vaultpress';
2150
		} else {
2151
			$active = array_diff( $active, array( 'vaultpress' ) );
2152
		}
2153
2154
		//If protect is active on the main site of a multisite, it should be active on all sites.
2155
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2156
			$active[] = 'protect';
2157
		}
2158
2159
		return array_unique( $active );
2160
	}
2161
2162
	/**
2163
	 * Check whether or not a Jetpack module is active.
2164
	 *
2165
	 * @param string $module The slug of a Jetpack module.
2166
	 * @return bool
2167
	 *
2168
	 * @static
2169
	 */
2170
	public static function is_module_active( $module ) {
2171
		return in_array( $module, self::get_active_modules() );
2172
	}
2173
2174
	public static function is_module( $module ) {
2175
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2176
	}
2177
2178
	/**
2179
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2180
	 *
2181
	 * @param bool $catch True to start catching, False to stop.
2182
	 *
2183
	 * @static
2184
	 */
2185
	public static function catch_errors( $catch ) {
2186
		static $display_errors, $error_reporting;
2187
2188
		if ( $catch ) {
2189
			$display_errors  = @ini_set( 'display_errors', 1 );
2190
			$error_reporting = @error_reporting( E_ALL );
2191
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2192
		} else {
2193
			@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...
2194
			@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...
2195
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2196
		}
2197
	}
2198
2199
	/**
2200
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2201
	 */
2202
	public static function catch_errors_on_shutdown() {
2203
		Jetpack::state( 'php_errors', ob_get_clean() );
2204
	}
2205
2206
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2207
		$jetpack = Jetpack::init();
2208
2209
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2210
		$modules = array_merge( $other_modules, $modules );
2211
2212
		// Look for standalone plugins and disable if active.
2213
2214
		$to_deactivate = array();
2215
		foreach ( $modules as $module ) {
2216
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2217
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2218
			}
2219
		}
2220
2221
		$deactivated = array();
2222
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2223
			list( $probable_file, $probable_title ) = $deactivate_me;
2224
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2225
				$deactivated[] = $module;
2226
			}
2227
		}
2228
2229
		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...
2230
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2231
2232
			$url = add_query_arg(
2233
				array(
2234
					'action'   => 'activate_default_modules',
2235
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2236
				),
2237
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2238
			);
2239
			wp_safe_redirect( $url );
2240
			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...
2241
		}
2242
2243
		/**
2244
		 * Fires before default modules are activated.
2245
		 *
2246
		 * @since 1.9.0
2247
		 *
2248
		 * @param string $min_version Minimum version number required to use modules.
2249
		 * @param string $max_version Maximum version number required to use modules.
2250
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2251
		 */
2252
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2253
2254
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2255
		Jetpack::restate();
2256
		Jetpack::catch_errors( true );
2257
2258
		$active = Jetpack::get_active_modules();
2259
2260
		foreach ( $modules as $module ) {
2261
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2262
				$active[] = $module;
2263
				self::update_active_modules( $active );
2264
				continue;
2265
			}
2266
2267
			if ( in_array( $module, $active ) ) {
2268
				$module_info = Jetpack::get_module( $module );
2269
				if ( ! $module_info['deactivate'] ) {
2270
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2271 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2272
						$active_state = explode( ',', $active_state );
2273
					} else {
2274
						$active_state = array();
2275
					}
2276
					$active_state[] = $module;
2277
					Jetpack::state( $state, implode( ',', $active_state ) );
2278
				}
2279
				continue;
2280
			}
2281
2282
			$file = Jetpack::get_module_path( $module );
2283
			if ( ! file_exists( $file ) ) {
2284
				continue;
2285
			}
2286
2287
			// we'll override this later if the plugin can be included without fatal error
2288
			if ( $redirect ) {
2289
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2290
			}
2291
			Jetpack::state( 'error', 'module_activation_failed' );
2292
			Jetpack::state( 'module', $module );
2293
			ob_start();
2294
			require $file;
2295
2296
			$active[] = $module;
2297
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2298 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2299
				$active_state = explode( ',', $active_state );
2300
			} else {
2301
				$active_state = array();
2302
			}
2303
			$active_state[] = $module;
2304
			Jetpack::state( $state, implode( ',', $active_state ) );
2305
			Jetpack::update_active_modules( $active );
2306
2307
			ob_end_clean();
2308
		}
2309
		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...
2310
		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...
2311
		Jetpack::catch_errors( false );
2312
		/**
2313
		 * Fires when default modules are activated.
2314
		 *
2315
		 * @since 1.9.0
2316
		 *
2317
		 * @param string $min_version Minimum version number required to use modules.
2318
		 * @param string $max_version Maximum version number required to use modules.
2319
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2320
		 */
2321
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2322
	}
2323
2324
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2325
		/**
2326
		 * Fires before a module is activated.
2327
		 *
2328
		 * @since 2.6.0
2329
		 *
2330
		 * @param string $module Module slug.
2331
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2332
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2333
		 */
2334
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2335
2336
		$jetpack = Jetpack::init();
2337
2338
		if ( ! strlen( $module ) )
2339
			return false;
2340
2341
		if ( ! Jetpack::is_module( $module ) )
2342
			return false;
2343
2344
		// If it's already active, then don't do it again
2345
		$active = Jetpack::get_active_modules();
2346
		foreach ( $active as $act ) {
2347
			if ( $act == $module )
2348
				return true;
2349
		}
2350
2351
		$module_data = Jetpack::get_module( $module );
2352
2353
		if ( ! Jetpack::is_active() ) {
2354
			if ( !Jetpack::is_development_mode() )
2355
				return false;
2356
2357
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2358
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2359
				return false;
2360
		}
2361
2362
		// Check and see if the old plugin is active
2363
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2364
			// Deactivate the old plugin
2365
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2366
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2367
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2368
				Jetpack::state( 'deactivated_plugins', $module );
2369
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2370
				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...
2371
			}
2372
		}
2373
2374
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2375
		Jetpack::state( 'module', $module );
2376
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2377
2378
		Jetpack::catch_errors( true );
2379
		ob_start();
2380
		require Jetpack::get_module_path( $module );
2381
		/** This action is documented in class.jetpack.php */
2382
		do_action( 'jetpack_activate_module', $module );
2383
		$active[] = $module;
2384
		Jetpack::update_active_modules( $active );
2385
2386
		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...
2387
		ob_end_clean();
2388
		Jetpack::catch_errors( false );
2389
2390
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2391 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2392
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2393
2394
			//Jump start is being dismissed send data to MC Stats
2395
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2396
2397
			$jetpack->do_stats( 'server_side' );
2398
		}
2399
2400
		if ( $redirect ) {
2401
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2402
		}
2403
		if ( $exit ) {
2404
			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...
2405
		}
2406
		return true;
2407
	}
2408
2409
	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...
2410
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2411
	}
2412
2413
	public static function deactivate_module( $module ) {
2414
		/**
2415
		 * Fires when a module is deactivated.
2416
		 *
2417
		 * @since 1.9.0
2418
		 *
2419
		 * @param string $module Module slug.
2420
		 */
2421
		do_action( 'jetpack_pre_deactivate_module', $module );
2422
2423
		$jetpack = Jetpack::init();
2424
2425
		$active = Jetpack::get_active_modules();
2426
		$new    = array_filter( array_diff( $active, (array) $module ) );
2427
2428
		// A flag for Jump Start so it's not shown again.
2429 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2430
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2431
2432
			//Jump start is being dismissed send data to MC Stats
2433
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2434
2435
			$jetpack->do_stats( 'server_side' );
2436
		}
2437
2438
		return self::update_active_modules( $new );
2439
	}
2440
2441
	public static function enable_module_configurable( $module ) {
2442
		$module = Jetpack::get_module_slug( $module );
2443
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2444
	}
2445
2446
	public static function module_configuration_url( $module ) {
2447
		$module = Jetpack::get_module_slug( $module );
2448
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2449
	}
2450
2451
	public static function module_configuration_load( $module, $method ) {
2452
		$module = Jetpack::get_module_slug( $module );
2453
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2454
	}
2455
2456
	public static function module_configuration_head( $module, $method ) {
2457
		$module = Jetpack::get_module_slug( $module );
2458
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2459
	}
2460
2461
	public static function module_configuration_screen( $module, $method ) {
2462
		$module = Jetpack::get_module_slug( $module );
2463
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2464
	}
2465
2466
	public static function module_configuration_activation_screen( $module, $method ) {
2467
		$module = Jetpack::get_module_slug( $module );
2468
		add_action( 'display_activate_module_setting_' . $module, $method );
2469
	}
2470
2471
/* Installation */
2472
2473
	public static function bail_on_activation( $message, $deactivate = true ) {
2474
?>
2475
<!doctype html>
2476
<html>
2477
<head>
2478
<meta charset="<?php bloginfo( 'charset' ); ?>">
2479
<style>
2480
* {
2481
	text-align: center;
2482
	margin: 0;
2483
	padding: 0;
2484
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2485
}
2486
p {
2487
	margin-top: 1em;
2488
	font-size: 18px;
2489
}
2490
</style>
2491
<body>
2492
<p><?php echo esc_html( $message ); ?></p>
2493
</body>
2494
</html>
2495
<?php
2496
		if ( $deactivate ) {
2497
			$plugins = get_option( 'active_plugins' );
2498
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2499
			$update  = false;
2500
			foreach ( $plugins as $i => $plugin ) {
2501
				if ( $plugin === $jetpack ) {
2502
					$plugins[$i] = false;
2503
					$update = true;
2504
				}
2505
			}
2506
2507
			if ( $update ) {
2508
				update_option( 'active_plugins', array_filter( $plugins ) );
2509
			}
2510
		}
2511
		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...
2512
	}
2513
2514
	/**
2515
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2516
	 * @static
2517
	 */
2518
	public static function plugin_activation( $network_wide ) {
2519
		Jetpack_Options::update_option( 'activated', 1 );
2520
2521
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2522
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2523
		}
2524
2525
		if ( $network_wide )
2526
			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...
2527
2528
		Jetpack::plugin_initialize();
2529
	}
2530
	/**
2531
	 * Runs before bumping version numbers up to a new version
2532
	 * @param  (string) $version    Version:timestamp
2533
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2534
	 * @return null              [description]
2535
	 */
2536
	public static function do_version_bump( $version, $old_version ) {
2537
2538
		if ( ! $old_version ) { // For new sites
2539
			// Setting up jetpack manage
2540
			Jetpack::activate_manage();
2541
		}
2542
	}
2543
2544
	/**
2545
	 * Sets the internal version number and activation state.
2546
	 * @static
2547
	 */
2548
	public static function plugin_initialize() {
2549
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2550
			Jetpack_Options::update_option( 'activated', 2 );
2551
		}
2552
2553 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2554
			$version = $old_version = JETPACK__VERSION . ':' . time();
2555
			/** This action is documented in class.jetpack.php */
2556
			do_action( 'updating_jetpack_version', $version, false );
2557
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2558
		}
2559
2560
		Jetpack::load_modules();
2561
2562
		Jetpack_Options::delete_option( 'do_activate' );
2563
	}
2564
2565
	/**
2566
	 * Removes all connection options
2567
	 * @static
2568
	 */
2569
	public static function plugin_deactivation( ) {
2570
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2571
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2572
			Jetpack_Network::init()->deactivate();
2573
		} else {
2574
			Jetpack::disconnect( false );
2575
			//Jetpack_Heartbeat::init()->deactivate();
2576
		}
2577
	}
2578
2579
	/**
2580
	 * Disconnects from the Jetpack servers.
2581
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2582
	 * @static
2583
	 */
2584
	public static function disconnect( $update_activated_state = true ) {
2585
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2586
		Jetpack::clean_nonces( true );
2587
2588
		// If the site is in an IDC because sync is not allowed,
2589
		// let's make sure to not disconnect the production site.
2590
		if ( ! self::validate_sync_error_idc_option() ) {
2591
			Jetpack::load_xml_rpc_client();
2592
			$xml = new Jetpack_IXR_Client();
2593
			$xml->query( 'jetpack.deregister' );
2594
		}
2595
2596
		Jetpack_Options::delete_option(
2597
			array(
2598
				'register',
2599
				'blog_token',
2600
				'user_token',
2601
				'user_tokens',
2602
				'master_user',
2603
				'time_diff',
2604
				'fallback_no_verify_ssl_certs',
2605
				'sync_error_idc',
2606
			)
2607
		);
2608
2609
		if ( $update_activated_state ) {
2610
			Jetpack_Options::update_option( 'activated', 4 );
2611
		}
2612
2613
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2614
			// Check then record unique disconnection if site has never been disconnected previously
2615
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2616
				$jetpack_unique_connection['disconnected'] = 1;
2617
			} else {
2618
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2619
					//track unique disconnect
2620
					$jetpack = Jetpack::init();
2621
2622
					$jetpack->stat( 'connections', 'unique-disconnect' );
2623
					$jetpack->do_stats( 'server_side' );
2624
				}
2625
				// increment number of times disconnected
2626
				$jetpack_unique_connection['disconnected'] += 1;
2627
			}
2628
2629
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2630
		}
2631
2632
		// Delete all the sync related data. Since it could be taking up space.
2633
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2634
		Jetpack_Sync_Sender::get_instance()->uninstall();
2635
2636
		// Disable the Heartbeat cron
2637
		Jetpack_Heartbeat::init()->deactivate();
2638
	}
2639
2640
	/**
2641
	 * Unlinks the current user from the linked WordPress.com user
2642
	 */
2643
	public static function unlink_user( $user_id = null ) {
2644
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2645
			return false;
2646
2647
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2648
2649
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2650
			return false;
2651
2652
		if ( ! isset( $tokens[ $user_id ] ) )
2653
			return false;
2654
2655
		Jetpack::load_xml_rpc_client();
2656
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2657
		$xml->query( 'jetpack.unlink_user', $user_id );
2658
2659
		unset( $tokens[ $user_id ] );
2660
2661
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2662
2663
		/**
2664
		 * Fires after the current user has been unlinked from WordPress.com.
2665
		 *
2666
		 * @since 4.1.0
2667
		 *
2668
		 * @param int $user_id The current user's ID.
2669
		 */
2670
		do_action( 'jetpack_unlinked_user', $user_id );
2671
2672
		return true;
2673
	}
2674
2675
	/**
2676
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2677
	 */
2678
	public static function try_registration() {
2679
		// Let's get some testing in beta versions and such.
2680
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2681
			// Before attempting to connect, let's make sure that the domains are viable.
2682
			$domains_to_check = array_unique( array(
2683
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2684
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2685
			) );
2686
			foreach ( $domains_to_check as $domain ) {
2687
				$result = Jetpack_Data::is_usable_domain( $domain );
2688
				if ( is_wp_error( $result ) ) {
2689
					return $result;
2690
				}
2691
			}
2692
		}
2693
2694
		$result = Jetpack::register();
2695
2696
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2697
		if ( ! $result || is_wp_error( $result ) ) {
2698
			return $result;
2699
		} else {
2700
			return true;
2701
		}
2702
	}
2703
2704
	/**
2705
	 * Tracking an internal event log. Try not to put too much chaff in here.
2706
	 *
2707
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2708
	 */
2709
	public static function log( $code, $data = null ) {
2710
		// only grab the latest 200 entries
2711
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2712
2713
		// Append our event to the log
2714
		$log_entry = array(
2715
			'time'    => time(),
2716
			'user_id' => get_current_user_id(),
2717
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2718
			'code'    => $code,
2719
		);
2720
		// Don't bother storing it unless we've got some.
2721
		if ( ! is_null( $data ) ) {
2722
			$log_entry['data'] = $data;
2723
		}
2724
		$log[] = $log_entry;
2725
2726
		// Try add_option first, to make sure it's not autoloaded.
2727
		// @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...
2728
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2729
			Jetpack_Options::update_option( 'log', $log );
2730
		}
2731
2732
		/**
2733
		 * Fires when Jetpack logs an internal event.
2734
		 *
2735
		 * @since 3.0.0
2736
		 *
2737
		 * @param array $log_entry {
2738
		 *	Array of details about the log entry.
2739
		 *
2740
		 *	@param string time Time of the event.
2741
		 *	@param int user_id ID of the user who trigerred the event.
2742
		 *	@param int blog_id Jetpack Blog ID.
2743
		 *	@param string code Unique name for the event.
2744
		 *	@param string data Data about the event.
2745
		 * }
2746
		 */
2747
		do_action( 'jetpack_log_entry', $log_entry );
2748
	}
2749
2750
	/**
2751
	 * Get the internal event log.
2752
	 *
2753
	 * @param $event (string) - only return the specific log events
2754
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2755
	 *
2756
	 * @return array of log events || WP_Error for invalid params
2757
	 */
2758
	public static function get_log( $event = false, $num = false ) {
2759
		if ( $event && ! is_string( $event ) ) {
2760
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2761
		}
2762
2763
		if ( $num && ! is_numeric( $num ) ) {
2764
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2765
		}
2766
2767
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2768
2769
		// If nothing set - act as it did before, otherwise let's start customizing the output
2770
		if ( ! $num && ! $event ) {
2771
			return $entire_log;
2772
		} else {
2773
			$entire_log = array_reverse( $entire_log );
2774
		}
2775
2776
		$custom_log_output = array();
2777
2778
		if ( $event ) {
2779
			foreach ( $entire_log as $log_event ) {
2780
				if ( $event == $log_event[ 'code' ] ) {
2781
					$custom_log_output[] = $log_event;
2782
				}
2783
			}
2784
		} else {
2785
			$custom_log_output = $entire_log;
2786
		}
2787
2788
		if ( $num ) {
2789
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2790
		}
2791
2792
		return $custom_log_output;
2793
	}
2794
2795
	/**
2796
	 * Log modification of important settings.
2797
	 */
2798
	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...
2799
		switch( $option ) {
2800
			case 'jetpack_sync_non_public_post_stati':
2801
				self::log( $option, $value );
2802
				break;
2803
		}
2804
	}
2805
2806
	/**
2807
	 * Return stat data for WPCOM sync
2808
	 */
2809
	public static function get_stat_data( $encode = true ) {
2810
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
2811
		$additional_data = self::get_additional_stat_data();
2812
2813
		$merged_data = array_merge( $heartbeat_data, $additional_data );
2814
2815
		if ( $encode ) {
2816
			return json_encode( $merged_data );
2817
		}
2818
2819
		return $merged_data;
2820
	}
2821
2822
	/**
2823
	 * Get additional stat data to sync to WPCOM
2824
	 */
2825
	public static function get_additional_stat_data( $prefix = '' ) {
2826
		global $wpdb;
2827
		$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...
2828
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2829
		$return["{$prefix}users"]          = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
2830
		$return["{$prefix}site-count"]     = 0;
2831
2832
		if ( function_exists( 'get_blog_count' ) ) {
2833
			$return["{$prefix}site-count"] = get_blog_count();
2834
		}
2835
		return $return;
2836
	}
2837
2838
	/* Admin Pages */
2839
2840
	function admin_init() {
2841
		// If the plugin is not connected, display a connect message.
2842
		if (
2843
			// the plugin was auto-activated and needs its candy
2844
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2845
		||
2846
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2847
			! Jetpack_Options::get_option( 'activated' )
2848
		) {
2849
			Jetpack::plugin_initialize();
2850
		}
2851
2852
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2853
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2854
				// Show connect notice on dashboard and plugins pages
2855
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
2856
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
2857
			}
2858
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2859
			// Upgrade: 1.1 -> 1.1.1
2860
			// Check and see if host can verify the Jetpack servers' SSL certificate
2861
			$args = array();
2862
			Jetpack_Client::_wp_remote_request(
2863
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2864
				$args,
2865
				true
2866
			);
2867
		} else {
2868
			// Show the notice on the Dashboard only for now
2869
2870
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2871
		}
2872
2873
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2874
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2875
		}
2876
2877
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2878
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2879
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2880
2881
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2882
			// Artificially throw errors in certain whitelisted cases during plugin activation
2883
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2884
		}
2885
2886
		// Jetpack Manage Activation Screen from .com
2887
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2888
2889
		// Add custom column in wp-admin/users.php to show whether user is linked.
2890
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2891
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2892
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2893
	}
2894
2895
	function admin_body_class( $admin_body_class = '' ) {
2896
		$classes = explode( ' ', trim( $admin_body_class ) );
2897
2898
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2899
2900
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2901
		return " $admin_body_class ";
2902
	}
2903
2904
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2905
		return $admin_body_class . ' jetpack-pagestyles ';
2906
	}
2907
2908
	function prepare_connect_notice() {
2909
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2910
2911
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
2912
2913
		if ( Jetpack::state( 'network_nag' ) )
2914
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
2915
	}
2916
	/**
2917
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2918
	 *
2919
	 * @return null
2920
	 */
2921
	function prepare_manage_jetpack_notice() {
2922
2923
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2924
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2925
	}
2926
2927
	function manage_activate_screen() {
2928
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2929
	}
2930
	/**
2931
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2932
	 * This function artificially throws errors for such cases (whitelisted).
2933
	 *
2934
	 * @param string $plugin The activated plugin.
2935
	 */
2936
	function throw_error_on_activate_plugin( $plugin ) {
2937
		$active_modules = Jetpack::get_active_modules();
2938
2939
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2940
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2941
			$throw = false;
2942
2943
			// Try and make sure it really was the stats plugin
2944
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2945
				if ( 'stats.php' == basename( $plugin ) ) {
2946
					$throw = true;
2947
				}
2948
			} else {
2949
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2950
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2951
					$throw = true;
2952
				}
2953
			}
2954
2955
			if ( $throw ) {
2956
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2957
			}
2958
		}
2959
	}
2960
2961
	function intercept_plugin_error_scrape_init() {
2962
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2963
	}
2964
2965
	function intercept_plugin_error_scrape( $action, $result ) {
2966
		if ( ! $result ) {
2967
			return;
2968
		}
2969
2970
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2971
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2972
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2973
			}
2974
		}
2975
	}
2976
2977
	function add_remote_request_handlers() {
2978
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2979
	}
2980
2981
	function remote_request_handlers() {
2982
		switch ( current_filter() ) {
2983
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2984
			$response = $this->upload_handler();
2985
			break;
2986
		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...
2987
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2988
			break;
2989
		}
2990
2991
		if ( ! $response ) {
2992
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2993
		}
2994
2995
		if ( is_wp_error( $response ) ) {
2996
			$status_code       = $response->get_error_data();
2997
			$error             = $response->get_error_code();
2998
			$error_description = $response->get_error_message();
2999
3000
			if ( ! is_int( $status_code ) ) {
3001
				$status_code = 400;
3002
			}
3003
3004
			status_header( $status_code );
3005
			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...
3006
		}
3007
3008
		status_header( 200 );
3009
		if ( true === $response ) {
3010
			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...
3011
		}
3012
3013
		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...
3014
	}
3015
3016
	function upload_handler() {
3017
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3018
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3019
		}
3020
3021
		$user = wp_authenticate( '', '' );
3022
		if ( ! $user || is_wp_error( $user ) ) {
3023
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3024
		}
3025
3026
		wp_set_current_user( $user->ID );
3027
3028
		if ( ! current_user_can( 'upload_files' ) ) {
3029
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3030
		}
3031
3032
		if ( empty( $_FILES ) ) {
3033
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3034
		}
3035
3036
		foreach ( array_keys( $_FILES ) as $files_key ) {
3037
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3038
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3039
			}
3040
		}
3041
3042
		$media_keys = array_keys( $_FILES['media'] );
3043
3044
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3045
		if ( ! $token || is_wp_error( $token ) ) {
3046
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3047
		}
3048
3049
		$uploaded_files = array();
3050
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3051
		unset( $GLOBALS['post'] );
3052
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3053
			$file = array();
3054
			foreach ( $media_keys as $media_key ) {
3055
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3056
			}
3057
3058
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3059
3060
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3061
			if ( $hmac_provided !== $hmac_file ) {
3062
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3063
				continue;
3064
			}
3065
3066
			$_FILES['.jetpack.upload.'] = $file;
3067
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3068
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3069
				$post_id = 0;
3070
			}
3071
			$attachment_id = media_handle_upload(
3072
				'.jetpack.upload.',
3073
				$post_id,
3074
				array(),
3075
				array(
3076
					'action' => 'jetpack_upload_file',
3077
				)
3078
			);
3079
3080
			if ( ! $attachment_id ) {
3081
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3082
			} elseif ( is_wp_error( $attachment_id ) ) {
3083
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3084
			} else {
3085
				$attachment = get_post( $attachment_id );
3086
				$uploaded_files[$index] = (object) array(
3087
					'id'   => (string) $attachment_id,
3088
					'file' => $attachment->post_title,
3089
					'url'  => wp_get_attachment_url( $attachment_id ),
3090
					'type' => $attachment->post_mime_type,
3091
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3092
				);
3093
			}
3094
		}
3095
		if ( ! is_null( $global_post ) ) {
3096
			$GLOBALS['post'] = $global_post;
3097
		}
3098
3099
		return $uploaded_files;
3100
	}
3101
3102
	/**
3103
	 * Add help to the Jetpack page
3104
	 *
3105
	 * @since Jetpack (1.2.3)
3106
	 * @return false if not the Jetpack page
3107
	 */
3108
	function admin_help() {
3109
		$current_screen = get_current_screen();
3110
3111
		// Overview
3112
		$current_screen->add_help_tab(
3113
			array(
3114
				'id'		=> 'home',
3115
				'title'		=> __( 'Home', 'jetpack' ),
3116
				'content'	=>
3117
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3118
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3119
					'<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>',
3120
			)
3121
		);
3122
3123
		// Screen Content
3124
		if ( current_user_can( 'manage_options' ) ) {
3125
			$current_screen->add_help_tab(
3126
				array(
3127
					'id'		=> 'settings',
3128
					'title'		=> __( 'Settings', 'jetpack' ),
3129
					'content'	=>
3130
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3131
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3132
						'<ol>' .
3133
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3134
							'<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>' .
3135
						'</ol>' .
3136
						'<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>'
3137
				)
3138
			);
3139
		}
3140
3141
		// Help Sidebar
3142
		$current_screen->set_help_sidebar(
3143
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3144
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3145
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3146
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3147
		);
3148
	}
3149
3150
	function admin_menu_css() {
3151
		wp_enqueue_style( 'jetpack-icons' );
3152
	}
3153
3154
	function admin_menu_order() {
3155
		return true;
3156
	}
3157
3158 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3159
		$jp_menu_order = array();
3160
3161
		foreach ( $menu_order as $index => $item ) {
3162
			if ( $item != 'jetpack' ) {
3163
				$jp_menu_order[] = $item;
3164
			}
3165
3166
			if ( $index == 0 ) {
3167
				$jp_menu_order[] = 'jetpack';
3168
			}
3169
		}
3170
3171
		return $jp_menu_order;
3172
	}
3173
3174
	function admin_head() {
3175 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3176
			/** This action is documented in class.jetpack-admin-page.php */
3177
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3178
	}
3179
3180 View Code Duplication
	function admin_banner_styles() {
3181
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3182
3183
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3184
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3185
		wp_style_add_data( 'jetpack', 'suffix', $min );
3186
	}
3187
3188
	function plugin_action_links( $actions ) {
3189
3190
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3191
3192
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3193
			return array_merge(
3194
				$jetpack_home,
3195
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3196
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3197
				$actions
3198
				);
3199
			}
3200
3201
		return array_merge( $jetpack_home, $actions );
3202
	}
3203
3204
	function admin_connect_notice() {
3205
		// Don't show the connect notice anywhere but the plugins.php after activating
3206
		$current = get_current_screen();
3207
		if ( 'plugins' !== $current->parent_base )
3208
			return;
3209
3210
		if ( ! current_user_can( 'jetpack_connect' ) )
3211
			return;
3212
3213
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3214
		?>
3215
		<div id="message" class="updated jp-banner">
3216
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3217
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3218
					<div class="jp-banner__description-container">
3219
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3220
						<p class="jp-banner__description"><?php _e( 'Please connect to or create a WordPress.com account to enable Jetpack, including powerful security, traffic, and customization services.', 'jetpack' ); ?></p>
3221
						<p class="jp-banner__button-container">
3222
							<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3223
							<a href="<?php echo Jetpack::admin_url( 'admin.php?page=jetpack' ) ?>" class="button" title="<?php esc_attr_e( 'Learn about the benefits you receive when you connect Jetpack to WordPress.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3224
						</p>
3225
					</div>
3226
			<?php else : ?>
3227
				<div class="jp-banner__content">
3228
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3229
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3230
				</div>
3231
				<div class="jp-banner__action-container">
3232
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3233
				</div>
3234
			<?php endif; ?>
3235
		</div>
3236
3237
		<?php
3238
	}
3239
3240
	/**
3241
	 * This is the first banner
3242
	 * It should be visible only to user that can update the option
3243
	 * Are not connected
3244
	 *
3245
	 * @return null
3246
	 */
3247
	function admin_jetpack_manage_notice() {
3248
		$screen = get_current_screen();
3249
3250
		// Don't show the connect notice on the jetpack settings page.
3251
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3252
			return;
3253
3254
		// Only show it if don't have the managment option set.
3255
		// And not dismissed it already.
3256
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3257
			return;
3258
		}
3259
3260
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3261
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3262
		/**
3263
		 * I think it would be great to have different wordsing depending on where you are
3264
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3265
		 * etc..
3266
		 */
3267
3268
		?>
3269
		<div id="message" class="updated jp-banner">
3270
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3271
				<div class="jp-banner__description-container">
3272
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3273
					<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>
3274
					<p class="jp-banner__button-container">
3275
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3276
						<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>
3277
					</p>
3278
				</div>
3279
		</div>
3280
		<?php
3281
	}
3282
3283
	/**
3284
	 * Returns the url that the user clicks to remove the notice for the big banner
3285
	 * @return (string)
3286
	 */
3287
	function opt_out_jetpack_manage_url() {
3288
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3289
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3290
	}
3291
	/**
3292
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3293
	 * @return (string)
3294
	 */
3295
	function opt_in_jetpack_manage_url() {
3296
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3297
	}
3298
3299
	function opt_in_jetpack_manage_notice() {
3300
		?>
3301
		<div class="wrap">
3302
			<div id="message" class="jetpack-message is-opt-in">
3303
				<?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' ); ?>
3304
			</div>
3305
		</div>
3306
		<?php
3307
3308
	}
3309
	/**
3310
	 * Determines whether to show the notice of not true = display notice
3311
	 * @return (bool)
3312
	 */
3313
	function can_display_jetpack_manage_notice() {
3314
		// never display the notice to users that can't do anything about it anyways
3315
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3316
			return false;
3317
3318
		// don't display if we are in development more
3319
		if( Jetpack::is_development_mode() ) {
3320
			return false;
3321
		}
3322
		// don't display if the site is private
3323
		if(  ! Jetpack_Options::get_option( 'public' ) )
3324
			return false;
3325
3326
		/**
3327
		 * Should the Jetpack Remote Site Management notice be displayed.
3328
		 *
3329
		 * @since 3.3.0
3330
		 *
3331
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3332
		 */
3333
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3334
	}
3335
3336
	function network_connect_notice() {
3337
		?>
3338
		<div id="message" class="updated jetpack-message">
3339
			<div class="squeezer">
3340
				<h2><?php _e( '<strong>Jetpack is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'jetpack' ) ?></h2>
3341
			</div>
3342
		</div>
3343
		<?php
3344
	}
3345
3346
	/*
3347
	 * Registration flow:
3348
	 * 1 - ::admin_page_load() action=register
3349
	 * 2 - ::try_registration()
3350
	 * 3 - ::register()
3351
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3352
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3353
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3354
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3355
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3356
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3357
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3358
	 *       jetpack_id, jetpack_secret, jetpack_public
3359
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3360
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3361
	 * 5 - user logs in with WP.com account
3362
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3363
	 *		- Jetpack_Client_Server::authorize()
3364
	 *		- Jetpack_Client_Server::get_token()
3365
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3366
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3367
	 *			- which responds with access_token, token_type, scope
3368
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3369
	 *		- Jetpack::activate_default_modules()
3370
	 *     		- Deactivates deprecated plugins
3371
	 *     		- Activates all default modules
3372
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3373
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3374
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3375
	 *     Done!
3376
	 */
3377
3378
	/**
3379
	 * Handles the page load events for the Jetpack admin page
3380
	 */
3381
	function admin_page_load() {
3382
		$error = false;
3383
3384
		// Make sure we have the right body class to hook stylings for subpages off of.
3385
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3386
3387
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3388
			// Should only be used in intermediate redirects to preserve state across redirects
3389
			Jetpack::restate();
3390
		}
3391
3392
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3393
			// User clicked in the iframe to link their accounts
3394
			if ( ! Jetpack::is_user_connected() ) {
3395
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3396
				if ( isset( $_GET['notes_iframe'] ) )
3397
					$connect_url .= '&notes_iframe';
3398
				wp_redirect( $connect_url );
3399
				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...
3400
			} else {
3401
				if ( ! isset( $_GET['calypso_env'] ) ) {
3402
					Jetpack::state( 'message', 'already_authorized' );
3403
					wp_safe_redirect( Jetpack::admin_url() );
3404
				} else {
3405
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3406
					$connect_url .= '&already_authorized=true';
3407
					wp_redirect( $connect_url );
3408
				}
3409
			}
3410
		}
3411
3412
3413
		if ( isset( $_GET['action'] ) ) {
3414
			switch ( $_GET['action'] ) {
3415
			case 'authorize':
3416
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3417
					Jetpack::state( 'message', 'already_authorized' );
3418
					wp_safe_redirect( Jetpack::admin_url() );
3419
					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...
3420
				}
3421
				Jetpack::log( 'authorize' );
3422
				$client_server = new Jetpack_Client_Server;
3423
				$client_server->client_authorize();
3424
				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...
3425
			case 'register' :
3426
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3427
					$error = 'cheatin';
3428
					break;
3429
				}
3430
				check_admin_referer( 'jetpack-register' );
3431
				Jetpack::log( 'register' );
3432
				Jetpack::maybe_set_version_option();
3433
				$registered = Jetpack::try_registration();
3434
				if ( is_wp_error( $registered ) ) {
3435
					$error = $registered->get_error_code();
3436
					Jetpack::state( 'error', $error );
3437
					Jetpack::state( 'error', $registered->get_error_message() );
3438
					break;
3439
				}
3440
3441
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3442
3443
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3444
				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...
3445
			case 'activate' :
3446
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3447
					$error = 'cheatin';
3448
					break;
3449
				}
3450
3451
				$module = stripslashes( $_GET['module'] );
3452
				check_admin_referer( "jetpack_activate-$module" );
3453
				Jetpack::log( 'activate', $module );
3454
				Jetpack::activate_module( $module );
3455
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3456
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3457
				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...
3458
			case 'activate_default_modules' :
3459
				check_admin_referer( 'activate_default_modules' );
3460
				Jetpack::log( 'activate_default_modules' );
3461
				Jetpack::restate();
3462
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3463
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3464
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3465
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3466
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3467
				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...
3468
			case 'disconnect' :
3469
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3470
					$error = 'cheatin';
3471
					break;
3472
				}
3473
3474
				check_admin_referer( 'jetpack-disconnect' );
3475
				Jetpack::log( 'disconnect' );
3476
				Jetpack::disconnect();
3477
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3478
				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...
3479
			case 'reconnect' :
3480
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3481
					$error = 'cheatin';
3482
					break;
3483
				}
3484
3485
				check_admin_referer( 'jetpack-reconnect' );
3486
				Jetpack::log( 'reconnect' );
3487
				$this->disconnect();
3488
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3489
				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...
3490 View Code Duplication
			case 'deactivate' :
3491
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3492
					$error = 'cheatin';
3493
					break;
3494
				}
3495
3496
				$modules = stripslashes( $_GET['module'] );
3497
				check_admin_referer( "jetpack_deactivate-$modules" );
3498
				foreach ( explode( ',', $modules ) as $module ) {
3499
					Jetpack::log( 'deactivate', $module );
3500
					Jetpack::deactivate_module( $module );
3501
					Jetpack::state( 'message', 'module_deactivated' );
3502
				}
3503
				Jetpack::state( 'module', $modules );
3504
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3505
				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...
3506
			case 'unlink' :
3507
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3508
				check_admin_referer( 'jetpack-unlink' );
3509
				Jetpack::log( 'unlink' );
3510
				$this->unlink_user();
3511
				Jetpack::state( 'message', 'unlinked' );
3512
				if ( 'sub-unlink' == $redirect ) {
3513
					wp_safe_redirect( admin_url() );
3514
				} else {
3515
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3516
				}
3517
				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...
3518
			default:
3519
				/**
3520
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3521
				 *
3522
				 * @since 2.6.0
3523
				 *
3524
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3525
				 */
3526
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3527
			}
3528
		}
3529
3530
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3531
			self::activate_new_modules( true );
3532
		}
3533
3534
		$message_code = Jetpack::state( 'message' );
3535
		if ( Jetpack::state( 'optin-manage' ) ) {
3536
			$activated_manage = $message_code;
3537
			$message_code = 'jetpack-manage';
3538
		}
3539
3540
		switch ( $message_code ) {
3541
		case 'jetpack-manage':
3542
			$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>';
3543
			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...
3544
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3545
			}
3546
			break;
3547
3548
		}
3549
3550
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3551
3552
		if ( ! empty( $deactivated_plugins ) ) {
3553
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3554
			$deactivated_titles  = array();
3555
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3556
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3557
					continue;
3558
				}
3559
3560
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3561
			}
3562
3563
			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...
3564
				if ( $this->message ) {
3565
					$this->message .= "<br /><br />\n";
3566
				}
3567
3568
				$this->message .= wp_sprintf(
3569
					_n(
3570
						'Jetpack contains the most recent version of the old %l plugin.',
3571
						'Jetpack contains the most recent versions of the old %l plugins.',
3572
						count( $deactivated_titles ),
3573
						'jetpack'
3574
					),
3575
					$deactivated_titles
3576
				);
3577
3578
				$this->message .= "<br />\n";
3579
3580
				$this->message .= _n(
3581
					'The old version has been deactivated and can be removed from your site.',
3582
					'The old versions have been deactivated and can be removed from your site.',
3583
					count( $deactivated_titles ),
3584
					'jetpack'
3585
				);
3586
			}
3587
		}
3588
3589
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3590
3591
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3592
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3593
		}
3594
3595 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3596
			/**
3597
			 * Fires when a module configuration page is loaded.
3598
			 * The dynamic part of the hook is the configure parameter from the URL.
3599
			 *
3600
			 * @since 1.1.0
3601
			 */
3602
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3603
		}
3604
3605
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3606
	}
3607
3608
	function admin_notices() {
3609
3610
		if ( $this->error ) {
3611
?>
3612
<div id="message" class="jetpack-message jetpack-err">
3613
	<div class="squeezer">
3614
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3615
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3616
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3617
<?php	endif; ?>
3618
	</div>
3619
</div>
3620
<?php
3621
		}
3622
3623
		if ( $this->message ) {
3624
?>
3625
<div id="message" class="jetpack-message">
3626
	<div class="squeezer">
3627
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3628
	</div>
3629
</div>
3630
<?php
3631
		}
3632
3633
		if ( $this->privacy_checks ) :
3634
			$module_names = $module_slugs = array();
3635
3636
			$privacy_checks = explode( ',', $this->privacy_checks );
3637
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3638
			foreach ( $privacy_checks as $module_slug ) {
3639
				$module = Jetpack::get_module( $module_slug );
3640
				if ( ! $module ) {
3641
					continue;
3642
				}
3643
3644
				$module_slugs[] = $module_slug;
3645
				$module_names[] = "<strong>{$module['name']}</strong>";
3646
			}
3647
3648
			$module_slugs = join( ',', $module_slugs );
3649
?>
3650
<div id="message" class="jetpack-message jetpack-err">
3651
	<div class="squeezer">
3652
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3653
		<p><?php
3654
			echo wp_kses(
3655
				wptexturize(
3656
					wp_sprintf(
3657
						_nx(
3658
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3659
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3660
							count( $privacy_checks ),
3661
							'%l = list of Jetpack module/feature names',
3662
							'jetpack'
3663
						),
3664
						$module_names
3665
					)
3666
				),
3667
				array( 'strong' => true )
3668
			);
3669
3670
			echo "\n<br />\n";
3671
3672
			echo wp_kses(
3673
				sprintf(
3674
					_nx(
3675
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3676
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3677
						count( $privacy_checks ),
3678
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3679
						'jetpack'
3680
					),
3681
					wp_nonce_url(
3682
						Jetpack::admin_url(
3683
							array(
3684
								'page'   => 'jetpack',
3685
								'action' => 'deactivate',
3686
								'module' => urlencode( $module_slugs ),
3687
							)
3688
						),
3689
						"jetpack_deactivate-$module_slugs"
3690
					),
3691
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3692
				),
3693
				array( 'a' => array( 'href' => true, 'title' => true ) )
3694
			);
3695
		?></p>
3696
	</div>
3697
</div>
3698
<?php endif;
3699
	// only display the notice if the other stuff is not there
3700
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3701
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3702
			$this->opt_in_jetpack_manage_notice();
3703
		}
3704
	}
3705
3706
	/**
3707
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3708
	 */
3709
	function stat( $group, $detail ) {
3710
		if ( ! isset( $this->stats[ $group ] ) )
3711
			$this->stats[ $group ] = array();
3712
		$this->stats[ $group ][] = $detail;
3713
	}
3714
3715
	/**
3716
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3717
	 */
3718
	function do_stats( $method = '' ) {
3719
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3720
			foreach ( $this->stats as $group => $stats ) {
3721
				if ( is_array( $stats ) && count( $stats ) ) {
3722
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3723
					if ( 'server_side' === $method ) {
3724
						self::do_server_side_stat( $args );
3725
					} else {
3726
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3727
					}
3728
				}
3729
				unset( $this->stats[ $group ] );
3730
			}
3731
		}
3732
	}
3733
3734
	/**
3735
	 * Runs stats code for a one-off, server-side.
3736
	 *
3737
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3738
	 *
3739
	 * @return bool If it worked.
3740
	 */
3741
	static function do_server_side_stat( $args ) {
3742
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3743
		if ( is_wp_error( $response ) )
3744
			return false;
3745
3746
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3747
			return false;
3748
3749
		return true;
3750
	}
3751
3752
	/**
3753
	 * Builds the stats url.
3754
	 *
3755
	 * @param $args array|string The arguments to append to the URL.
3756
	 *
3757
	 * @return string The URL to be pinged.
3758
	 */
3759
	static function build_stats_url( $args ) {
3760
		$defaults = array(
3761
			'v'    => 'wpcom2',
3762
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3763
		);
3764
		$args     = wp_parse_args( $args, $defaults );
3765
		/**
3766
		 * Filter the URL used as the Stats tracking pixel.
3767
		 *
3768
		 * @since 2.3.2
3769
		 *
3770
		 * @param string $url Base URL used as the Stats tracking pixel.
3771
		 */
3772
		$base_url = apply_filters(
3773
			'jetpack_stats_base_url',
3774
			'https://pixel.wp.com/g.gif'
3775
		);
3776
		$url      = add_query_arg( $args, $base_url );
3777
		return $url;
3778
	}
3779
3780
	static function translate_current_user_to_role() {
3781
		foreach ( self::$capability_translations as $role => $cap ) {
3782
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3783
				return $role;
3784
			}
3785
		}
3786
3787
		return false;
3788
	}
3789
3790
	static function translate_role_to_cap( $role ) {
3791
		if ( ! isset( self::$capability_translations[$role] ) ) {
3792
			return false;
3793
		}
3794
3795
		return self::$capability_translations[$role];
3796
	}
3797
3798
	static function sign_role( $role ) {
3799
		if ( ! $user_id = (int) get_current_user_id() ) {
3800
			return false;
3801
		}
3802
3803
		$token = Jetpack_Data::get_access_token();
3804
		if ( ! $token || is_wp_error( $token ) ) {
3805
			return false;
3806
		}
3807
3808
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3809
	}
3810
3811
3812
	/**
3813
	 * Builds a URL to the Jetpack connection auth page
3814
	 *
3815
	 * @since 3.9.5
3816
	 *
3817
	 * @param bool $raw If true, URL will not be escaped.
3818
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3819
	 *                              If string, will be a custom redirect.
3820
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3821
	 *
3822
	 * @return string Connect URL
3823
	 */
3824
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
3825
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
3826
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3827
			if( is_network_admin() ) {
3828
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3829
			}
3830
		} else {
3831
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3832
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3833
			}
3834
3835
			$role = self::translate_current_user_to_role();
3836
			$signed_role = self::sign_role( $role );
3837
3838
			$user = wp_get_current_user();
3839
3840
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3841
			$redirect = $redirect
3842
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3843
				: $jetpack_admin_page;
3844
3845
			if( isset( $_REQUEST['is_multisite'] ) ) {
3846
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3847
			}
3848
3849
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
3850
			@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...
3851
3852
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3853
				? get_site_icon_url()
3854
				: false;
3855
3856
			/**
3857
			 * Filter the type of authorization.
3858
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
3859
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3860
			 *
3861
			 * @since 4.3.3
3862
			 *
3863
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3864
			 */
3865
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3866
3867
			$args = urlencode_deep(
3868
				array(
3869
					'response_type' => 'code',
3870
					'client_id'     => Jetpack_Options::get_option( 'id' ),
3871
					'redirect_uri'  => add_query_arg(
3872
						array(
3873
							'action'   => 'authorize',
3874
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3875
							'redirect' => urlencode( $redirect ),
3876
						),
3877
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
3878
					),
3879
					'state'         => $user->ID,
3880
					'scope'         => $signed_role,
3881
					'user_email'    => $user->user_email,
3882
					'user_login'    => $user->user_login,
3883
					'is_active'     => Jetpack::is_active(),
3884
					'jp_version'    => JETPACK__VERSION,
3885
					'auth_type'     => $auth_type,
3886
					'secret'        => $secret,
3887
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
3888
					'blogname'      => get_option( 'blogname' ),
3889
					'site_url'      => site_url(),
3890
					'home_url'      => home_url(),
3891
					'site_icon'     => $site_icon,
3892
				)
3893
			);
3894
3895
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
3896
		}
3897
3898
		if ( $from ) {
3899
			$url = add_query_arg( 'from', $from, $url );
3900
		}
3901
3902
		if ( isset( $_GET['calypso_env'] ) ) {
3903
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
3904
		}
3905
3906
		return $raw ? $url : esc_url( $url );
3907
	}
3908
3909
	function build_reconnect_url( $raw = false ) {
3910
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
3911
		return $raw ? $url : esc_url( $url );
3912
	}
3913
3914
	public static function admin_url( $args = null ) {
3915
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
3916
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
3917
		return $url;
3918
	}
3919
3920
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
3921
		$actionurl = str_replace( '&amp;', '&', $actionurl );
3922
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
3923
	}
3924
3925
	function dismiss_jetpack_notice() {
3926
3927
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
3928
			return;
3929
		}
3930
3931
		switch( $_GET['jetpack-notice'] ) {
3932
			case 'dismiss':
3933
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
3934
3935
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
3936
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
3937
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
3938
				}
3939
				break;
3940 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...
3941
3942
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
3943
					// Don't show the banner again
3944
3945
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
3946
					// redirect back to the page that had the notice
3947
					if ( wp_get_referer() ) {
3948
						wp_safe_redirect( wp_get_referer() );
3949
					} else {
3950
						// Take me to Jetpack
3951
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3952
					}
3953
				}
3954
				break;
3955 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...
3956
3957
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
3958
					// Don't show the banner again
3959
3960
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
3961
					// redirect back to the page that had the notice
3962
					if ( wp_get_referer() ) {
3963
						wp_safe_redirect( wp_get_referer() );
3964
					} else {
3965
						// Take me to Jetpack
3966
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3967
					}
3968
				}
3969
				break;
3970
			case 'jetpack-manage-opt-in':
3971
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
3972
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
3973
3974
					$redirection_url = Jetpack::admin_url();
3975
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3976
3977
					// Don't redirect form the Jetpack Setting Page
3978
					$referer_parsed = parse_url ( wp_get_referer() );
3979
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
3980
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
3981
						// Take the user to Jetpack home except when on the setting page
3982
						$redirection_url = wp_get_referer();
3983
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3984
					}
3985
					// Also update the JSON API FULL MANAGEMENT Option
3986
					Jetpack::activate_module( 'manage', false, false );
3987
3988
					// Special Message when option in.
3989
					Jetpack::state( 'optin-manage', 'true' );
3990
					// Activate the Module if not activated already
3991
3992
					// Redirect properly
3993
					wp_safe_redirect( $redirection_url );
3994
3995
				}
3996
				break;
3997
		}
3998
	}
3999
4000
	function debugger_page() {
4001
		nocache_headers();
4002
		if ( ! current_user_can( 'manage_options' ) ) {
4003
			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...
4004
		}
4005
		Jetpack_Debugger::jetpack_debug_display_handler();
4006
		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...
4007
	}
4008
4009
	public static function admin_screen_configure_module( $module_id ) {
4010
4011
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4012
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4013
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4014
				/**
4015
				 * Fires to diplay a custom module activation screen.
4016
				 *
4017
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4018
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4019
				 *
4020
				 * @module manage
4021
				 *
4022
				 * @since 3.8.0
4023
				 *
4024
				 * @param int $module_id Module ID.
4025
				 */
4026
				do_action( 'display_activate_module_setting_' . $module_id );
4027
			} else {
4028
				self::display_activate_module_link( $module_id );
4029
			}
4030
4031
			return false;
4032
		} ?>
4033
4034
		<div id="jp-settings-screen" style="position: relative">
4035
			<h3>
4036
			<?php
4037
				$module = Jetpack::get_module( $module_id );
4038
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4039
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4040
			?>
4041
			</h3>
4042
			<?php
4043
				/**
4044
				 * Fires within the displayed message when a feature configuation is updated.
4045
				 *
4046
				 * @since 3.4.0
4047
				 *
4048
				 * @param int $module_id Module ID.
4049
				 */
4050
				do_action( 'jetpack_notices_update_settings', $module_id );
4051
				/**
4052
				 * Fires when a feature configuation screen is loaded.
4053
				 * The dynamic part of the hook, $module_id, is the module ID.
4054
				 *
4055
				 * @since 1.1.0
4056
				 */
4057
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4058
			?>
4059
		</div><?php
4060
	}
4061
4062
	/**
4063
	 * Display link to activate the module to see the settings screen.
4064
	 * @param  string $module_id
4065
	 * @return null
4066
	 */
4067
	public static function display_activate_module_link( $module_id ) {
4068
4069
		$info =  Jetpack::get_module( $module_id );
4070
		$extra = '';
4071
		$activate_url = wp_nonce_url(
4072
				Jetpack::admin_url(
4073
					array(
4074
						'page'   => 'jetpack',
4075
						'action' => 'activate',
4076
						'module' => $module_id,
4077
					)
4078
				),
4079
				"jetpack_activate-$module_id"
4080
			);
4081
4082
		?>
4083
4084
		<div class="wrap configure-module">
4085
			<div id="jp-settings-screen">
4086
				<?php
4087
				if ( $module_id == 'json-api' ) {
4088
4089
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4090
4091
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4092
4093
					$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' );
4094
4095
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4096
				} ?>
4097
4098
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4099
				<div class="narrow">
4100
					<p><?php echo  $info['description']; ?></p>
4101
					<?php if( $extra ) { ?>
4102
					<p><?php echo esc_html( $extra ); ?></p>
4103
					<?php } ?>
4104
					<p>
4105
						<?php
4106
						if( wp_get_referer() ) {
4107
							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() );
4108
						} else {
4109
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4110
						} ?>
4111
					</p>
4112
				</div>
4113
4114
			</div>
4115
		</div>
4116
4117
		<?php
4118
	}
4119
4120
	public static function sort_modules( $a, $b ) {
4121
		if ( $a['sort'] == $b['sort'] )
4122
			return 0;
4123
4124
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4125
	}
4126
4127
	function ajax_recheck_ssl() {
4128
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4129
		$result = Jetpack::permit_ssl( true );
4130
		wp_send_json( array(
4131
			'enabled' => $result,
4132
			'message' => get_transient( 'jetpack_https_test_message' )
4133
		) );
4134
	}
4135
4136
/* Client API */
4137
4138
	/**
4139
	 * Returns the requested Jetpack API URL
4140
	 *
4141
	 * @return string
4142
	 */
4143
	public static function api_url( $relative_url ) {
4144
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4145
	}
4146
4147
	/**
4148
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4149
	 */
4150
	public static function fix_url_for_bad_hosts( $url ) {
4151
		if ( 0 !== strpos( $url, 'https://' ) ) {
4152
			return $url;
4153
		}
4154
4155
		switch ( JETPACK_CLIENT__HTTPS ) {
4156
			case 'ALWAYS' :
4157
				return $url;
4158
			case 'NEVER' :
4159
				return set_url_scheme( $url, 'http' );
4160
			// default : case 'AUTO' :
4161
		}
4162
4163
		// we now return the unmodified SSL URL by default, as a security precaution
4164
		return $url;
4165
	}
4166
4167
	/**
4168
	 * Checks to see if the URL is using SSL to connect with Jetpack
4169
	 *
4170
	 * @since 2.3.3
4171
	 * @return boolean
4172
	 */
4173
	public static function permit_ssl( $force_recheck = false ) {
4174
		// Do some fancy tests to see if ssl is being supported
4175
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4176
			$message = '';
4177
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4178
				$ssl = 0;
4179
			} else {
4180
				switch ( JETPACK_CLIENT__HTTPS ) {
4181
					case 'NEVER':
4182
						$ssl = 0;
4183
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4184
						break;
4185
					case 'ALWAYS':
4186
					case 'AUTO':
4187
					default:
4188
						$ssl = 1;
4189
						break;
4190
				}
4191
4192
				// If it's not 'NEVER', test to see
4193
				if ( $ssl ) {
4194
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4195
						$ssl = 0;
4196
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4197
					} else {
4198
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4199
						if ( is_wp_error( $response ) ) {
4200
							$ssl = 0;
4201
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4202
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4203
							$ssl = 0;
4204
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4205
						}
4206
					}
4207
				}
4208
			}
4209
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4210
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4211
		}
4212
4213
		return (bool) $ssl;
4214
	}
4215
4216
	/*
4217
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4218
	 */
4219
	public function alert_auto_ssl_fail() {
4220
		if ( ! current_user_can( 'manage_options' ) )
4221
			return;
4222
4223
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4224
		?>
4225
4226
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4227
			<div class="jp-banner__content">
4228
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4229
				<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>
4230
				<p>
4231
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4232
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4233
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4234
				</p>
4235
				<p>
4236
					<?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' ),
4237
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4238
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4239
				</p>
4240
			</div>
4241
		</div>
4242
		<style>
4243
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4244
		</style>
4245
		<script type="text/javascript">
4246
			jQuery( document ).ready( function( $ ) {
4247
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4248
					var $this = $( this );
4249
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4250
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4251
					e.preventDefault();
4252
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4253
					$.post( ajaxurl, data )
4254
					  .done( function( response ) {
4255
					  	if ( response.enabled ) {
4256
					  		$( '#jetpack-ssl-warning' ).hide();
4257
					  	} else {
4258
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4259
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4260
					  	}
4261
					  }.bind( $this ) );
4262
				} );
4263
			} );
4264
		</script>
4265
4266
		<?php
4267
	}
4268
4269
	/**
4270
	 * Returns the Jetpack XML-RPC API
4271
	 *
4272
	 * @return string
4273
	 */
4274
	public static function xmlrpc_api_url() {
4275
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4276
		return untrailingslashit( $base ) . '/xmlrpc.php';
4277
	}
4278
4279
	/**
4280
	 * Creates two secret tokens and the end of life timestamp for them.
4281
	 *
4282
	 * Note these tokens are unique per call, NOT static per site for connecting.
4283
	 *
4284
	 * @since 2.6
4285
	 * @return array
4286
	 */
4287
	public function generate_secrets( $action, $exp = 600 ) {
4288
	    $secret = wp_generate_password( 32, false ) // secret_1
4289
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4290
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4291
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4292
		Jetpack_Options::update_option( $action, $secret );
4293
	    return Jetpack_Options::get_option( $action );
4294
	}
4295
4296
	/**
4297
	 * Builds the timeout limit for queries talking with the wpcom servers.
4298
	 *
4299
	 * Based on local php max_execution_time in php.ini
4300
	 *
4301
	 * @since 2.6
4302
	 * @return int
4303
	 **/
4304
	public function get_remote_query_timeout_limit() {
4305
	    $timeout = (int) ini_get( 'max_execution_time' );
4306
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4307
		$timeout = 30;
4308
	    return intval( $timeout / 2 );
4309
	}
4310
4311
4312
	/**
4313
	 * Takes the response from the Jetpack register new site endpoint and
4314
	 * verifies it worked properly.
4315
	 *
4316
	 * @since 2.6
4317
	 * @return true or Jetpack_Error
4318
	 **/
4319
	public function validate_remote_register_response( $response ) {
4320
	    	if ( is_wp_error( $response ) ) {
4321
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4322
		}
4323
4324
		$code   = wp_remote_retrieve_response_code( $response );
4325
		$entity = wp_remote_retrieve_body( $response );
4326
		if ( $entity )
4327
			$json = json_decode( $entity );
4328
		else
4329
			$json = false;
4330
4331
		$code_type = intval( $code / 100 );
4332
		if ( 5 == $code_type ) {
4333
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4334
		} elseif ( 408 == $code ) {
4335
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4336
		} elseif ( ! empty( $json->error ) ) {
4337
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4338
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4339
		} elseif ( 200 != $code ) {
4340
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4341
		}
4342
4343
		// Jetpack ID error block
4344
		if ( empty( $json->jetpack_id ) ) {
4345
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4346
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4347
			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 );
4348
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4349
			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 );
4350
		}
4351
4352
	    return true;
4353
	}
4354
	/**
4355
	 * @return bool|WP_Error
4356
	 */
4357
	public static function register() {
4358
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4359
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4360
4361
		@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...
4362 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4363
			return new Jetpack_Error( 'missing_secrets' );
4364
		}
4365
4366
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4367
4368
		$gmt_offset = get_option( 'gmt_offset' );
4369
		if ( ! $gmt_offset ) {
4370
			$gmt_offset = 0;
4371
		}
4372
4373
		$stats_options = get_option( 'stats_options' );
4374
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4375
4376
		$args = array(
4377
			'method'  => 'POST',
4378
			'body'    => array(
4379
				'siteurl'         => site_url(),
4380
				'home'            => home_url(),
4381
				'gmt_offset'      => $gmt_offset,
4382
				'timezone_string' => (string) get_option( 'timezone_string' ),
4383
				'site_name'       => (string) get_option( 'blogname' ),
4384
				'secret_1'        => $secret_1,
4385
				'secret_2'        => $secret_2,
4386
				'site_lang'       => get_locale(),
4387
				'timeout'         => $timeout,
4388
				'stats_id'        => $stats_id,
4389
				'state'           => get_current_user_id(),
4390
			),
4391
			'headers' => array(
4392
				'Accept' => 'application/json',
4393
			),
4394
			'timeout' => $timeout,
4395
		);
4396
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4397
4398
4399
		// Make sure the response is valid and does not contain any Jetpack errors
4400
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
4401
		if( is_wp_error( $valid_response ) || !$valid_response ) {
4402
		    return $valid_response;
4403
		}
4404
4405
		// Grab the response values to work with
4406
		$code   = wp_remote_retrieve_response_code( $response );
4407
		$entity = wp_remote_retrieve_body( $response );
4408
4409
		if ( $entity )
4410
			$json = json_decode( $entity );
4411
		else
4412
			$json = false;
4413
4414 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4415
			return new Jetpack_Error( 'jetpack_secret', '', $code );
4416
4417
		if ( isset( $json->jetpack_public ) ) {
4418
			$jetpack_public = (int) $json->jetpack_public;
4419
		} else {
4420
			$jetpack_public = false;
4421
		}
4422
4423
		Jetpack_Options::update_options(
4424
			array(
4425
				'id'         => (int)    $json->jetpack_id,
4426
				'blog_token' => (string) $json->jetpack_secret,
4427
				'public'     => $jetpack_public,
4428
			)
4429
		);
4430
4431
		/**
4432
		 * Fires when a site is registered on WordPress.com.
4433
		 *
4434
		 * @since 3.7.0
4435
		 *
4436
		 * @param int $json->jetpack_id Jetpack Blog ID.
4437
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4438
		 * @param int|bool $jetpack_public Is the site public.
4439
		 */
4440
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
4441
4442
		// Initialize Jump Start for the first and only time.
4443
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4444
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4445
4446
			$jetpack = Jetpack::init();
4447
4448
			$jetpack->stat( 'jumpstart', 'unique-views' );
4449
			$jetpack->do_stats( 'server_side' );
4450
		};
4451
4452
		return true;
4453
	}
4454
4455
	/**
4456
	 * If the db version is showing something other that what we've got now, bump it to current.
4457
	 *
4458
	 * @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...
4459
	 */
4460
	public static function maybe_set_version_option() {
4461
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4462
		if ( JETPACK__VERSION != $version ) {
4463
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4464
4465
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4466
				/** This action is documented in class.jetpack.php */
4467
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4468
			}
4469
4470
			return true;
4471
		}
4472
		return false;
4473
	}
4474
4475
/* Client Server API */
4476
4477
	/**
4478
	 * Loads the Jetpack XML-RPC client
4479
	 */
4480
	public static function load_xml_rpc_client() {
4481
		require_once ABSPATH . WPINC . '/class-IXR.php';
4482
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4483
	}
4484
4485
	function verify_xml_rpc_signature() {
4486
		if ( $this->xmlrpc_verification ) {
4487
			return $this->xmlrpc_verification;
4488
		}
4489
4490
		// It's not for us
4491
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4492
			return false;
4493
		}
4494
4495
		@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...
4496
		if (
4497
			empty( $token_key )
4498
		||
4499
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4500
		) {
4501
			return false;
4502
		}
4503
4504
		if ( '0' === $user_id ) {
4505
			$token_type = 'blog';
4506
			$user_id = 0;
4507
		} else {
4508
			$token_type = 'user';
4509
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4510
				return false;
4511
			}
4512
			$user_id = (int) $user_id;
4513
4514
			$user = new WP_User( $user_id );
4515
			if ( ! $user || ! $user->exists() ) {
4516
				return false;
4517
			}
4518
		}
4519
4520
		$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...
4521
		if ( ! $token ) {
4522
			return false;
4523
		}
4524
4525
		$token_check = "$token_key.";
4526
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4527
			return false;
4528
		}
4529
4530
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4531
4532
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4533
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4534
			$post_data   = $_POST;
4535
			$file_hashes = array();
4536
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4537
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4538
					continue;
4539
				}
4540
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4541
				$file_hashes[$post_data_key] = $post_data_value;
4542
			}
4543
4544
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4545
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4546
				$post_data[$post_data_key] = $post_data_value;
4547
			}
4548
4549
			ksort( $post_data );
4550
4551
			$body = http_build_query( stripslashes_deep( $post_data ) );
4552
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4553
			$body = file_get_contents( 'php://input' );
4554
		} else {
4555
			$body = null;
4556
		}
4557
		$signature = $jetpack_signature->sign_current_request(
4558
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4559
		);
4560
4561
		if ( ! $signature ) {
4562
			return false;
4563
		} else if ( is_wp_error( $signature ) ) {
4564
			return $signature;
4565
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4566
			return false;
4567
		}
4568
4569
		$timestamp = (int) $_GET['timestamp'];
4570
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4571
4572
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4573
			return false;
4574
		}
4575
4576
		$this->xmlrpc_verification = array(
4577
			'type'    => $token_type,
4578
			'user_id' => $token->external_user_id,
4579
		);
4580
4581
		return $this->xmlrpc_verification;
4582
	}
4583
4584
	/**
4585
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4586
	 */
4587
	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...
4588
		if ( is_a( $user, 'WP_User' ) ) {
4589
			return $user;
4590
		}
4591
4592
		$token_details = $this->verify_xml_rpc_signature();
4593
4594
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4595
			return $user;
4596
		}
4597
4598
		if ( 'user' !== $token_details['type'] ) {
4599
			return $user;
4600
		}
4601
4602
		if ( ! $token_details['user_id'] ) {
4603
			return $user;
4604
		}
4605
4606
		nocache_headers();
4607
4608
		return new WP_User( $token_details['user_id'] );
4609
	}
4610
4611
	function add_nonce( $timestamp, $nonce ) {
4612
		global $wpdb;
4613
		static $nonces_used_this_request = array();
4614
4615
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4616
			return $nonces_used_this_request["$timestamp:$nonce"];
4617
		}
4618
4619
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4620
		$timestamp = (int) $timestamp;
4621
		$nonce     = esc_sql( $nonce );
4622
4623
		// Raw query so we can avoid races: add_option will also update
4624
		$show_errors = $wpdb->show_errors( false );
4625
4626
		$old_nonce = $wpdb->get_row(
4627
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4628
		);
4629
4630
		if ( is_null( $old_nonce ) ) {
4631
			$return = $wpdb->query(
4632
				$wpdb->prepare(
4633
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4634
					"jetpack_nonce_{$timestamp}_{$nonce}",
4635
					time(),
4636
					'no'
4637
				)
4638
			);
4639
		} else {
4640
			$return = false;
4641
		}
4642
4643
		$wpdb->show_errors( $show_errors );
4644
4645
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4646
4647
		return $return;
4648
	}
4649
4650
	/**
4651
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4652
	 * Capture it here so we can verify the signature later.
4653
	 */
4654
	function xmlrpc_methods( $methods ) {
4655
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4656
		return $methods;
4657
	}
4658
4659
	function public_xmlrpc_methods( $methods ) {
4660
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4661
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4662
		}
4663
		return $methods;
4664
	}
4665
4666
	function jetpack_getOptions( $args ) {
4667
		global $wp_xmlrpc_server;
4668
4669
		$wp_xmlrpc_server->escape( $args );
4670
4671
		$username	= $args[1];
4672
		$password	= $args[2];
4673
4674
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4675
			return $wp_xmlrpc_server->error;
4676
		}
4677
4678
		$options = array();
4679
		$user_data = $this->get_connected_user_data();
4680
		if ( is_array( $user_data ) ) {
4681
			$options['jetpack_user_id'] = array(
4682
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4683
				'readonly'      => true,
4684
				'value'         => $user_data['ID'],
4685
			);
4686
			$options['jetpack_user_login'] = array(
4687
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4688
				'readonly'      => true,
4689
				'value'         => $user_data['login'],
4690
			);
4691
			$options['jetpack_user_email'] = array(
4692
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4693
				'readonly'      => true,
4694
				'value'         => $user_data['email'],
4695
			);
4696
			$options['jetpack_user_site_count'] = array(
4697
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4698
				'readonly'      => true,
4699
				'value'         => $user_data['site_count'],
4700
			);
4701
		}
4702
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4703
		$args = stripslashes_deep( $args );
4704
		return $wp_xmlrpc_server->wp_getOptions( $args );
4705
	}
4706
4707
	function xmlrpc_options( $options ) {
4708
		$jetpack_client_id = false;
4709
		if ( self::is_active() ) {
4710
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4711
		}
4712
		$options['jetpack_version'] = array(
4713
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4714
				'readonly'      => true,
4715
				'value'         => JETPACK__VERSION,
4716
		);
4717
4718
		$options['jetpack_client_id'] = array(
4719
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4720
				'readonly'      => true,
4721
				'value'         => $jetpack_client_id,
4722
		);
4723
		return $options;
4724
	}
4725
4726
	public static function clean_nonces( $all = false ) {
4727
		global $wpdb;
4728
4729
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4730
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4731
4732
		if ( true !== $all ) {
4733
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4734
			$sql_args[] = time() - 3600;
4735
		}
4736
4737
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4738
4739
		$sql = $wpdb->prepare( $sql, $sql_args );
4740
4741
		for ( $i = 0; $i < 1000; $i++ ) {
4742
			if ( ! $wpdb->query( $sql ) ) {
4743
				break;
4744
			}
4745
		}
4746
	}
4747
4748
	/**
4749
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4750
	 * SET: state( $key, $value );
4751
	 * GET: $value = state( $key );
4752
	 *
4753
	 * @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...
4754
	 * @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...
4755
	 * @param bool $restate private
4756
	 */
4757
	public static function state( $key = null, $value = null, $restate = false ) {
4758
		static $state = array();
4759
		static $path, $domain;
4760
		if ( ! isset( $path ) ) {
4761
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4762
			$admin_url = Jetpack::admin_url();
4763
			$bits      = parse_url( $admin_url );
4764
4765
			if ( is_array( $bits ) ) {
4766
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4767
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4768
			} else {
4769
				$path = $domain = null;
4770
			}
4771
		}
4772
4773
		// Extract state from cookies and delete cookies
4774
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4775
			$yum = $_COOKIE[ 'jetpackState' ];
4776
			unset( $_COOKIE[ 'jetpackState' ] );
4777
			foreach ( $yum as $k => $v ) {
4778
				if ( strlen( $v ) )
4779
					$state[ $k ] = $v;
4780
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4781
			}
4782
		}
4783
4784
		if ( $restate ) {
4785
			foreach ( $state as $k => $v ) {
4786
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4787
			}
4788
			return;
4789
		}
4790
4791
		// Get a state variable
4792
		if ( isset( $key ) && ! isset( $value ) ) {
4793
			if ( array_key_exists( $key, $state ) )
4794
				return $state[ $key ];
4795
			return null;
4796
		}
4797
4798
		// Set a state variable
4799
		if ( isset ( $key ) && isset( $value ) ) {
4800
			if( is_array( $value ) && isset( $value[0] ) ) {
4801
				$value = $value[0];
4802
			}
4803
			$state[ $key ] = $value;
4804
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4805
		}
4806
	}
4807
4808
	public static function restate() {
4809
		Jetpack::state( null, null, true );
4810
	}
4811
4812
	public static function check_privacy( $file ) {
4813
		static $is_site_publicly_accessible = null;
4814
4815
		if ( is_null( $is_site_publicly_accessible ) ) {
4816
			$is_site_publicly_accessible = false;
4817
4818
			Jetpack::load_xml_rpc_client();
4819
			$rpc = new Jetpack_IXR_Client();
4820
4821
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4822
			if ( $success ) {
4823
				$response = $rpc->getResponse();
4824
				if ( $response ) {
4825
					$is_site_publicly_accessible = true;
4826
				}
4827
			}
4828
4829
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4830
		}
4831
4832
		if ( $is_site_publicly_accessible ) {
4833
			return;
4834
		}
4835
4836
		$module_slug = self::get_module_slug( $file );
4837
4838
		$privacy_checks = Jetpack::state( 'privacy_checks' );
4839
		if ( ! $privacy_checks ) {
4840
			$privacy_checks = $module_slug;
4841
		} else {
4842
			$privacy_checks .= ",$module_slug";
4843
		}
4844
4845
		Jetpack::state( 'privacy_checks', $privacy_checks );
4846
	}
4847
4848
	/**
4849
	 * Helper method for multicall XMLRPC.
4850
	 */
4851
	public static function xmlrpc_async_call() {
4852
		global $blog_id;
4853
		static $clients = array();
4854
4855
		$client_blog_id = is_multisite() ? $blog_id : 0;
4856
4857
		if ( ! isset( $clients[$client_blog_id] ) ) {
4858
			Jetpack::load_xml_rpc_client();
4859
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
4860
			if ( function_exists( 'ignore_user_abort' ) ) {
4861
				ignore_user_abort( true );
4862
			}
4863
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
4864
		}
4865
4866
		$args = func_get_args();
4867
4868
		if ( ! empty( $args[0] ) ) {
4869
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
4870
		} elseif ( is_multisite() ) {
4871
			foreach ( $clients as $client_blog_id => $client ) {
4872
				if ( ! $client_blog_id || empty( $client->calls ) ) {
4873
					continue;
4874
				}
4875
4876
				$switch_success = switch_to_blog( $client_blog_id, true );
4877
				if ( ! $switch_success ) {
4878
					continue;
4879
				}
4880
4881
				flush();
4882
				$client->query();
4883
4884
				restore_current_blog();
4885
			}
4886
		} else {
4887
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
4888
				flush();
4889
				$clients[0]->query();
4890
			}
4891
		}
4892
	}
4893
4894
	public static function staticize_subdomain( $url ) {
4895
4896
		// Extract hostname from URL
4897
		$host = parse_url( $url, PHP_URL_HOST );
4898
4899
		// Explode hostname on '.'
4900
		$exploded_host = explode( '.', $host );
4901
4902
		// Retrieve the name and TLD
4903
		if ( count( $exploded_host ) > 1 ) {
4904
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
4905
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
4906
			// Rebuild domain excluding subdomains
4907
			$domain = $name . '.' . $tld;
4908
		} else {
4909
			$domain = $host;
4910
		}
4911
		// Array of Automattic domains
4912
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
4913
4914
		// Return $url if not an Automattic domain
4915
		if ( ! in_array( $domain, $domain_whitelist ) ) {
4916
			return $url;
4917
		}
4918
4919
		if ( is_ssl() ) {
4920
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
4921
		}
4922
4923
		srand( crc32( basename( $url ) ) );
4924
		$static_counter = rand( 0, 2 );
4925
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
4926
4927
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
4928
	}
4929
4930
/* JSON API Authorization */
4931
4932
	/**
4933
	 * Handles the login action for Authorizing the JSON API
4934
	 */
4935
	function login_form_json_api_authorization() {
4936
		$this->verify_json_api_authorization_request();
4937
4938
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
4939
4940
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
4941
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
4942
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
4943
	}
4944
4945
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
4946
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
4947
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
4948
			return $url;
4949
		}
4950
4951
		$parsed_url = parse_url( $url );
4952
		$url = strtok( $url, '?' );
4953
		$url = "$url?{$_SERVER['QUERY_STRING']}";
4954
		if ( ! empty( $parsed_url['query'] ) )
4955
			$url .= "&{$parsed_url['query']}";
4956
4957
		return $url;
4958
	}
4959
4960
	// Make sure the POSTed request is handled by the same action
4961
	function preserve_action_in_login_form_for_json_api_authorization() {
4962
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
4963
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
4964
	}
4965
4966
	// If someone logs in to approve API access, store the Access Code in usermeta
4967
	function store_json_api_authorization_token( $user_login, $user ) {
4968
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
4969
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
4970
		$token = wp_generate_password( 32, false );
4971
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
4972
	}
4973
4974
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
4975
	function allow_wpcom_public_api_domain( $domains ) {
4976
		$domains[] = 'public-api.wordpress.com';
4977
		return $domains;
4978
	}
4979
4980
	// Add the Access Code details to the public-api.wordpress.com redirect
4981
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
4982
		return add_query_arg(
4983
			urlencode_deep(
4984
				array(
4985
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
4986
					'jetpack-user-id' => (int) $user->ID,
4987
					'jetpack-state'   => $this->json_api_authorization_request['state'],
4988
				)
4989
			),
4990
			$redirect_to
4991
		);
4992
	}
4993
4994
	// Verifies the request by checking the signature
4995
	function verify_json_api_authorization_request() {
4996
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4997
4998
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
4999
		if ( ! $token || empty( $token->secret ) ) {
5000
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5001
		}
5002
5003
		$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' );
5004
5005
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5006
5007
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5008
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5009
		} else {
5010
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5011
		}
5012
5013
		if ( ! $signature ) {
5014
			wp_die( $die_error );
5015
		} else if ( is_wp_error( $signature ) ) {
5016
			wp_die( $die_error );
5017
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5018
			if ( is_ssl() ) {
5019
				// 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
5020
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5021
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $_GET['signature'] ) ) {
5022
					wp_die( $die_error );
5023
				}
5024
			} else {
5025
				wp_die( $die_error );
5026
			}
5027
		}
5028
5029
		$timestamp = (int) $_GET['timestamp'];
5030
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5031
5032
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5033
			// De-nonce the nonce, at least for 5 minutes.
5034
			// 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)
5035
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5036
			if ( $old_nonce_time < time() - 300 ) {
5037
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5038
			}
5039
		}
5040
5041
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5042
		$data_filters = array(
5043
			'state'        => 'opaque',
5044
			'client_id'    => 'int',
5045
			'client_title' => 'string',
5046
			'client_image' => 'url',
5047
		);
5048
5049
		foreach ( $data_filters as $key => $sanitation ) {
5050
			if ( ! isset( $data->$key ) ) {
5051
				wp_die( $die_error );
5052
			}
5053
5054
			switch ( $sanitation ) {
5055
			case 'int' :
5056
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5057
				break;
5058
			case 'opaque' :
5059
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5060
				break;
5061
			case 'string' :
5062
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5063
				break;
5064
			case 'url' :
5065
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5066
				break;
5067
			}
5068
		}
5069
5070
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5071
			wp_die( $die_error );
5072
		}
5073
	}
5074
5075
	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...
5076
		return '<p class="message">' . sprintf(
5077
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5078
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5079
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5080
	}
5081
5082
	/**
5083
	 * Get $content_width, but with a <s>twist</s> filter.
5084
	 */
5085
	public static function get_content_width() {
5086
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5087
		/**
5088
		 * Filter the Content Width value.
5089
		 *
5090
		 * @since 2.2.3
5091
		 *
5092
		 * @param string $content_width Content Width value.
5093
		 */
5094
		return apply_filters( 'jetpack_content_width', $content_width );
5095
	}
5096
5097
	/**
5098
	 * Centralize the function here until it gets added to core.
5099
	 *
5100
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5101
	 * @param int $size Size of the avatar image
5102
	 * @param string $default URL to a default image to use if no avatar is available
5103
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5104
	 *
5105
	 * @return array First element is the URL, second is the class.
5106
	 */
5107
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5108
		// Don't bother adding the __return_true filter if it's already there.
5109
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5110
5111
		if ( $force_display && ! $has_filter )
5112
			add_filter( 'pre_option_show_avatars', '__return_true' );
5113
5114
		$avatar = get_avatar( $id_or_email, $size, $default );
5115
5116
		if ( $force_display && ! $has_filter )
5117
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5118
5119
		// If no data, fail out.
5120
		if ( is_wp_error( $avatar ) || ! $avatar )
5121
			return array( null, null );
5122
5123
		// Pull out the URL.  If it's not there, fail out.
5124
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5125
			return array( null, null );
5126
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5127
5128
		// Pull out the class, but it's not a big deal if it's missing.
5129
		$class = '';
5130
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5131
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5132
5133
		return array( $url, $class );
5134
	}
5135
5136
	/**
5137
	 * Pings the WordPress.com Mirror Site for the specified options.
5138
	 *
5139
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5140
	 *
5141
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5142
	 */
5143
	public function get_cloud_site_options( $option_names ) {
5144
		$option_names = array_filter( (array) $option_names, 'is_string' );
5145
5146
		Jetpack::load_xml_rpc_client();
5147
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5148
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5149
		if ( $xml->isError() ) {
5150
			return array(
5151
				'error_code' => $xml->getErrorCode(),
5152
				'error_msg'  => $xml->getErrorMessage(),
5153
			);
5154
		}
5155
		$cloud_site_options = $xml->getResponse();
5156
5157
		return $cloud_site_options;
5158
	}
5159
5160
	/**
5161
	 * Checks if the site is currently in an identity crisis.
5162
	 *
5163
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5164
	 */
5165
	public static function check_identity_crisis() {
5166
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5167
			return false;
5168
		}
5169
5170
		return Jetpack_Options::get_option( 'sync_error_idc' );
5171
	}
5172
5173
	/**
5174
	 * Checks whether the home and siteurl specifically are whitelisted
5175
	 * Written so that we don't have re-check $key and $value params every time
5176
	 * we want to check if this site is whitelisted, for example in footer.php
5177
	 *
5178
	 * @since  3.8.0
5179
	 * @return bool True = already whitelisted False = not whitelisted
5180
	 */
5181
	public static function is_staging_site() {
5182
		$is_staging = false;
5183
5184
		$known_staging = array(
5185
			'urls' => array(
5186
				'#\.staging\.wpengine\.com$#i', // WP Engine
5187
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5188
				),
5189
			'constants' => array(
5190
				'IS_WPE_SNAPSHOT',      // WP Engine
5191
				'KINSTA_DEV_ENV',       // Kinsta.com
5192
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5193
				'JETPACK_STAGING_MODE', // Generic
5194
				)
5195
			);
5196
		/**
5197
		 * Filters the flags of known staging sites.
5198
		 *
5199
		 * @since 3.9.0
5200
		 *
5201
		 * @param array $known_staging {
5202
		 *     An array of arrays that each are used to check if the current site is staging.
5203
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5204
		 *     @type array $constants PHP constants of known staging/developement environments.
5205
		 *  }
5206
		 */
5207
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5208
5209
		if ( isset( $known_staging['urls'] ) ) {
5210
			foreach ( $known_staging['urls'] as $url ){
5211
				if ( preg_match( $url, site_url() ) ) {
5212
					$is_staging = true;
5213
					break;
5214
				}
5215
			}
5216
		}
5217
5218
		if ( isset( $known_staging['constants'] ) ) {
5219
			foreach ( $known_staging['constants'] as $constant ) {
5220
				if ( defined( $constant ) && constant( $constant ) ) {
5221
					$is_staging = true;
5222
				}
5223
			}
5224
		}
5225
5226
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5227
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5228
			$is_staging = true;
5229
		}
5230
5231
		/**
5232
		 * Filters is_staging_site check.
5233
		 *
5234
		 * @since 3.9.0
5235
		 *
5236
		 * @param bool $is_staging If the current site is a staging site.
5237
		 */
5238
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5239
	}
5240
5241
	/**
5242
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5243
	 *
5244
	 * @return bool
5245
	 */
5246
	public static function validate_sync_error_idc_option() {
5247
		$is_valid = false;
5248
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5249
		$local_options = self::get_sync_error_idc_option();
5250
5251
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5252
		if ( $sync_error && self::sync_idc_optin() ) {
5253
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5254
				$is_valid = true;
5255
			}
5256
		}
5257
5258
		/**
5259
		 * Filters whether the sync_error_idc option is valid.
5260
		 *
5261
		 * @since 4.4.0
5262
		 *
5263
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5264
		 */
5265
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5266
5267
		if ( ! $is_valid && $sync_error ) {
5268
			// Since the option exists, and did not validate, delete it
5269
			Jetpack_Options::delete_option( 'sync_error_idc' );
5270
		}
5271
5272
		return $is_valid;
5273
	}
5274
5275
	/**
5276
	 * Normalizes a url by doing three things:
5277
	 *  - Strips protocol
5278
	 *  - Strips www
5279
	 *  - Adds a trailing slash
5280
	 *
5281
	 * @since 4.4.0
5282
	 * @param string $url
5283
	 * @return WP_Error|string
5284
	 */
5285
	public static function normalize_url_protocol_agnostic( $url ) {
5286
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5287
		if ( ! $parsed_url ) {
5288
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5289
		}
5290
5291
		// Strip www and protocols
5292
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5293
		return $url;
5294
	}
5295
5296
	/**
5297
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5298
	 *
5299
	 * @since 4.4.0
5300
	 *
5301
	 * @param array $response
5302
	 * @return array Array of the local urls, wpcom urls, and error code
5303
	 */
5304
	public static function get_sync_error_idc_option( $response = array() ) {
5305
		$local_options = array(
5306
			'home' => get_home_url(),
5307
			'siteurl' => get_site_url(),
5308
		);
5309
5310
		$options = array_merge( $local_options, $response );
5311
5312
		$returned_values = array();
5313
		foreach( $options as $key => $option ) {
5314
			if ( 'error_code' === $key ) {
5315
				$returned_values[ $key ] = $option;
5316
				continue;
5317
			}
5318
5319
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5320
				continue;
5321
			}
5322
5323
			$returned_values[ $key ] = $normalized_url;
5324
		}
5325
5326
		return $returned_values;
5327
	}
5328
5329
	/**
5330
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5331
	 * If set to true, the site will be put into staging mode.
5332
	 *
5333
	 * @since 4.3.2
5334
	 * @return bool
5335
	 */
5336
	public static function sync_idc_optin() {
5337
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5338
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5339
		} else {
5340
			$default = false;
5341
		}
5342
5343
		/**
5344
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5345
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5346
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5347
		 *
5348
		 * @since 4.3.2
5349
		 *
5350
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5351
		 */
5352
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5353
	}
5354
5355
	/**
5356
	 * Maybe Use a .min.css stylesheet, maybe not.
5357
	 *
5358
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5359
	 */
5360
	public static function maybe_min_asset( $url, $path, $plugin ) {
5361
		// Short out on things trying to find actual paths.
5362
		if ( ! $path || empty( $plugin ) ) {
5363
			return $url;
5364
		}
5365
5366
		// Strip out the abspath.
5367
		$base = dirname( plugin_basename( $plugin ) );
5368
5369
		// Short out on non-Jetpack assets.
5370
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5371
			return $url;
5372
		}
5373
5374
		// File name parsing.
5375
		$file              = "{$base}/{$path}";
5376
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5377
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5378
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5379
		$extension         = array_shift( $file_name_parts_r );
5380
5381
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5382
			// Already pointing at the minified version.
5383
			if ( 'min' === $file_name_parts_r[0] ) {
5384
				return $url;
5385
			}
5386
5387
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5388
			if ( file_exists( $min_full_path ) ) {
5389
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5390
			}
5391
		}
5392
5393
		return $url;
5394
	}
5395
5396
	/**
5397
	 * Maybe inlines a stylesheet.
5398
	 *
5399
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5400
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5401
	 *
5402
	 * Attached to `style_loader_tag` filter.
5403
	 *
5404
	 * @param string $tag The tag that would link to the external asset.
5405
	 * @param string $handle The registered handle of the script in question.
5406
	 *
5407
	 * @return string
5408
	 */
5409
	public static function maybe_inline_style( $tag, $handle ) {
5410
		global $wp_styles;
5411
		$item = $wp_styles->registered[ $handle ];
5412
5413
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5414
			return $tag;
5415
		}
5416
5417
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5418
			$href = $matches[1];
5419
			// Strip off query string
5420
			if ( $pos = strpos( $href, '?' ) ) {
5421
				$href = substr( $href, 0, $pos );
5422
			}
5423
			// Strip off fragment
5424
			if ( $pos = strpos( $href, '#' ) ) {
5425
				$href = substr( $href, 0, $pos );
5426
			}
5427
		} else {
5428
			return $tag;
5429
		}
5430
5431
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5432
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5433
			return $tag;
5434
		}
5435
5436
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5437
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5438
			// And this isn't the pass that actually deals with the RTL version...
5439
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5440
				// Short out, as the RTL version will deal with it in a moment.
5441
				return $tag;
5442
			}
5443
		}
5444
5445
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5446
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5447
		if ( $css ) {
5448
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5449
			if ( empty( $item->extra['after'] ) ) {
5450
				wp_add_inline_style( $handle, $css );
5451
			} else {
5452
				array_unshift( $item->extra['after'], $css );
5453
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5454
			}
5455
		}
5456
5457
		return $tag;
5458
	}
5459
5460
	/**
5461
	 * Loads a view file from the views
5462
	 *
5463
	 * Data passed in with the $data parameter will be available in the
5464
	 * template file as $data['value']
5465
	 *
5466
	 * @param string $template - Template file to load
5467
	 * @param array $data - Any data to pass along to the template
5468
	 * @return boolean - If template file was found
5469
	 **/
5470
	public function load_view( $template, $data = array() ) {
5471
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5472
5473
		if( file_exists( $views_dir . $template ) ) {
5474
			require_once( $views_dir . $template );
5475
			return true;
5476
		}
5477
5478
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5479
		return false;
5480
	}
5481
5482
	/**
5483
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5484
	 */
5485
	public function deprecated_hooks() {
5486
		global $wp_filter;
5487
5488
		/*
5489
		 * Format:
5490
		 * deprecated_filter_name => replacement_name
5491
		 *
5492
		 * If there is no replacement us null for replacement_name
5493
		 */
5494
		$deprecated_list = array(
5495
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5496
			'wpl_sharing_2014_1'                                     => null,
5497
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5498
			'jetpack_identity_crisis_options_to_check'               => null,
5499
			'update_option_jetpack_single_user_site'                 => null,
5500
			'audio_player_default_colors'                            => null,
5501
			'add_option_jetpack_featured_images_enabled'             => null,
5502
			'add_option_jetpack_update_details'                      => null,
5503
			'add_option_jetpack_updates'                             => null,
5504
			'add_option_jetpack_network_name'                        => null,
5505
			'add_option_jetpack_network_allow_new_registrations'     => null,
5506
			'add_option_jetpack_network_add_new_users'               => null,
5507
			'add_option_jetpack_network_site_upload_space'           => null,
5508
			'add_option_jetpack_network_upload_file_types'           => null,
5509
			'add_option_jetpack_network_enable_administration_menus' => null,
5510
			'add_option_jetpack_is_multi_site'                       => null,
5511
			'add_option_jetpack_is_main_network'                     => null,
5512
			'add_option_jetpack_main_network_site'                   => null,
5513
			'jetpack_sync_all_registered_options'                    => null,
5514
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5515
		);
5516
5517
		// This is a silly loop depth. Better way?
5518
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5519
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
5520
				foreach( $wp_filter[$hook] AS $func => $values ) {
5521
					foreach( $values AS $hooked ) {
5522
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
5523
					}
5524
				}
5525
			}
5526
		}
5527
	}
5528
5529
	/**
5530
	 * Converts any url in a stylesheet, to the correct absolute url.
5531
	 *
5532
	 * Considerations:
5533
	 *  - Normal, relative URLs     `feh.png`
5534
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5535
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5536
	 *  - Absolute URLs             `http://domain.com/feh.png`
5537
	 *  - Domain root relative URLs `/feh.png`
5538
	 *
5539
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5540
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5541
	 *
5542
	 * @return mixed|string
5543
	 */
5544
	public static function absolutize_css_urls( $css, $css_file_url ) {
5545
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5546
		$css_dir = dirname( $css_file_url );
5547
		$p       = parse_url( $css_dir );
5548
		$domain  = sprintf(
5549
					'%1$s//%2$s%3$s%4$s',
5550
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5551
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5552
					$p['host'],
5553
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5554
				);
5555
5556
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5557
			$find = $replace = array();
5558
			foreach ( $matches as $match ) {
5559
				$url = trim( $match['path'], "'\" \t" );
5560
5561
				// If this is a data url, we don't want to mess with it.
5562
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5563
					continue;
5564
				}
5565
5566
				// If this is an absolute or protocol-agnostic url,
5567
				// we don't want to mess with it.
5568
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5569
					continue;
5570
				}
5571
5572
				switch ( substr( $url, 0, 1 ) ) {
5573
					case '/':
5574
						$absolute = $domain . $url;
5575
						break;
5576
					default:
5577
						$absolute = $css_dir . '/' . $url;
5578
				}
5579
5580
				$find[]    = $match[0];
5581
				$replace[] = sprintf( 'url("%s")', $absolute );
5582
			}
5583
			$css = str_replace( $find, $replace, $css );
5584
		}
5585
5586
		return $css;
5587
	}
5588
5589
	/**
5590
	 * This methods removes all of the registered css files on the front end
5591
	 * from Jetpack in favor of using a single file. In effect "imploding"
5592
	 * all the files into one file.
5593
	 *
5594
	 * Pros:
5595
	 * - Uses only ONE css asset connection instead of 15
5596
	 * - Saves a minimum of 56k
5597
	 * - Reduces server load
5598
	 * - Reduces time to first painted byte
5599
	 *
5600
	 * Cons:
5601
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5602
	 *		should not cause any issues with themes.
5603
	 * - Plugins/themes dequeuing styles no longer do anything. See
5604
	 *		jetpack_implode_frontend_css filter for a workaround
5605
	 *
5606
	 * For some situations developers may wish to disable css imploding and
5607
	 * instead operate in legacy mode where each file loads seperately and
5608
	 * can be edited individually or dequeued. This can be accomplished with
5609
	 * the following line:
5610
	 *
5611
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5612
	 *
5613
	 * @since 3.2
5614
	 **/
5615
	public function implode_frontend_css( $travis_test = false ) {
5616
		$do_implode = true;
5617
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5618
			$do_implode = false;
5619
		}
5620
5621
		/**
5622
		 * Allow CSS to be concatenated into a single jetpack.css file.
5623
		 *
5624
		 * @since 3.2.0
5625
		 *
5626
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5627
		 */
5628
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5629
5630
		// Do not use the imploded file when default behaviour was altered through the filter
5631
		if ( ! $do_implode ) {
5632
			return;
5633
		}
5634
5635
		// We do not want to use the imploded file in dev mode, or if not connected
5636
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5637
			if ( ! $travis_test ) {
5638
				return;
5639
			}
5640
		}
5641
5642
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5643
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5644
			return;
5645
		}
5646
5647
		/*
5648
		 * Now we assume Jetpack is connected and able to serve the single
5649
		 * file.
5650
		 *
5651
		 * In the future there will be a check here to serve the file locally
5652
		 * or potentially from the Jetpack CDN
5653
		 *
5654
		 * For now:
5655
		 * - Enqueue a single imploded css file
5656
		 * - Zero out the style_loader_tag for the bundled ones
5657
		 * - Be happy, drink scotch
5658
		 */
5659
5660
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5661
5662
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5663
5664
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5665
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5666
	}
5667
5668
	function concat_remove_style_loader_tag( $tag, $handle ) {
5669
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5670
			$tag = '';
5671
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5672
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5673
			}
5674
		}
5675
5676
		return $tag;
5677
	}
5678
5679
	/*
5680
	 * Check the heartbeat data
5681
	 *
5682
	 * Organizes the heartbeat data by severity.  For example, if the site
5683
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5684
	 *
5685
	 * Data will be added to "caution" array, if it either:
5686
	 *  - Out of date Jetpack version
5687
	 *  - Out of date WP version
5688
	 *  - Out of date PHP version
5689
	 *
5690
	 * $return array $filtered_data
5691
	 */
5692
	public static function jetpack_check_heartbeat_data() {
5693
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5694
5695
		$good    = array();
5696
		$caution = array();
5697
		$bad     = array();
5698
5699
		foreach ( $raw_data as $stat => $value ) {
5700
5701
			// Check jetpack version
5702
			if ( 'version' == $stat ) {
5703
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5704
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5705
					continue;
5706
				}
5707
			}
5708
5709
			// Check WP version
5710
			if ( 'wp-version' == $stat ) {
5711
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5712
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5713
					continue;
5714
				}
5715
			}
5716
5717
			// Check PHP version
5718
			if ( 'php-version' == $stat ) {
5719
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5720
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5721
					continue;
5722
				}
5723
			}
5724
5725
			// Check ID crisis
5726
			if ( 'identitycrisis' == $stat ) {
5727
				if ( 'yes' == $value ) {
5728
					$bad[ $stat ] = $value;
5729
					continue;
5730
				}
5731
			}
5732
5733
			// The rest are good :)
5734
			$good[ $stat ] = $value;
5735
		}
5736
5737
		$filtered_data = array(
5738
			'good'    => $good,
5739
			'caution' => $caution,
5740
			'bad'     => $bad
5741
		);
5742
5743
		return $filtered_data;
5744
	}
5745
5746
5747
	/*
5748
	 * This method is used to organize all options that can be reset
5749
	 * without disconnecting Jetpack.
5750
	 *
5751
	 * It is used in class.jetpack-cli.php to reset options
5752
	 *
5753
	 * @return array of options to delete.
5754
	 */
5755
	public static function get_jetpack_options_for_reset() {
5756
		$jetpack_options            = Jetpack_Options::get_option_names();
5757
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
5758
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
5759
5760
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
5761
5762
		// A manual build of the wp options
5763
		$wp_options = array(
5764
			'sharing-options',
5765
			'disabled_likes',
5766
			'disabled_reblogs',
5767
			'jetpack_comments_likes_enabled',
5768
			'wp_mobile_excerpt',
5769
			'wp_mobile_featured_images',
5770
			'wp_mobile_app_promos',
5771
			'stats_options',
5772
			'stats_dashboard_widget',
5773
			'safecss_preview_rev',
5774
			'safecss_rev',
5775
			'safecss_revision_migrated',
5776
			'nova_menu_order',
5777
			'jetpack_portfolio',
5778
			'jetpack_portfolio_posts_per_page',
5779
			'jetpack_testimonial',
5780
			'jetpack_testimonial_posts_per_page',
5781
			'wp_mobile_custom_css',
5782
			'sharedaddy_disable_resources',
5783
			'sharing-options',
5784
			'sharing-services',
5785
			'site_icon_temp_data',
5786
			'featured-content',
5787
			'site_logo',
5788
			'jetpack_dismissed_notices',
5789
		);
5790
5791
		// Flag some Jetpack options as unsafe
5792
		$unsafe_options = array(
5793
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
5794
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
5795
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
5796
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
5797
5798
			// non_compact
5799
			'activated',
5800
5801
			// private
5802
			'register',
5803
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
5804
			'user_token',                  // (string) The User Token of this site. (deprecated)
5805
			'user_tokens'
5806
		);
5807
5808
		// Remove the unsafe Jetpack options
5809
		foreach ( $unsafe_options as $unsafe_option ) {
5810
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
5811
				unset( $all_jp_options[ $key ] );
5812
			}
5813
		}
5814
5815
		$options = array(
5816
			'jp_options' => $all_jp_options,
5817
			'wp_options' => $wp_options
5818
		);
5819
5820
		return $options;
5821
	}
5822
5823
	/**
5824
	 * Check if an option of a Jetpack module has been updated.
5825
	 *
5826
	 * If any module option has been updated before Jump Start has been dismissed,
5827
	 * update the 'jumpstart' option so we can hide Jump Start.
5828
	 *
5829
	 * @param string $option_name
5830
	 *
5831
	 * @return bool
5832
	 */
5833
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5834
		// Bail if Jump Start has already been dismissed
5835
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
5836
			return false;
5837
		}
5838
5839
		$jetpack = Jetpack::init();
5840
5841
		// Manual build of module options
5842
		$option_names = self::get_jetpack_options_for_reset();
5843
5844
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5845
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5846
5847
			//Jump start is being dismissed send data to MC Stats
5848
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5849
5850
			$jetpack->do_stats( 'server_side' );
5851
		}
5852
5853
	}
5854
5855
	/*
5856
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
5857
	 * so we can bring them directly to their site in calypso.
5858
	 *
5859
	 * @param string | url
5860
	 * @return string | url without the guff
5861
	 */
5862
	public static function build_raw_urls( $url ) {
5863
		$strip_http = '/.*?:\/\//i';
5864
		$url = preg_replace( $strip_http, '', $url  );
5865
		$url = str_replace( '/', '::', $url );
5866
		return $url;
5867
	}
5868
5869
	/**
5870
	 * Stores and prints out domains to prefetch for page speed optimization.
5871
	 *
5872
	 * @param mixed $new_urls
5873
	 */
5874
	public static function dns_prefetch( $new_urls = null ) {
5875
		static $prefetch_urls = array();
5876
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
5877
			echo "\r\n";
5878
			foreach ( $prefetch_urls as $this_prefetch_url ) {
5879
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
5880
			}
5881
		} elseif ( ! empty( $new_urls ) ) {
5882
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
5883
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
5884
			}
5885
			foreach ( (array) $new_urls as $this_new_url ) {
5886
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
5887
			}
5888
			$prefetch_urls = array_unique( $prefetch_urls );
5889
		}
5890
	}
5891
5892
	public function wp_dashboard_setup() {
5893
		if ( self::is_active() ) {
5894
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
5895
			$widget_title = __( 'Site Stats', 'jetpack' );
5896
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
5897
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
5898
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
5899
		}
5900
5901
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
5902
			wp_add_dashboard_widget(
5903
				'jetpack_summary_widget',
5904
				$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...
5905
				array( __CLASS__, 'dashboard_widget' )
5906
			);
5907
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
5908
5909
			// If we're inactive and not in development mode, sort our box to the top.
5910
			if ( ! self::is_active() && ! self::is_development_mode() ) {
5911
				global $wp_meta_boxes;
5912
5913
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
5914
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
5915
5916
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
5917
			}
5918
		}
5919
	}
5920
5921
	/**
5922
	 * @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...
5923
	 * @return mixed
5924
	 */
5925
	function get_user_option_meta_box_order_dashboard( $sorted ) {
5926
		if ( ! is_array( $sorted ) ) {
5927
			return $sorted;
5928
		}
5929
5930
		foreach ( $sorted as $box_context => $ids ) {
5931
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
5932
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
5933
				continue;
5934
			}
5935
5936
			$ids_array = explode( ',', $ids );
5937
			$key = array_search( 'dashboard_stats', $ids_array );
5938
5939
			if ( false !== $key ) {
5940
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
5941
				$ids_array[ $key ] = 'jetpack_summary_widget';
5942
				$sorted[ $box_context ] = implode( ',', $ids_array );
5943
				// We've found it, stop searching, and just return.
5944
				break;
5945
			}
5946
		}
5947
5948
		return $sorted;
5949
	}
5950
5951
	public static function dashboard_widget() {
5952
		/**
5953
		 * Fires when the dashboard is loaded.
5954
		 *
5955
		 * @since 3.4.0
5956
		 */
5957
		do_action( 'jetpack_dashboard_widget' );
5958
	}
5959
5960
	public static function dashboard_widget_footer() {
5961
		?>
5962
		<footer>
5963
5964
		<div class="protect">
5965
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
5966
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
5967
				<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>
5968
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
5969
				<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' ); ?>">
5970
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
5971
				</a>
5972
			<?php else : ?>
5973
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
5974
			<?php endif; ?>
5975
		</div>
5976
5977
		<div class="akismet">
5978
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
5979
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
5980
				<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>
5981
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
5982
				<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">
5983
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
5984
				</a>
5985
			<?php else : ?>
5986
				<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>
5987
			<?php endif; ?>
5988
		</div>
5989
5990
		</footer>
5991
		<?php
5992
	}
5993
5994
	public function dashboard_widget_connect_to_wpcom() {
5995
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
5996
			return;
5997
		}
5998
		?>
5999
		<div class="wpcom-connect">
6000
			<div class="jp-emblem">
6001
			<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">
6002
				<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"/>
6003
			</svg>
6004
			</div>
6005
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6006
			<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>
6007
6008
			<div class="actions">
6009
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6010
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6011
				</a>
6012
			</div>
6013
		</div>
6014
		<?php
6015
	}
6016
6017
	/*
6018
	 * A graceful transition to using Core's site icon.
6019
	 *
6020
	 * All of the hard work has already been done with the image
6021
	 * in all_done_page(). All that needs to be done now is update
6022
	 * the option and display proper messaging.
6023
	 *
6024
	 * @todo remove when WP 4.3 is minimum
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...
6025
	 *
6026
	 * @since 3.6.1
6027
	 *
6028
	 * @return bool false = Core's icon not available || true = Core's icon is available
6029
	 */
6030
	public static function jetpack_site_icon_available_in_core() {
6031
		global $wp_version;
6032
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
6033
6034
		if ( ! $core_icon_available ) {
6035
			return false;
6036
		}
6037
6038
		// No need for Jetpack's site icon anymore if core's is already set
6039
		if ( has_site_icon() ) {
6040
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
6041
				Jetpack::log( 'deactivate', 'site-icon' );
6042
				Jetpack::deactivate_module( 'site-icon' );
6043
			}
6044
			return true;
6045
		}
6046
6047
		// Transfer Jetpack's site icon to use core.
6048
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
6049
		if ( $site_icon_id ) {
6050
			// Update core's site icon
6051
			update_option( 'site_icon', $site_icon_id );
6052
6053
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
6054
			delete_option( 'site_icon_id' );
6055
		}
6056
6057
		// No need for Jetpack's site icon anymore
6058
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
6059
			Jetpack::log( 'deactivate', 'site-icon' );
6060
			Jetpack::deactivate_module( 'site-icon' );
6061
		}
6062
6063
		return true;
6064
	}
6065
6066
	/**
6067
	 * Return string containing the Jetpack logo.
6068
	 *
6069
	 * @since 3.9.0
6070
	 *
6071
	 * @return string
6072
	 */
6073
	public static function get_jp_emblem() {
6074
		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>';
6075
	}
6076
6077
	/*
6078
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6079
	 */
6080
	function jetpack_icon_user_connected( $columns ) {
6081
		$columns['user_jetpack'] = '';
6082
		return $columns;
6083
	}
6084
6085
	/*
6086
	 * Show Jetpack icon if the user is linked.
6087
	 */
6088
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6089
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6090
			$emblem_html = sprintf(
6091
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6092
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6093
				Jetpack::get_jp_emblem()
6094
			);
6095
			return $emblem_html;
6096
		}
6097
6098
		return $val;
6099
	}
6100
6101
	/*
6102
	 * Style the Jetpack user column
6103
	 */
6104
	function jetpack_user_col_style() {
6105
		global $current_screen;
6106
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6107
			<style>
6108
				.fixed .column-user_jetpack {
6109
					width: 21px;
6110
				}
6111
				.jp-emblem-user-admin path {
6112
					fill: #8cc258;
6113
				}
6114
			</style>
6115
		<?php }
6116
	}
6117
6118
}
6119