Completed
Push — fix/7598 ( 25a20b...a8e820 )
by
unknown
24:48 queued 13:24
created

Jetpack::is_main_network_option()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
		'eu-cookie-law-style',
60
		'flickr-widget-style',
61
	);
62
63
	public $plugins_to_deactivate = array(
64
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
65
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
66
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
67
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
68
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
69
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
70
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
71
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
72
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
73
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
74
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
75
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
76
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
77
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
78
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
79
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
80
	);
81
82
	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...
83
		'administrator' => 'manage_options',
84
		'editor'        => 'edit_others_posts',
85
		'author'        => 'publish_posts',
86
		'contributor'   => 'edit_posts',
87
		'subscriber'    => 'read',
88
	);
89
90
	/**
91
	 * Map of modules that have conflicts with plugins and should not be auto-activated
92
	 * if the plugins are active.  Used by filter_default_modules
93
	 *
94
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
95
	 * change `module-slug` and add this to your plugin:
96
	 *
97
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
98
	 * function my_jetpack_get_default_modules( $modules ) {
99
	 *     return array_diff( $modules, array( 'module-slug' ) );
100
	 * }
101
	 *
102
	 * @var array
103
	 */
104
	private $conflicting_plugins = array(
105
		'comments'          => array(
106
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
107
			'Disqus'                               => 'disqus-comment-system/disqus.php',
108
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
109
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
110
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
111
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
112
		),
113
		'comment-likes' => array(
114
			'Epoch'                                => 'epoch/plugincore.php',
115
		),
116
		'contact-form'      => array(
117
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
118
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
119
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
120
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
121
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
122
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
123
		),
124
		'minileven'         => array(
125
			'WPtouch'                              => 'wptouch/wptouch.php',
126
		),
127
		'latex'             => array(
128
			'LaTeX for WordPress'                  => 'latex/latex.php',
129
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
130
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
131
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
132
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
133
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
134
		),
135
		'protect'           => array(
136
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
137
			'Captcha'                              => 'captcha/captcha.php',
138
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
139
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
140
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
141
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
142
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
143
			'Security-protection'                  => 'security-protection/security-protection.php',
144
			'Login Security'                       => 'login-security/login-security.php',
145
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
146
			'Wordfence Security'                   => 'wordfence/wordfence.php',
147
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
148
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
149
		),
150
		'random-redirect'   => array(
151
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
152
		),
153
		'related-posts'     => array(
154
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
155
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
156
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
157
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
158
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
159
			'outbrain'                             => 'outbrain/outbrain.php',
160
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
161
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
162
		),
163
		'sharedaddy'        => array(
164
			'AddThis'                              => 'addthis/addthis_social_widget.php',
165
			'Add To Any'                           => 'add-to-any/add-to-any.php',
166
			'ShareThis'                            => 'share-this/sharethis.php',
167
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
168
		),
169
		'seo-tools' => array(
170
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
171
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
172
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
173
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
174
		),
175
		'verification-tools' => array(
176
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
177
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
178
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
179
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
180
		),
181
		'widget-visibility' => array(
182
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
183
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
184
		),
185
		'sitemaps' => array(
186
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
187
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
188
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
189
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
190
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'Sitemap'                              => 'sitemap/sitemap.php',
196
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
197
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
198
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
199
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
200
		),
201
	);
202
203
	/**
204
	 * Plugins for which we turn off our Facebook OG Tags implementation.
205
	 *
206
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
207
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
208
	 *
209
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
210
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
211
	 */
212
	private $open_graph_conflicting_plugins = array(
213
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
214
		                                                         // 2 Click Social Media Buttons
215
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
216
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
217
		'autodescription/autodescription.php',                   // The SEO Framework
218
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
219
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
220
		                                                         // Open Graph Meta Tags by Heateor
221
		'facebook/facebook.php',                                 // Facebook (official plugin)
222
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
223
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
224
		                                                         // Facebook Featured Image & OG Meta Tags
225
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
226
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
227
		                                                         // Facebook Open Graph Meta Tags for WordPress
228
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
229
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
230
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
231
		                                                         // Fedmich's Facebook Open Graph Meta
232
		'network-publisher/networkpub.php',                      // Network Publisher
233
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
234
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
235
		                                                         // NextScripts SNAP
236
		'og-tags/og-tags.php',                                   // OG Tags
237
		'opengraph/opengraph.php',                               // Open Graph
238
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
239
		                                                         // Open Graph Protocol Framework
240
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
241
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
242
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
243
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
244
		'sharepress/sharepress.php',                             // SharePress
245
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
246
		'social-discussions/social-discussions.php',             // Social Discussions
247
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
248
		'socialize/socialize.php',                               // Socialize
249
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
250
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
251
		                                                         // Tweet, Like, Google +1 and Share
252
		'wordbooker/wordbooker.php',                             // Wordbooker
253
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
254
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
255
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
256
		                                                         // WP Facebook Like Send & Open Graph Meta
257
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
258
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
259
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
260
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
261
	);
262
263
	/**
264
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
265
	 */
266
	private $twitter_cards_conflicting_plugins = array(
267
	//	'twitter/twitter.php',                       // The official one handles this on its own.
268
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
269
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
270
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
271
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
272
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
273
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
274
		'twitter-cards/twitter-cards.php',           // Twitter Cards
275
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
276
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
277
	);
278
279
	/**
280
	 * Message to display in admin_notice
281
	 * @var string
282
	 */
283
	public $message = '';
284
285
	/**
286
	 * Error to display in admin_notice
287
	 * @var string
288
	 */
289
	public $error = '';
290
291
	/**
292
	 * Modules that need more privacy description.
293
	 * @var string
294
	 */
295
	public $privacy_checks = '';
296
297
	/**
298
	 * Stats to record once the page loads
299
	 *
300
	 * @var array
301
	 */
302
	public $stats = array();
303
304
	/**
305
	 * Jetpack_Sync object
306
	 */
307
	public $sync;
308
309
	/**
310
	 * Verified data for JSON authorization request
311
	 */
312
	public $json_api_authorization_request = array();
313
314
	/**
315
	 * Holds the singleton instance of this class
316
	 * @since 2.3.3
317
	 * @var Jetpack
318
	 */
319
	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...
320
321
	/**
322
	 * Singleton
323
	 * @static
324
	 */
325
	public static function init() {
326
		if ( ! self::$instance ) {
327
			self::$instance = new Jetpack;
328
329
			self::$instance->plugin_upgrade();
330
		}
331
332
		return self::$instance;
333
	}
334
335
	/**
336
	 * Must never be called statically
337
	 */
338
	function plugin_upgrade() {
339
		if ( Jetpack::is_active() ) {
340
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
341
			if ( JETPACK__VERSION != $version ) {
342
343
				// check which active modules actually exist and remove others from active_modules list
344
				$unfiltered_modules = Jetpack::get_active_modules();
345
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
346
				if ( array_diff( $unfiltered_modules, $modules ) ) {
347
					Jetpack::update_active_modules( $modules );
348
				}
349
350
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
351
352
				// Upgrade to 4.3.0
353
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
354
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
355
				}
356
357
				// Make sure Markdown for posts gets turned back on
358
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
359
					update_option( 'wpcom_publish_posts_with_markdown', true );
360
				}
361
362
				if ( did_action( 'wp_loaded' ) ) {
363
					self::upgrade_on_load();
364
				} else {
365
					add_action(
366
						'wp_loaded',
367
						array( __CLASS__, 'upgrade_on_load' )
368
					);
369
				}
370
			}
371
		}
372
	}
373
374
	/**
375
	 * Runs upgrade routines that need to have modules loaded.
376
	 */
377
	static function upgrade_on_load() {
378
379
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
380
		// This can happen in case Jetpack has been just upgraded and is
381
		// being initialized late during the page load. In this case we wait
382
		// until the next proper admin page load with Jetpack active.
383
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
384
			return;
385
		}
386
387
		Jetpack::maybe_set_version_option();
388
389
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
390
			Jetpack_Widget_Conditions::migrate_post_type_rules();
391
		}
392
	}
393
394
	static function activate_manage( ) {
395
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
396
			self::activate_module( 'manage', false, false );
397
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
398
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
399
		}
400
	}
401
402
	static function update_active_modules( $modules ) {
403
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
404
405
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
406
407
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
408
			$new_active_modules = array_diff( $modules, $current_modules );
409
			foreach( $new_active_modules as $module ) {
410
				/**
411
				 * Fires when a specific module is activated.
412
				 *
413
				 * @since 1.9.0
414
				 *
415
				 * @param string $module Module slug.
416
				 * @param boolean $success whether the module was activated. @since 4.2
417
				 */
418
				do_action( 'jetpack_activate_module', $module, $success );
419
420
				/**
421
				 * Fires when a module is activated.
422
				 * The dynamic part of the filter, $module, is the module slug.
423
				 *
424
				 * @since 1.9.0
425
				 *
426
				 * @param string $module Module slug.
427
				 */
428
				do_action( "jetpack_activate_module_$module", $module );
429
			}
430
431
			$new_deactive_modules = array_diff( $current_modules, $modules );
432
			foreach( $new_deactive_modules as $module ) {
433
				/**
434
				 * Fired after a module has been deactivated.
435
				 *
436
				 * @since 4.2.0
437
				 *
438
				 * @param string $module Module slug.
439
				 * @param boolean $success whether the module was deactivated.
440
				 */
441
				do_action( 'jetpack_deactivate_module', $module, $success );
442
				/**
443
				 * Fires when a module is deactivated.
444
				 * The dynamic part of the filter, $module, is the module slug.
445
				 *
446
				 * @since 1.9.0
447
				 *
448
				 * @param string $module Module slug.
449
				 */
450
				do_action( "jetpack_deactivate_module_$module", $module );
451
			}
452
		}
453
454
		return $success;
455
	}
456
457
	static function delete_active_modules() {
458
		self::update_active_modules( array() );
459
	}
460
461
	/**
462
	 * Constructor.  Initializes WordPress hooks
463
	 */
464
	private function __construct() {
465
		/*
466
		 * Check for and alert any deprecated hooks
467
		 */
468
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
469
470
		/*
471
		 * Load things that should only be in Network Admin.
472
		 *
473
		 * For now blow away everything else until a more full
474
		 * understanding of what is needed at the network level is
475
		 * available
476
		 */
477
		if( is_multisite() ) {
478
			Jetpack_Network::init();
479
		}
480
481
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
482
483
		// Unlink user before deleting the user from .com
484
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
485
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
486
487
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
488
			@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...
489
490
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
491
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
492
493
			$this->require_jetpack_authentication();
494
495
			if ( Jetpack::is_active() ) {
496
				// Hack to preserve $HTTP_RAW_POST_DATA
497
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
498
499
				$signed = $this->verify_xml_rpc_signature();
500
				if ( $signed && ! is_wp_error( $signed ) ) {
501
					// The actual API methods.
502
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
503
				} else {
504
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
505
					// active Jetpack connection, so that additional users can link their account.
506
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
507
				}
508
			} else {
509
				// The bootstrap API methods.
510
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
511
			}
512
513
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
514
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
515
		} elseif (
516
			is_admin() &&
517
			isset( $_POST['action'] ) && (
518
				'jetpack_upload_file' == $_POST['action'] ||
519
				'jetpack_update_file' == $_POST['action']
520
			)
521
		) {
522
			$this->require_jetpack_authentication();
523
			$this->add_remote_request_handlers();
524
		} else {
525
			if ( Jetpack::is_active() ) {
526
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
527
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
528
			}
529
		}
530
531
		if ( Jetpack::is_active() ) {
532
			Jetpack_Heartbeat::init();
533
		}
534
535
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
536
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
537
538
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
539
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
540
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
541
		}
542
543
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
544
545
		add_action( 'admin_init', array( $this, 'admin_init' ) );
546
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
547
548
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
549
550
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
551
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
552
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
553
554
		// returns HTTPS support status
555
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
556
557
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
558
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
559
560
		// JITM AJAX callback function
561
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
562
563
		// Universal ajax callback for all tracking events triggered via js
564
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
565
566
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
567
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
568
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
569
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
570
571
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
572
573
		/**
574
		 * These actions run checks to load additional files.
575
		 * They check for external files or plugins, so they need to run as late as possible.
576
		 */
577
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
578
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
579
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
580
581
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
582
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
583
584
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
585
586
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
587
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
588
589
		// A filter to control all just in time messages
590
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
591
592
		// Update the Jetpack plan from API on heartbeats
593
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
594
595
		/**
596
		 * This is the hack to concatinate all css files into one.
597
		 * For description and reasoning see the implode_frontend_css method
598
		 *
599
		 * Super late priority so we catch all the registered styles
600
		 */
601
		if( !is_admin() ) {
602
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
603
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
604
		}
605
606
		/**
607
		 * These are sync actions that we need to keep track of for jitms
608
		 */
609
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
610
	}
611
612
	function jetpack_track_last_sync_callback( $params ) {
613
		if ( is_array( $params ) && isset( $params[0] ) ) {
614
			$option = $params[0];
615
			if ( 'active_plugins' === $option ) {
616
				// use the cache if we can, but not terribly important if it gets evicted
617
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
618
			}
619
		}
620
621
		return $params;
622
	}
623
624
	function jetpack_admin_ajax_tracks_callback() {
625
		// Check for nonce
626
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
627
			wp_die( 'Permissions check failed.' );
628
		}
629
630
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
631
			wp_die( 'No valid event name or type.' );
632
		}
633
634
		$tracks_data = array();
635
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
636
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
637
		}
638
639
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
640
		wp_send_json_success();
641
		wp_die();
642
	}
643
644
	/**
645
	 * The callback for the JITM ajax requests.
646
	 */
647
	function jetpack_jitm_ajax_callback() {
648
		// Check for nonce
649
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
650
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
651
		}
652
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
653
			$module_slug = $_REQUEST['jitmModule'];
654
			Jetpack::log( 'activate', $module_slug );
655
			Jetpack::activate_module( $module_slug, false, false );
656
			Jetpack::state( 'message', 'no_message' );
657
658
			//A Jetpack module is being activated through a JITM, track it
659
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
660
			$this->do_stats( 'server_side' );
661
662
			wp_send_json_success();
663
		}
664
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
665
			// get the hide_jitm options array
666
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
667
			$module_slug = $_REQUEST['jitmModule'];
668
669
			if( ! $jetpack_hide_jitm ) {
670
				$jetpack_hide_jitm = array(
671
					$module_slug => 'hide'
672
				);
673
			} else {
674
				$jetpack_hide_jitm[$module_slug] = 'hide';
675
			}
676
677
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
678
679
			//jitm is being dismissed forever, track it
680
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
681
			$this->do_stats( 'server_side' );
682
683
			wp_send_json_success();
684
		}
685 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
686
			$module_slug = $_REQUEST['jitmModule'];
687
688
			// User went to WordPress.com, track this
689
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
690
			$this->do_stats( 'server_side' );
691
692
			wp_send_json_success();
693
		}
694 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
695
			$track = $_REQUEST['jitmModule'];
696
697
			// User is viewing JITM, track it.
698
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
699
			$this->do_stats( 'server_side' );
700
701
			wp_send_json_success();
702
		}
703
	}
704
705
	/**
706
	 * If there are any stats that need to be pushed, but haven't been, push them now.
707
	 */
708
	function __destruct() {
709
		if ( ! empty( $this->stats ) ) {
710
			$this->do_stats( 'server_side' );
711
		}
712
	}
713
714
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
715
		switch( $cap ) {
716
			case 'jetpack_connect' :
717
			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...
718
				if ( Jetpack::is_development_mode() ) {
719
					$caps = array( 'do_not_allow' );
720
					break;
721
				}
722
				/**
723
				 * Pass through. If it's not development mode, these should match disconnect.
724
				 * Let users disconnect if it's development mode, just in case things glitch.
725
				 */
726
			case 'jetpack_disconnect' :
727
				/**
728
				 * In multisite, can individual site admins manage their own connection?
729
				 *
730
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
731
				 */
732
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
733
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
734
						/**
735
						 * We need to update the option name -- it's terribly unclear which
736
						 * direction the override goes.
737
						 *
738
						 * @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...
739
						 */
740
						$caps = array( 'do_not_allow' );
741
						break;
742
					}
743
				}
744
745
				$caps = array( 'manage_options' );
746
				break;
747
			case 'jetpack_manage_modules' :
748
			case 'jetpack_activate_modules' :
749
			case 'jetpack_deactivate_modules' :
750
				$caps = array( 'manage_options' );
751
				break;
752
			case 'jetpack_configure_modules' :
753
				$caps = array( 'manage_options' );
754
				break;
755
			case 'jetpack_network_admin_page':
756
			case 'jetpack_network_settings_page':
757
				$caps = array( 'manage_network_plugins' );
758
				break;
759
			case 'jetpack_network_sites_page':
760
				$caps = array( 'manage_sites' );
761
				break;
762
			case 'jetpack_admin_page' :
763
				if ( Jetpack::is_development_mode() ) {
764
					$caps = array( 'manage_options' );
765
					break;
766
				} else {
767
					$caps = array( 'read' );
768
				}
769
				break;
770
			case 'jetpack_connect_user' :
771
				if ( Jetpack::is_development_mode() ) {
772
					$caps = array( 'do_not_allow' );
773
					break;
774
				}
775
				$caps = array( 'read' );
776
				break;
777
		}
778
		return $caps;
779
	}
780
781
	function require_jetpack_authentication() {
782
		// Don't let anyone authenticate
783
		$_COOKIE = array();
784
		remove_all_filters( 'authenticate' );
785
		remove_all_actions( 'wp_login_failed' );
786
787
		if ( Jetpack::is_active() ) {
788
			// Allow Jetpack authentication
789
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
790
		}
791
	}
792
793
	/**
794
	 * Load language files
795
	 * @action plugins_loaded
796
	 */
797
	public static function plugin_textdomain() {
798
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
799
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
800
	}
801
802
	/**
803
	 * Register assets for use in various modules and the Jetpack admin page.
804
	 *
805
	 * @uses wp_script_is, wp_register_script, plugins_url
806
	 * @action wp_loaded
807
	 * @return null
808
	 */
809
	public function register_assets() {
810
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
811
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
812
		}
813
814 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
815
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
816
		}
817
818 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
819
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
820
		}
821
822 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
823
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
824
		}
825
826
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
827
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
828
829
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
830
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
831
			if ( ! is_numeric( $fb_app_id ) ) {
832
				$fb_app_id = '';
833
			}
834
			wp_localize_script(
835
				'jetpack-facebook-embed',
836
				'jpfbembed',
837
				array(
838
					'appid' => $fb_app_id,
839
					'locale' => $this->get_locale(),
840
				)
841
			);
842
		}
843
844
		/**
845
		 * As jetpack_register_genericons is by default fired off a hook,
846
		 * the hook may have already fired by this point.
847
		 * So, let's just trigger it manually.
848
		 */
849
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
850
		jetpack_register_genericons();
851
852
		/**
853
		 * Register the social logos
854
		 */
855
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
856
		jetpack_register_social_logos();
857
858 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
859
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
860
	}
861
862
	/**
863
	 * Guess locale from language code.
864
	 *
865
	 * @param string $lang Language code.
866
	 * @return string|bool
867
	 */
868 View Code Duplication
	function guess_locale_from_lang( $lang ) {
869
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
870
			return 'en_US';
871
		}
872
873
		if ( ! class_exists( 'GP_Locales' ) ) {
874
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
875
				return false;
876
			}
877
878
			require JETPACK__GLOTPRESS_LOCALES_PATH;
879
		}
880
881
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
882
			// WP.com: get_locale() returns 'it'
883
			$locale = GP_Locales::by_slug( $lang );
884
		} else {
885
			// Jetpack: get_locale() returns 'it_IT';
886
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
887
		}
888
889
		if ( ! $locale ) {
890
			return false;
891
		}
892
893
		if ( empty( $locale->facebook_locale ) ) {
894
			if ( empty( $locale->wp_locale ) ) {
895
				return false;
896
			} else {
897
				// Facebook SDK is smart enough to fall back to en_US if a
898
				// locale isn't supported. Since supported Facebook locales
899
				// can fall out of sync, we'll attempt to use the known
900
				// wp_locale value and rely on said fallback.
901
				return $locale->wp_locale;
902
			}
903
		}
904
905
		return $locale->facebook_locale;
906
	}
907
908
	/**
909
	 * Get the locale.
910
	 *
911
	 * @return string|bool
912
	 */
913
	function get_locale() {
914
		$locale = $this->guess_locale_from_lang( get_locale() );
915
916
		if ( ! $locale ) {
917
			$locale = 'en_US';
918
		}
919
920
		return $locale;
921
	}
922
923
	/**
924
	 * Device Pixels support
925
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
926
	 */
927
	function devicepx() {
928
		if ( Jetpack::is_active() ) {
929
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
930
		}
931
	}
932
933
	/**
934
	 * Return the network_site_url so that .com knows what network this site is a part of.
935
	 * @param  bool $option
936
	 * @return string
937
	 */
938
	public function jetpack_main_network_site_option( $option ) {
939
		return network_site_url();
940
	}
941
	/**
942
	 * Network Name.
943
	 */
944
	static function network_name( $option = null ) {
945
		global $current_site;
946
		return $current_site->site_name;
947
	}
948
	/**
949
	 * Does the network allow new user and site registrations.
950
	 * @return string
951
	 */
952
	static function network_allow_new_registrations( $option = null ) {
953
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
954
	}
955
	/**
956
	 * Does the network allow admins to add new users.
957
	 * @return boolian
958
	 */
959
	static function network_add_new_users( $option = null ) {
960
		return (bool) get_site_option( 'add_new_users' );
961
	}
962
	/**
963
	 * File upload psace left per site in MB.
964
	 *  -1 means NO LIMIT.
965
	 * @return number
966
	 */
967
	static function network_site_upload_space( $option = null ) {
968
		// value in MB
969
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
970
	}
971
972
	/**
973
	 * Network allowed file types.
974
	 * @return string
975
	 */
976
	static function network_upload_file_types( $option = null ) {
977
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
978
	}
979
980
	/**
981
	 * Maximum file upload size set by the network.
982
	 * @return number
983
	 */
984
	static function network_max_upload_file_size( $option = null ) {
985
		// value in KB
986
		return get_site_option( 'fileupload_maxk', 300 );
987
	}
988
989
	/**
990
	 * Lets us know if a site allows admins to manage the network.
991
	 * @return array
992
	 */
993
	static function network_enable_administration_menus( $option = null ) {
994
		return get_site_option( 'menu_items' );
995
	}
996
997
	/**
998
	 * If a user has been promoted to or demoted from admin, we need to clear the
999
	 * jetpack_other_linked_admins transient.
1000
	 *
1001
	 * @since 4.3.2
1002
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1003
	 *
1004
	 * @param int    $user_id   The user ID whose role changed.
1005
	 * @param string $role      The new role.
1006
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1007
	 */
1008
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1009
		if ( 'administrator' == $role
1010
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1011
			|| is_null( $old_roles )
1012
		) {
1013
			delete_transient( 'jetpack_other_linked_admins' );
1014
		}
1015
	}
1016
1017
	/**
1018
	 * Checks to see if there are any other users available to become primary
1019
	 * Users must both:
1020
	 * - Be linked to wpcom
1021
	 * - Be an admin
1022
	 *
1023
	 * @return mixed False if no other users are linked, Int if there are.
1024
	 */
1025
	static function get_other_linked_admins() {
1026
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1027
1028
		if ( false === $other_linked_users ) {
1029
			$admins = get_users( array( 'role' => 'administrator' ) );
1030
			if ( count( $admins ) > 1 ) {
1031
				$available = array();
1032
				foreach ( $admins as $admin ) {
1033
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1034
						$available[] = $admin->ID;
1035
					}
1036
				}
1037
1038
				$count_connected_admins = count( $available );
1039
				if ( count( $available ) > 1 ) {
1040
					$other_linked_users = $count_connected_admins;
1041
				} else {
1042
					$other_linked_users = 0;
1043
				}
1044
			} else {
1045
				$other_linked_users = 0;
1046
			}
1047
1048
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1049
		}
1050
1051
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1052
	}
1053
1054
	/**
1055
	 * Return whether we are dealing with a multi network setup or not.
1056
	 * The reason we are type casting this is because we want to avoid the situation where
1057
	 * the result is false since when is_main_network_option return false it cases
1058
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1059
	 * database which could be set to anything as opposed to what this function returns.
1060
	 * @param  bool  $option
1061
	 *
1062
	 * @return boolean
1063
	 */
1064
	public function is_main_network_option( $option ) {
1065
		// return '1' or ''
1066
		return (string) (bool) Jetpack::is_multi_network();
1067
	}
1068
1069
	/**
1070
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1071
	 *
1072
	 * @param  string  $option
1073
	 * @return boolean
1074
	 */
1075
	public function is_multisite( $option ) {
1076
		return (string) (bool) is_multisite();
1077
	}
1078
1079
	/**
1080
	 * Implemented since there is no core is multi network function
1081
	 * Right now there is no way to tell if we which network is the dominant network on the system
1082
	 *
1083
	 * @since  3.3
1084
	 * @return boolean
1085
	 */
1086
	public static function is_multi_network() {
1087
		global  $wpdb;
1088
1089
		// if we don't have a multi site setup no need to do any more
1090
		if ( ! is_multisite() ) {
1091
			return false;
1092
		}
1093
1094
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1095
		if ( $num_sites > 1 ) {
1096
			return true;
1097
		} else {
1098
			return false;
1099
		}
1100
	}
1101
1102
	/**
1103
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1104
	 * @return null
1105
	 */
1106
	function update_jetpack_main_network_site_option() {
1107
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1108
	}
1109
	/**
1110
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1111
	 *
1112
	 */
1113
	function update_jetpack_network_settings() {
1114
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1115
		// Only sync this info for the main network site.
1116
	}
1117
1118
	/**
1119
	 * Get back if the current site is single user site.
1120
	 *
1121
	 * @return bool
1122
	 */
1123
	public static function is_single_user_site() {
1124
		global $wpdb;
1125
1126 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1127
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1128
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1129
		}
1130
		return 1 === (int) $some_users;
1131
	}
1132
1133
	/**
1134
	 * Returns true if the site has file write access false otherwise.
1135
	 * @return string ( '1' | '0' )
1136
	 **/
1137
	public static function file_system_write_access() {
1138
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1139
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1140
		}
1141
1142
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1143
1144
		$filesystem_method = get_filesystem_method();
1145
		if ( $filesystem_method === 'direct' ) {
1146
			return 1;
1147
		}
1148
1149
		ob_start();
1150
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1151
		ob_end_clean();
1152
		if ( $filesystem_credentials_are_stored ) {
1153
			return 1;
1154
		}
1155
		return 0;
1156
	}
1157
1158
	/**
1159
	 * Finds out if a site is using a version control system.
1160
	 * @return string ( '1' | '0' )
1161
	 **/
1162
	public static function is_version_controlled() {
1163
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1164
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1165
	}
1166
1167
	/**
1168
	 * Determines whether the current theme supports featured images or not.
1169
	 * @return string ( '1' | '0' )
1170
	 */
1171
	public static function featured_images_enabled() {
1172
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1173
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1174
	}
1175
1176
	/**
1177
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1178
	 *
1179
	 * @deprecated 4.7 use get_avatar_url instead.
1180
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1181
	 * @param int $size Size of the avatar image
1182
	 * @param string $default URL to a default image to use if no avatar is available
1183
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1184
	 *
1185
	 * @return array
1186
	 */
1187
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1188
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1189
		return get_avatar_url( $id_or_email, array(
1190
			'size' => $size,
1191
			'default' => $default,
1192
			'force_default' => $force_display,
1193
		) );
1194
	}
1195
1196
	/**
1197
	 * jetpack_updates is saved in the following schema:
1198
	 *
1199
	 * array (
1200
	 *      'plugins'                       => (int) Number of plugin updates available.
1201
	 *      'themes'                        => (int) Number of theme updates available.
1202
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1203
	 *      'translations'                  => (int) Number of translation updates available.
1204
	 *      'total'                         => (int) Total of all available updates.
1205
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1206
	 * )
1207
	 * @return array
1208
	 */
1209
	public static function get_updates() {
1210
		$update_data = wp_get_update_data();
1211
1212
		// Stores the individual update counts as well as the total count.
1213
		if ( isset( $update_data['counts'] ) ) {
1214
			$updates = $update_data['counts'];
1215
		}
1216
1217
		// If we need to update WordPress core, let's find the latest version number.
1218 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1219
			$cur = get_preferred_from_update_core();
1220
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1221
				$updates['wp_update_version'] = $cur->current;
1222
			}
1223
		}
1224
		return isset( $updates ) ? $updates : array();
1225
	}
1226
1227
	public static function get_update_details() {
1228
		$update_details = array(
1229
			'update_core' => get_site_transient( 'update_core' ),
1230
			'update_plugins' => get_site_transient( 'update_plugins' ),
1231
			'update_themes' => get_site_transient( 'update_themes' ),
1232
		);
1233
		return $update_details;
1234
	}
1235
1236
	public static function refresh_update_data() {
1237
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1238
1239
	}
1240
1241
	public static function refresh_theme_data() {
1242
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1243
	}
1244
1245
	/**
1246
	 * Is Jetpack active?
1247
	 */
1248
	public static function is_active() {
1249
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1250
	}
1251
1252
	/**
1253
	 * Make an API call to WordPress.com for plan status
1254
	 *
1255
	 * @uses Jetpack_Options::get_option()
1256
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1257
	 * @uses update_option()
1258
	 *
1259
	 * @access public
1260
	 * @static
1261
	 *
1262
	 * @return bool True if plan is updated, false if no update
1263
	 */
1264
	public static function refresh_active_plan_from_wpcom() {
1265
		// Make the API request
1266
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1267
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1268
1269
		// Bail if there was an error or malformed response
1270
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1271
			return false;
1272
		}
1273
1274
		// Decode the results
1275
		$results = json_decode( $response['body'], true );
1276
1277
		// Bail if there were no results or plan details returned
1278
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1279
			return false;
1280
		}
1281
1282
		// Store the option and return true if updated
1283
		return update_option( 'jetpack_active_plan', $results['plan'] );
1284
	}
1285
1286
	/**
1287
	 * Get the plan that this Jetpack site is currently using
1288
	 *
1289
	 * @uses get_option()
1290
	 *
1291
	 * @access public
1292
	 * @static
1293
	 *
1294
	 * @return array Active Jetpack plan details
1295
	 */
1296
	public static function get_active_plan() {
1297
		$plan = get_option( 'jetpack_active_plan', array() );
1298
1299
		// Set the default options
1300
		if ( empty( $plan ) || ( isset( $plan['product_slug'] ) && 'jetpack_free' === $plan['product_slug'] ) ) {
1301
			$plan = wp_parse_args( $plan, array(
1302
				'product_slug' => 'jetpack_free',
1303
				'supports'     => array(),
1304
				'class'        => 'free',
1305
			) );
1306
		}
1307
1308
		// Define what paid modules are supported by personal plans
1309
		$personal_plans = array(
1310
			'jetpack_personal',
1311
			'jetpack_personal_monthly',
1312
			'personal-bundle',
1313
		);
1314
1315
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1316
			$plan['supports'] = array(
1317
				'akismet',
1318
			);
1319
			$plan['class'] = 'personal';
1320
		}
1321
1322
		// Define what paid modules are supported by premium plans
1323
		$premium_plans = array(
1324
			'jetpack_premium',
1325
			'jetpack_premium_monthly',
1326
			'value_bundle',
1327
		);
1328
1329 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1330
			$plan['supports'] = array(
1331
				'videopress',
1332
				'akismet',
1333
				'vaultpress',
1334
				'wordads',
1335
			);
1336
			$plan['class'] = 'premium';
1337
		}
1338
1339
		// Define what paid modules are supported by professional plans
1340
		$business_plans = array(
1341
			'jetpack_business',
1342
			'jetpack_business_monthly',
1343
			'business-bundle',
1344
		);
1345
1346 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1347
			$plan['supports'] = array(
1348
				'videopress',
1349
				'akismet',
1350
				'vaultpress',
1351
				'seo-tools',
1352
				'google-analytics',
1353
				'wordads',
1354
			);
1355
			$plan['class'] = 'business';
1356
		}
1357
1358
		// Make sure we have an array here in the event database data is stale
1359
		if ( ! isset( $plan['supports'] ) ) {
1360
			$plan['supports'] = array();
1361
		}
1362
1363
		return $plan;
1364
	}
1365
1366
	/**
1367
	 * Determine whether the active plan supports a particular feature
1368
	 *
1369
	 * @uses Jetpack::get_active_plan()
1370
	 *
1371
	 * @access public
1372
	 * @static
1373
	 *
1374
	 * @return bool True if plan supports feature, false if not
1375
	 */
1376
	public static function active_plan_supports( $feature ) {
1377
		$plan = Jetpack::get_active_plan();
1378
1379
		if ( in_array( $feature, $plan['supports'] ) ) {
1380
			return true;
1381
		}
1382
1383
		return false;
1384
	}
1385
1386
	/**
1387
	 * Is Jetpack in development (offline) mode?
1388
	 */
1389
	public static function is_development_mode() {
1390
		$development_mode = false;
1391
1392
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1393
			$development_mode = JETPACK_DEV_DEBUG;
1394
		} elseif ( $site_url = site_url() ) {
1395
			$development_mode = false === strpos( $site_url, '.' );
1396
		}
1397
1398
		/**
1399
		 * Filters Jetpack's development mode.
1400
		 *
1401
		 * @see https://jetpack.com/support/development-mode/
1402
		 *
1403
		 * @since 2.2.1
1404
		 *
1405
		 * @param bool $development_mode Is Jetpack's development mode active.
1406
		 */
1407
		return apply_filters( 'jetpack_development_mode', $development_mode );
1408
	}
1409
1410
	/**
1411
	* Get Jetpack development mode notice text and notice class.
1412
	*
1413
	* Mirrors the checks made in Jetpack::is_development_mode
1414
	*
1415
	*/
1416
	public static function show_development_mode_notice() {
1417
		if ( Jetpack::is_development_mode() ) {
1418
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1419
				$notice = sprintf(
1420
					/* translators: %s is a URL */
1421
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1422
					'https://jetpack.com/support/development-mode/'
1423
				);
1424
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1425
				$notice = sprintf(
1426
					/* translators: %s is a URL */
1427
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1428
					'https://jetpack.com/support/development-mode/'
1429
				);
1430
			} else {
1431
				$notice = sprintf(
1432
					/* translators: %s is a URL */
1433
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1434
					'https://jetpack.com/support/development-mode/'
1435
				);
1436
			}
1437
1438
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1439
		}
1440
1441
		// Throw up a notice if using a development version and as for feedback.
1442
		if ( Jetpack::is_development_version() ) {
1443
			/* translators: %s is a URL */
1444
			$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/' );
1445
1446
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1447
		}
1448
		// Throw up a notice if using staging mode
1449
		if ( Jetpack::is_staging_site() ) {
1450
			/* translators: %s is a URL */
1451
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1452
1453
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1454
		}
1455
	}
1456
1457
	/**
1458
	 * Whether Jetpack's version maps to a public release, or a development version.
1459
	 */
1460
	public static function is_development_version() {
1461
		/**
1462
		 * Allows filtering whether this is a development version of Jetpack.
1463
		 *
1464
		 * This filter is especially useful for tests.
1465
		 *
1466
		 * @since 4.3.0
1467
		 *
1468
		 * @param bool $development_version Is this a develoment version of Jetpack?
1469
		 */
1470
		return (bool) apply_filters(
1471
			'jetpack_development_version',
1472
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1473
		);
1474
	}
1475
1476
	/**
1477
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1478
	 */
1479
	public static function is_user_connected( $user_id = false ) {
1480
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1481
		if ( ! $user_id ) {
1482
			return false;
1483
		}
1484
1485
		return (bool) Jetpack_Data::get_access_token( $user_id );
1486
	}
1487
1488
	/**
1489
	 * Get the wpcom user data of the current|specified connected user.
1490
	 */
1491
	public static function get_connected_user_data( $user_id = null ) {
1492
		if ( ! $user_id ) {
1493
			$user_id = get_current_user_id();
1494
		}
1495
1496
		$transient_key = "jetpack_connected_user_data_$user_id";
1497
1498
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1499
			return $cached_user_data;
1500
		}
1501
1502
		Jetpack::load_xml_rpc_client();
1503
		$xml = new Jetpack_IXR_Client( array(
1504
			'user_id' => $user_id,
1505
		) );
1506
		$xml->query( 'wpcom.getUser' );
1507
		if ( ! $xml->isError() ) {
1508
			$user_data = $xml->getResponse();
1509
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1510
			return $user_data;
1511
		}
1512
1513
		return false;
1514
	}
1515
1516
	/**
1517
	 * Get the wpcom email of the current|specified connected user.
1518
	 */
1519 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1520
		if ( ! $user_id ) {
1521
			$user_id = get_current_user_id();
1522
		}
1523
		Jetpack::load_xml_rpc_client();
1524
		$xml = new Jetpack_IXR_Client( array(
1525
			'user_id' => $user_id,
1526
		) );
1527
		$xml->query( 'wpcom.getUserEmail' );
1528
		if ( ! $xml->isError() ) {
1529
			return $xml->getResponse();
1530
		}
1531
		return false;
1532
	}
1533
1534
	/**
1535
	 * Get the wpcom email of the master user.
1536
	 */
1537
	public static function get_master_user_email() {
1538
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1539
		if ( $master_user_id ) {
1540
			return self::get_connected_user_email( $master_user_id );
1541
		}
1542
		return '';
1543
	}
1544
1545
	function current_user_is_connection_owner() {
1546
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1547
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1548
	}
1549
1550
	/**
1551
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1552
	 */
1553
	function extra_oembed_providers() {
1554
		// Cloudup: https://dev.cloudup.com/#oembed
1555
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1556
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1557
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1558
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1559
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1560
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1561
	}
1562
1563
	/**
1564
	 * Synchronize connected user role changes
1565
	 */
1566
	function user_role_change( $user_id ) {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1568
		Jetpack_Sync_Users::user_role_change( $user_id );
1569
	}
1570
1571
	/**
1572
	 * Loads the currently active modules.
1573
	 */
1574
	public static function load_modules() {
1575
		if ( ! self::is_active() && !self::is_development_mode() ) {
1576
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1577
				return;
1578
			}
1579
		}
1580
1581
		$version = Jetpack_Options::get_option( 'version' );
1582 View Code Duplication
		if ( ! $version ) {
1583
			$version = $old_version = JETPACK__VERSION . ':' . time();
1584
			/** This action is documented in class.jetpack.php */
1585
			do_action( 'updating_jetpack_version', $version, false );
1586
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1587
		}
1588
		list( $version ) = explode( ':', $version );
1589
1590
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1591
1592
		$modules_data = array();
1593
1594
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1595
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1596
			$updated_modules = array();
1597
			foreach ( $modules as $module ) {
1598
				$modules_data[ $module ] = Jetpack::get_module( $module );
1599
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1600
					continue;
1601
				}
1602
1603
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1604
					continue;
1605
				}
1606
1607
				$updated_modules[] = $module;
1608
			}
1609
1610
			$modules = array_diff( $modules, $updated_modules );
1611
		}
1612
1613
		$is_development_mode = Jetpack::is_development_mode();
1614
1615
		foreach ( $modules as $index => $module ) {
1616
			// If we're in dev mode, disable modules requiring a connection
1617
			if ( $is_development_mode ) {
1618
				// Prime the pump if we need to
1619
				if ( empty( $modules_data[ $module ] ) ) {
1620
					$modules_data[ $module ] = Jetpack::get_module( $module );
1621
				}
1622
				// If the module requires a connection, but we're in local mode, don't include it.
1623
				if ( $modules_data[ $module ]['requires_connection'] ) {
1624
					continue;
1625
				}
1626
			}
1627
1628
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1629
				continue;
1630
			}
1631
1632
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1633
				unset( $modules[ $index ] );
1634
				self::update_active_modules( array_values( $modules ) );
1635
				continue;
1636
			}
1637
1638
			/**
1639
			 * Fires when a specific module is loaded.
1640
			 * The dynamic part of the hook, $module, is the module slug.
1641
			 *
1642
			 * @since 1.1.0
1643
			 */
1644
			do_action( 'jetpack_module_loaded_' . $module );
1645
		}
1646
1647
		/**
1648
		 * Fires when all the modules are loaded.
1649
		 *
1650
		 * @since 1.1.0
1651
		 */
1652
		do_action( 'jetpack_modules_loaded' );
1653
1654
		// 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.
1655
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1656
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1657
	}
1658
1659
	/**
1660
	 * Check if Jetpack's REST API compat file should be included
1661
	 * @action plugins_loaded
1662
	 * @return null
1663
	 */
1664
	public function check_rest_api_compat() {
1665
		/**
1666
		 * Filters the list of REST API compat files to be included.
1667
		 *
1668
		 * @since 2.2.5
1669
		 *
1670
		 * @param array $args Array of REST API compat files to include.
1671
		 */
1672
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1673
1674
		if ( function_exists( 'bbpress' ) )
1675
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1676
1677
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1678
			require_once $_jetpack_rest_api_compat_include;
1679
	}
1680
1681
	/**
1682
	 * Gets all plugins currently active in values, regardless of whether they're
1683
	 * traditionally activated or network activated.
1684
	 *
1685
	 * @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...
1686
	 */
1687
	public static function get_active_plugins() {
1688
		$active_plugins = (array) get_option( 'active_plugins', array() );
1689
1690
		if ( is_multisite() ) {
1691
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1692
			// whereas active_plugins stores them in the values.
1693
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1694
			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...
1695
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1696
			}
1697
		}
1698
1699
		sort( $active_plugins );
1700
1701
		return array_unique( $active_plugins );
1702
	}
1703
1704
	/**
1705
	 * Gets and parses additional plugin data to send with the heartbeat data
1706
	 *
1707
	 * @since 3.8.1
1708
	 *
1709
	 * @return array Array of plugin data
1710
	 */
1711
	public static function get_parsed_plugin_data() {
1712
		if ( ! function_exists( 'get_plugins' ) ) {
1713
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1714
		}
1715
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1716
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1717
		$active_plugins = Jetpack::get_active_plugins();
1718
1719
		$plugins = array();
1720
		foreach ( $all_plugins as $path => $plugin_data ) {
1721
			$plugins[ $path ] = array(
1722
					'is_active' => in_array( $path, $active_plugins ),
1723
					'file'      => $path,
1724
					'name'      => $plugin_data['Name'],
1725
					'version'   => $plugin_data['Version'],
1726
					'author'    => $plugin_data['Author'],
1727
			);
1728
		}
1729
1730
		return $plugins;
1731
	}
1732
1733
	/**
1734
	 * Gets and parses theme data to send with the heartbeat data
1735
	 *
1736
	 * @since 3.8.1
1737
	 *
1738
	 * @return array Array of theme data
1739
	 */
1740
	public static function get_parsed_theme_data() {
1741
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1742
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1743
1744
		$themes = array();
1745
		foreach ( $all_themes as $slug => $theme_data ) {
1746
			$theme_headers = array();
1747
			foreach ( $header_keys as $header_key ) {
1748
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1749
			}
1750
1751
			$themes[ $slug ] = array(
1752
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1753
					'slug' => $slug,
1754
					'theme_root' => $theme_data->get_theme_root_uri(),
1755
					'parent' => $theme_data->parent(),
1756
					'headers' => $theme_headers
1757
			);
1758
		}
1759
1760
		return $themes;
1761
	}
1762
1763
	/**
1764
	 * Checks whether a specific plugin is active.
1765
	 *
1766
	 * We don't want to store these in a static variable, in case
1767
	 * there are switch_to_blog() calls involved.
1768
	 */
1769
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1770
		return in_array( $plugin, self::get_active_plugins() );
1771
	}
1772
1773
	/**
1774
	 * Check if Jetpack's Open Graph tags should be used.
1775
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1776
	 *
1777
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1778
	 * @action plugins_loaded
1779
	 * @return null
1780
	 */
1781
	public function check_open_graph() {
1782
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1783
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1784
		}
1785
1786
		$active_plugins = self::get_active_plugins();
1787
1788
		if ( ! empty( $active_plugins ) ) {
1789
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1790
				if ( in_array( $plugin, $active_plugins ) ) {
1791
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1792
					break;
1793
				}
1794
			}
1795
		}
1796
1797
		/**
1798
		 * Allow the addition of Open Graph Meta Tags to all pages.
1799
		 *
1800
		 * @since 2.0.3
1801
		 *
1802
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1803
		 */
1804
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1805
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1806
		}
1807
	}
1808
1809
	/**
1810
	 * Check if Jetpack's Twitter tags should be used.
1811
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1812
	 *
1813
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1814
	 * @action plugins_loaded
1815
	 * @return null
1816
	 */
1817
	public function check_twitter_tags() {
1818
1819
		$active_plugins = self::get_active_plugins();
1820
1821
		if ( ! empty( $active_plugins ) ) {
1822
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1823
				if ( in_array( $plugin, $active_plugins ) ) {
1824
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1825
					break;
1826
				}
1827
			}
1828
		}
1829
1830
		/**
1831
		 * Allow Twitter Card Meta tags to be disabled.
1832
		 *
1833
		 * @since 2.6.0
1834
		 *
1835
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1836
		 */
1837
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1838
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1839
		}
1840
	}
1841
1842
	/**
1843
	 * Allows plugins to submit security reports.
1844
 	 *
1845
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1846
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1847
	 * @param array   $args         See definitions above
1848
	 */
1849
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1850
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1851
	}
1852
1853
/* Jetpack Options API */
1854
1855
	public static function get_option_names( $type = 'compact' ) {
1856
		return Jetpack_Options::get_option_names( $type );
1857
	}
1858
1859
	/**
1860
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1861
 	 *
1862
	 * @param string $name    Option name
1863
	 * @param mixed  $default (optional)
1864
	 */
1865
	public static function get_option( $name, $default = false ) {
1866
		return Jetpack_Options::get_option( $name, $default );
1867
	}
1868
1869
	/**
1870
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1871
 	 *
1872
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1873
	 * @param string $name  Option name
1874
	 * @param mixed  $value Option value
1875
	 */
1876
	public static function update_option( $name, $value ) {
1877
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1878
		return Jetpack_Options::update_option( $name, $value );
1879
	}
1880
1881
	/**
1882
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1883
 	 *
1884
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1885
	 * @param array $array array( option name => option value, ... )
1886
	 */
1887
	public static function update_options( $array ) {
1888
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1889
		return Jetpack_Options::update_options( $array );
1890
	}
1891
1892
	/**
1893
	 * Deletes the given option.  May be passed multiple option names as an array.
1894
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1895
	 *
1896
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1897
	 * @param string|array $names
1898
	 */
1899
	public static function delete_option( $names ) {
1900
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1901
		return Jetpack_Options::delete_option( $names );
1902
	}
1903
1904
	/**
1905
	 * Enters a user token into the user_tokens option
1906
	 *
1907
	 * @param int $user_id
1908
	 * @param string $token
1909
	 * return bool
1910
	 */
1911
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1912
		// not designed for concurrent updates
1913
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1914
		if ( ! is_array( $user_tokens ) )
1915
			$user_tokens = array();
1916
		$user_tokens[$user_id] = $token;
1917
		if ( $is_master_user ) {
1918
			$master_user = $user_id;
1919
			$options     = compact( 'user_tokens', 'master_user' );
1920
		} else {
1921
			$options = compact( 'user_tokens' );
1922
		}
1923
		return Jetpack_Options::update_options( $options );
1924
	}
1925
1926
	/**
1927
	 * Returns an array of all PHP files in the specified absolute path.
1928
	 * Equivalent to glob( "$absolute_path/*.php" ).
1929
	 *
1930
	 * @param string $absolute_path The absolute path of the directory to search.
1931
	 * @return array Array of absolute paths to the PHP files.
1932
	 */
1933
	public static function glob_php( $absolute_path ) {
1934
		if ( function_exists( 'glob' ) ) {
1935
			return glob( "$absolute_path/*.php" );
1936
		}
1937
1938
		$absolute_path = untrailingslashit( $absolute_path );
1939
		$files = array();
1940
		if ( ! $dir = @opendir( $absolute_path ) ) {
1941
			return $files;
1942
		}
1943
1944
		while ( false !== $file = readdir( $dir ) ) {
1945
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1946
				continue;
1947
			}
1948
1949
			$file = "$absolute_path/$file";
1950
1951
			if ( ! is_file( $file ) ) {
1952
				continue;
1953
			}
1954
1955
			$files[] = $file;
1956
		}
1957
1958
		closedir( $dir );
1959
1960
		return $files;
1961
	}
1962
1963
	public static function activate_new_modules( $redirect = false ) {
1964
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1965
			return;
1966
		}
1967
1968
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1969 View Code Duplication
		if ( ! $jetpack_old_version ) {
1970
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1971
			/** This action is documented in class.jetpack.php */
1972
			do_action( 'updating_jetpack_version', $version, false );
1973
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1974
		}
1975
1976
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1977
1978
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1979
			return;
1980
		}
1981
1982
		$active_modules     = Jetpack::get_active_modules();
1983
		$reactivate_modules = array();
1984
		foreach ( $active_modules as $active_module ) {
1985
			$module = Jetpack::get_module( $active_module );
1986
			if ( ! isset( $module['changed'] ) ) {
1987
				continue;
1988
			}
1989
1990
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1991
				continue;
1992
			}
1993
1994
			$reactivate_modules[] = $active_module;
1995
			Jetpack::deactivate_module( $active_module );
1996
		}
1997
1998
		$new_version = JETPACK__VERSION . ':' . time();
1999
		/** This action is documented in class.jetpack.php */
2000
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2001
		Jetpack_Options::update_options(
2002
			array(
2003
				'version'     => $new_version,
2004
				'old_version' => $jetpack_old_version,
2005
			)
2006
		);
2007
2008
		Jetpack::state( 'message', 'modules_activated' );
2009
		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...
2010
2011
		if ( $redirect ) {
2012
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2013
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2014
				$page = $_GET['page'];
2015
			}
2016
2017
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2018
			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...
2019
		}
2020
	}
2021
2022
	/**
2023
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2024
	 * Make sure to tuck away module "library" files in a sub-directory.
2025
	 */
2026
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2027
		static $modules = null;
2028
2029
		if ( ! isset( $modules ) ) {
2030
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2031
			// Use the cache if we're on the front-end and it's available...
2032
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2033
				$modules = $available_modules_option[ JETPACK__VERSION ];
2034
			} else {
2035
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2036
2037
				$modules = array();
2038
2039
				foreach ( $files as $file ) {
2040
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2041
						continue;
2042
					}
2043
2044
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2045
				}
2046
2047
				Jetpack_Options::update_option( 'available_modules', array(
2048
					JETPACK__VERSION => $modules,
2049
				) );
2050
			}
2051
		}
2052
2053
		/**
2054
		 * Filters the array of modules available to be activated.
2055
		 *
2056
		 * @since 2.4.0
2057
		 *
2058
		 * @param array $modules Array of available modules.
2059
		 * @param string $min_version Minimum version number required to use modules.
2060
		 * @param string $max_version Maximum version number required to use modules.
2061
		 */
2062
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2063
2064
		if ( ! $min_version && ! $max_version ) {
2065
			return array_keys( $mods );
2066
		}
2067
2068
		$r = array();
2069
		foreach ( $mods as $slug => $introduced ) {
2070
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2071
				continue;
2072
			}
2073
2074
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2075
				continue;
2076
			}
2077
2078
			$r[] = $slug;
2079
		}
2080
2081
		return $r;
2082
	}
2083
2084
	/**
2085
	 * Default modules loaded on activation.
2086
	 */
2087
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2088
		$return = array();
2089
2090
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2091
			$module_data = Jetpack::get_module( $module );
2092
2093
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2094
				case 'yes' :
2095
					$return[] = $module;
2096
					break;
2097
				case 'public' :
2098
					if ( Jetpack_Options::get_option( 'public' ) ) {
2099
						$return[] = $module;
2100
					}
2101
					break;
2102
				case 'no' :
2103
				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...
2104
					break;
2105
			}
2106
		}
2107
		/**
2108
		 * Filters the array of default modules.
2109
		 *
2110
		 * @since 2.5.0
2111
		 *
2112
		 * @param array $return Array of default modules.
2113
		 * @param string $min_version Minimum version number required to use modules.
2114
		 * @param string $max_version Maximum version number required to use modules.
2115
		 */
2116
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2117
	}
2118
2119
	/**
2120
	 * Checks activated modules during auto-activation to determine
2121
	 * if any of those modules are being deprecated.  If so, close
2122
	 * them out, and add any replacement modules.
2123
	 *
2124
	 * Runs at priority 99 by default.
2125
	 *
2126
	 * This is run late, so that it can still activate a module if
2127
	 * the new module is a replacement for another that the user
2128
	 * currently has active, even if something at the normal priority
2129
	 * would kibosh everything.
2130
	 *
2131
	 * @since 2.6
2132
	 * @uses jetpack_get_default_modules filter
2133
	 * @param array $modules
2134
	 * @return array
2135
	 */
2136
	function handle_deprecated_modules( $modules ) {
2137
		$deprecated_modules = array(
2138
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2139
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2140
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2141
		);
2142
2143
		// Don't activate SSO if they never completed activating WPCC.
2144
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2145
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2146
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2147
				$deprecated_modules['wpcc'] = null;
2148
			}
2149
		}
2150
2151
		foreach ( $deprecated_modules as $module => $replacement ) {
2152
			if ( Jetpack::is_module_active( $module ) ) {
2153
				self::deactivate_module( $module );
2154
				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...
2155
					$modules[] = $replacement;
2156
				}
2157
			}
2158
		}
2159
2160
		return array_unique( $modules );
2161
	}
2162
2163
	/**
2164
	 * Checks activated plugins during auto-activation to determine
2165
	 * if any of those plugins are in the list with a corresponding module
2166
	 * that is not compatible with the plugin. The module will not be allowed
2167
	 * to auto-activate.
2168
	 *
2169
	 * @since 2.6
2170
	 * @uses jetpack_get_default_modules filter
2171
	 * @param array $modules
2172
	 * @return array
2173
	 */
2174
	function filter_default_modules( $modules ) {
2175
2176
		$active_plugins = self::get_active_plugins();
2177
2178
		if ( ! empty( $active_plugins ) ) {
2179
2180
			// For each module we'd like to auto-activate...
2181
			foreach ( $modules as $key => $module ) {
2182
				// If there are potential conflicts for it...
2183
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2184
					// For each potential conflict...
2185
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2186
						// If that conflicting plugin is active...
2187
						if ( in_array( $plugin, $active_plugins ) ) {
2188
							// Remove that item from being auto-activated.
2189
							unset( $modules[ $key ] );
2190
						}
2191
					}
2192
				}
2193
			}
2194
		}
2195
2196
		return $modules;
2197
	}
2198
2199
	/**
2200
	 * Extract a module's slug from its full path.
2201
	 */
2202
	public static function get_module_slug( $file ) {
2203
		return str_replace( '.php', '', basename( $file ) );
2204
	}
2205
2206
	/**
2207
	 * Generate a module's path from its slug.
2208
	 */
2209
	public static function get_module_path( $slug ) {
2210
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2211
	}
2212
2213
	/**
2214
	 * Load module data from module file. Headers differ from WordPress
2215
	 * plugin headers to avoid them being identified as standalone
2216
	 * plugins on the WordPress plugins page.
2217
	 */
2218
	public static function get_module( $module ) {
2219
		$headers = array(
2220
			'name'                      => 'Module Name',
2221
			'description'               => 'Module Description',
2222
			'jumpstart_desc'            => 'Jumpstart Description',
2223
			'sort'                      => 'Sort Order',
2224
			'recommendation_order'      => 'Recommendation Order',
2225
			'introduced'                => 'First Introduced',
2226
			'changed'                   => 'Major Changes In',
2227
			'deactivate'                => 'Deactivate',
2228
			'free'                      => 'Free',
2229
			'requires_connection'       => 'Requires Connection',
2230
			'auto_activate'             => 'Auto Activate',
2231
			'module_tags'               => 'Module Tags',
2232
			'feature'                   => 'Feature',
2233
			'additional_search_queries' => 'Additional Search Queries',
2234
		);
2235
2236
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2237
2238
		$mod = Jetpack::get_file_data( $file, $headers );
2239
		if ( empty( $mod['name'] ) ) {
2240
			return false;
2241
		}
2242
2243
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2244
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2245
		$mod['deactivate']              = empty( $mod['deactivate'] );
2246
		$mod['free']                    = empty( $mod['free'] );
2247
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2248
2249
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2250
			$mod['auto_activate'] = 'No';
2251
		} else {
2252
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2253
		}
2254
2255
		if ( $mod['module_tags'] ) {
2256
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2257
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2258
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2259
		} else {
2260
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2261
		}
2262
2263
		if ( $mod['feature'] ) {
2264
			$mod['feature'] = explode( ',', $mod['feature'] );
2265
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2266
		} else {
2267
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2268
		}
2269
2270
		/**
2271
		 * Filters the feature array on a module.
2272
		 *
2273
		 * This filter allows you to control where each module is filtered: Recommended,
2274
		 * Jumpstart, and the default "Other" listing.
2275
		 *
2276
		 * @since 3.5.0
2277
		 *
2278
		 * @param array   $mod['feature'] The areas to feature this module:
2279
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2280
		 *     'Recommended' shows on the main Jetpack admin screen.
2281
		 *     'Other' should be the default if no other value is in the array.
2282
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2283
		 * @param array   $mod All the currently assembled module data.
2284
		 */
2285
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2286
2287
		/**
2288
		 * Filter the returned data about a module.
2289
		 *
2290
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2291
		 * so please be careful.
2292
		 *
2293
		 * @since 3.6.0
2294
		 *
2295
		 * @param array   $mod    The details of the requested module.
2296
		 * @param string  $module The slug of the module, e.g. sharedaddy
2297
		 * @param string  $file   The path to the module source file.
2298
		 */
2299
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2300
	}
2301
2302
	/**
2303
	 * Like core's get_file_data implementation, but caches the result.
2304
	 */
2305
	public static function get_file_data( $file, $headers ) {
2306
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2307
		$file_name = basename( $file );
2308
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2309
		$key              = md5( $file_name . serialize( $headers ) );
2310
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2311
2312
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2313
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2314
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2315
		}
2316
2317
		$data = get_file_data( $file, $headers );
2318
2319
		// Strip out any old Jetpack versions that are cluttering the option.
2320
		//
2321
		// We maintain the data for the current version of Jetpack plus the previous version
2322
		// to prevent repeated DB hits on large sites hosted with multiple web servers
2323
		// on a single database (since all web servers might not be updated simultaneously)
2324
2325
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2326
2327
		if ( count( $file_data_option ) > 2 ) {
2328
			$count = 0;
2329
			krsort( $file_data_option );
2330
			foreach ( $file_data_option as $version => $values ) {
2331
				$count++;
2332
				if ( $count > 2 && JETPACK__VERSION != $version ) {
2333
					unset( $file_data_option[ $version ] );
2334
				}
2335
			}
2336
		}
2337
2338
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2339
2340
		return $data;
2341
	}
2342
2343
2344
	/**
2345
	 * Return translated module tag.
2346
	 *
2347
	 * @param string $tag Tag as it appears in each module heading.
2348
	 *
2349
	 * @return mixed
2350
	 */
2351
	public static function translate_module_tag( $tag ) {
2352
		return jetpack_get_module_i18n_tag( $tag );
2353
	}
2354
2355
	/**
2356
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2357
	 *
2358
	 * @since 3.9.2
2359
	 *
2360
	 * @param array $modules
2361
	 *
2362
	 * @return string|void
2363
	 */
2364
	public static function get_translated_modules( $modules ) {
2365
		foreach ( $modules as $index => $module ) {
2366
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2367
			if ( isset( $module['name'] ) ) {
2368
				$modules[ $index ]['name'] = $i18n_module['name'];
2369
			}
2370
			if ( isset( $module['description'] ) ) {
2371
				$modules[ $index ]['description'] = $i18n_module['description'];
2372
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2373
			}
2374
		}
2375
		return $modules;
2376
	}
2377
2378
	/**
2379
	 * Get a list of activated modules as an array of module slugs.
2380
	 */
2381
	public static function get_active_modules() {
2382
		$active = Jetpack_Options::get_option( 'active_modules' );
2383
2384
		if ( ! is_array( $active ) ) {
2385
			$active = array();
2386
		}
2387
2388
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2389
			$active[] = 'vaultpress';
2390
		} else {
2391
			$active = array_diff( $active, array( 'vaultpress' ) );
2392
		}
2393
2394
		//If protect is active on the main site of a multisite, it should be active on all sites.
2395
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2396
			$active[] = 'protect';
2397
		}
2398
2399
		return array_unique( $active );
2400
	}
2401
2402
	/**
2403
	 * Check whether or not a Jetpack module is active.
2404
	 *
2405
	 * @param string $module The slug of a Jetpack module.
2406
	 * @return bool
2407
	 *
2408
	 * @static
2409
	 */
2410
	public static function is_module_active( $module ) {
2411
		return in_array( $module, self::get_active_modules() );
2412
	}
2413
2414
	public static function is_module( $module ) {
2415
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2416
	}
2417
2418
	/**
2419
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2420
	 *
2421
	 * @param bool $catch True to start catching, False to stop.
2422
	 *
2423
	 * @static
2424
	 */
2425
	public static function catch_errors( $catch ) {
2426
		static $display_errors, $error_reporting;
2427
2428
		if ( $catch ) {
2429
			$display_errors  = @ini_set( 'display_errors', 1 );
2430
			$error_reporting = @error_reporting( E_ALL );
2431
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2432
		} else {
2433
			@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...
2434
			@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...
2435
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2436
		}
2437
	}
2438
2439
	/**
2440
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2441
	 */
2442
	public static function catch_errors_on_shutdown() {
2443
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2444
	}
2445
2446
	/**
2447
	 * Rewrite any string to make paths easier to read.
2448
	 *
2449
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2450
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2451
	 *
2452
	 * @param $string
2453
	 * @return mixed
2454
	 */
2455
	public static function alias_directories( $string ) {
2456
		// ABSPATH has a trailing slash.
2457
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2458
		// WP_CONTENT_DIR does not have a trailing slash.
2459
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2460
2461
		return $string;
2462
	}
2463
2464
	public static function activate_default_modules(
2465
		$min_version = false,
2466
		$max_version = false,
2467
		$other_modules = array(),
2468
		$redirect = true,
2469
		$send_state_messages = true
2470
	) {
2471
		$jetpack = Jetpack::init();
2472
2473
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2474
		$modules = array_merge( $other_modules, $modules );
2475
2476
		// Look for standalone plugins and disable if active.
2477
2478
		$to_deactivate = array();
2479
		foreach ( $modules as $module ) {
2480
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2481
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2482
			}
2483
		}
2484
2485
		$deactivated = array();
2486
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2487
			list( $probable_file, $probable_title ) = $deactivate_me;
2488
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2489
				$deactivated[] = $module;
2490
			}
2491
		}
2492
2493
		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...
2494
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2495
2496
			$url = add_query_arg(
2497
				array(
2498
					'action'   => 'activate_default_modules',
2499
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2500
				),
2501
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2502
			);
2503
			wp_safe_redirect( $url );
2504
			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...
2505
		}
2506
2507
		/**
2508
		 * Fires before default modules are activated.
2509
		 *
2510
		 * @since 1.9.0
2511
		 *
2512
		 * @param string $min_version Minimum version number required to use modules.
2513
		 * @param string $max_version Maximum version number required to use modules.
2514
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2515
		 */
2516
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2517
2518
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2519
		Jetpack::restate();
2520
		Jetpack::catch_errors( true );
2521
2522
		$active = Jetpack::get_active_modules();
2523
2524
		foreach ( $modules as $module ) {
2525
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2526
				$active[] = $module;
2527
				self::update_active_modules( $active );
2528
				continue;
2529
			}
2530
2531
			if ( $send_state_messages && in_array( $module, $active ) ) {
2532
				$module_info = Jetpack::get_module( $module );
2533 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2534
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2535
					if ( $active_state = Jetpack::state( $state ) ) {
2536
						$active_state = explode( ',', $active_state );
2537
					} else {
2538
						$active_state = array();
2539
					}
2540
					$active_state[] = $module;
2541
					Jetpack::state( $state, implode( ',', $active_state ) );
2542
				}
2543
				continue;
2544
			}
2545
2546
			$file = Jetpack::get_module_path( $module );
2547
			if ( ! file_exists( $file ) ) {
2548
				continue;
2549
			}
2550
2551
			// we'll override this later if the plugin can be included without fatal error
2552
			if ( $redirect ) {
2553
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2554
			}
2555
2556
			if ( $send_state_messages ) {
2557
				Jetpack::state( 'error', 'module_activation_failed' );
2558
				Jetpack::state( 'module', $module );
2559
			}
2560
2561
			ob_start();
2562
			require $file;
2563
2564
			$active[] = $module;
2565
2566 View Code Duplication
			if ( $send_state_messages ) {
2567
2568
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
2569
				if ( $active_state = Jetpack::state( $state ) ) {
2570
					$active_state = explode( ',', $active_state );
2571
				} else {
2572
					$active_state = array();
2573
				}
2574
				$active_state[] = $module;
2575
				Jetpack::state( $state, implode( ',', $active_state ) );
2576
			}
2577
2578
			Jetpack::update_active_modules( $active );
2579
2580
			ob_end_clean();
2581
		}
2582
2583
		if ( $send_state_messages ) {
2584
			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...
2585
			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...
2586
		}
2587
2588
		Jetpack::catch_errors( false );
2589
		/**
2590
		 * Fires when default modules are activated.
2591
		 *
2592
		 * @since 1.9.0
2593
		 *
2594
		 * @param string $min_version Minimum version number required to use modules.
2595
		 * @param string $max_version Maximum version number required to use modules.
2596
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2597
		 */
2598
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2599
	}
2600
2601
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2602
		/**
2603
		 * Fires before a module is activated.
2604
		 *
2605
		 * @since 2.6.0
2606
		 *
2607
		 * @param string $module Module slug.
2608
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2609
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2610
		 */
2611
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2612
2613
		$jetpack = Jetpack::init();
2614
2615
		if ( ! strlen( $module ) )
2616
			return false;
2617
2618
		if ( ! Jetpack::is_module( $module ) )
2619
			return false;
2620
2621
		// If it's already active, then don't do it again
2622
		$active = Jetpack::get_active_modules();
2623
		foreach ( $active as $act ) {
2624
			if ( $act == $module )
2625
				return true;
2626
		}
2627
2628
		$module_data = Jetpack::get_module( $module );
2629
2630
		if ( ! Jetpack::is_active() ) {
2631
			if ( !Jetpack::is_development_mode() )
2632
				return false;
2633
2634
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2635
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2636
				return false;
2637
		}
2638
2639
		// Check and see if the old plugin is active
2640
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2641
			// Deactivate the old plugin
2642
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2643
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2644
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2645
				Jetpack::state( 'deactivated_plugins', $module );
2646
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2647
				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...
2648
			}
2649
		}
2650
2651
		// Protect won't work with mis-configured IPs
2652
		if ( 'protect' === $module ) {
2653
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2654
			if ( ! jetpack_protect_get_ip() ) {
2655
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2656
				return false;
2657
			}
2658
		}
2659
2660
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2661
		Jetpack::state( 'module', $module );
2662
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2663
2664
		Jetpack::catch_errors( true );
2665
		ob_start();
2666
		require Jetpack::get_module_path( $module );
2667
		/** This action is documented in class.jetpack.php */
2668
		do_action( 'jetpack_activate_module', $module );
2669
		$active[] = $module;
2670
		Jetpack::update_active_modules( $active );
2671
2672
		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...
2673
		ob_end_clean();
2674
		Jetpack::catch_errors( false );
2675
2676
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2677 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2678
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2679
2680
			//Jump start is being dismissed send data to MC Stats
2681
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2682
2683
			$jetpack->do_stats( 'server_side' );
2684
		}
2685
2686
		if ( $redirect ) {
2687
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2688
		}
2689
		if ( $exit ) {
2690
			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...
2691
		}
2692
		return true;
2693
	}
2694
2695
	function activate_module_actions( $module ) {
2696
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2697
	}
2698
2699
	public static function deactivate_module( $module ) {
2700
		/**
2701
		 * Fires when a module is deactivated.
2702
		 *
2703
		 * @since 1.9.0
2704
		 *
2705
		 * @param string $module Module slug.
2706
		 */
2707
		do_action( 'jetpack_pre_deactivate_module', $module );
2708
2709
		$jetpack = Jetpack::init();
2710
2711
		$active = Jetpack::get_active_modules();
2712
		$new    = array_filter( array_diff( $active, (array) $module ) );
2713
2714
		// A flag for Jump Start so it's not shown again.
2715 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2716
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2717
2718
			//Jump start is being dismissed send data to MC Stats
2719
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2720
2721
			$jetpack->do_stats( 'server_side' );
2722
		}
2723
2724
		return self::update_active_modules( $new );
2725
	}
2726
2727
	public static function enable_module_configurable( $module ) {
2728
		$module = Jetpack::get_module_slug( $module );
2729
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2730
	}
2731
2732
	public static function module_configuration_url( $module ) {
2733
		$module = Jetpack::get_module_slug( $module );
2734
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2735
	}
2736
2737
	public static function module_configuration_load( $module, $method ) {
2738
		$module = Jetpack::get_module_slug( $module );
2739
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2740
	}
2741
2742
	public static function module_configuration_head( $module, $method ) {
2743
		$module = Jetpack::get_module_slug( $module );
2744
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2745
	}
2746
2747
	public static function module_configuration_screen( $module, $method ) {
2748
		$module = Jetpack::get_module_slug( $module );
2749
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2750
	}
2751
2752
	public static function module_configuration_activation_screen( $module, $method ) {
2753
		$module = Jetpack::get_module_slug( $module );
2754
		add_action( 'display_activate_module_setting_' . $module, $method );
2755
	}
2756
2757
/* Installation */
2758
2759
	public static function bail_on_activation( $message, $deactivate = true ) {
2760
?>
2761
<!doctype html>
2762
<html>
2763
<head>
2764
<meta charset="<?php bloginfo( 'charset' ); ?>">
2765
<style>
2766
* {
2767
	text-align: center;
2768
	margin: 0;
2769
	padding: 0;
2770
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2771
}
2772
p {
2773
	margin-top: 1em;
2774
	font-size: 18px;
2775
}
2776
</style>
2777
<body>
2778
<p><?php echo esc_html( $message ); ?></p>
2779
</body>
2780
</html>
2781
<?php
2782
		if ( $deactivate ) {
2783
			$plugins = get_option( 'active_plugins' );
2784
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2785
			$update  = false;
2786
			foreach ( $plugins as $i => $plugin ) {
2787
				if ( $plugin === $jetpack ) {
2788
					$plugins[$i] = false;
2789
					$update = true;
2790
				}
2791
			}
2792
2793
			if ( $update ) {
2794
				update_option( 'active_plugins', array_filter( $plugins ) );
2795
			}
2796
		}
2797
		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...
2798
	}
2799
2800
	/**
2801
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2802
	 * @static
2803
	 */
2804
	public static function plugin_activation( $network_wide ) {
2805
		Jetpack_Options::update_option( 'activated', 1 );
2806
2807
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2808
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2809
		}
2810
2811
		if ( $network_wide )
2812
			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...
2813
2814
		// For firing one-off events (notices) immediately after activation
2815
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2816
2817
		Jetpack::plugin_initialize();
2818
	}
2819
	/**
2820
	 * Runs before bumping version numbers up to a new version
2821
	 * @param  (string) $version    Version:timestamp
2822
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2823
	 * @return null              [description]
2824
	 */
2825
	public static function do_version_bump( $version, $old_version ) {
2826
2827
		if ( ! $old_version ) { // For new sites
2828
			// Setting up jetpack manage
2829
			Jetpack::activate_manage();
2830
		}
2831
	}
2832
2833
	/**
2834
	 * Sets the internal version number and activation state.
2835
	 * @static
2836
	 */
2837
	public static function plugin_initialize() {
2838
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2839
			Jetpack_Options::update_option( 'activated', 2 );
2840
		}
2841
2842 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2843
			$version = $old_version = JETPACK__VERSION . ':' . time();
2844
			/** This action is documented in class.jetpack.php */
2845
			do_action( 'updating_jetpack_version', $version, false );
2846
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2847
		}
2848
2849
		Jetpack::load_modules();
2850
2851
		Jetpack_Options::delete_option( 'do_activate' );
2852
	}
2853
2854
	/**
2855
	 * Removes all connection options
2856
	 * @static
2857
	 */
2858
	public static function plugin_deactivation( ) {
2859
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2860
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2861
			Jetpack_Network::init()->deactivate();
2862
		} else {
2863
			Jetpack::disconnect( false );
2864
			//Jetpack_Heartbeat::init()->deactivate();
2865
		}
2866
	}
2867
2868
	/**
2869
	 * Disconnects from the Jetpack servers.
2870
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2871
	 * @static
2872
	 */
2873
	public static function disconnect( $update_activated_state = true ) {
2874
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2875
		Jetpack::clean_nonces( true );
2876
2877
		// If the site is in an IDC because sync is not allowed,
2878
		// let's make sure to not disconnect the production site.
2879
		if ( ! self::validate_sync_error_idc_option() ) {
2880
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2881
			Jetpack::load_xml_rpc_client();
2882
			$xml = new Jetpack_IXR_Client();
2883
			$xml->query( 'jetpack.deregister' );
2884
		}
2885
2886
		Jetpack_Options::delete_option(
2887
			array(
2888
				'blog_token',
2889
				'user_token',
2890
				'user_tokens',
2891
				'master_user',
2892
				'time_diff',
2893
				'fallback_no_verify_ssl_certs',
2894
			)
2895
		);
2896
2897
		Jetpack_IDC::clear_all_idc_options();
2898
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
2899
2900
		if ( $update_activated_state ) {
2901
			Jetpack_Options::update_option( 'activated', 4 );
2902
		}
2903
2904
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2905
			// Check then record unique disconnection if site has never been disconnected previously
2906
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2907
				$jetpack_unique_connection['disconnected'] = 1;
2908
			} else {
2909
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2910
					//track unique disconnect
2911
					$jetpack = Jetpack::init();
2912
2913
					$jetpack->stat( 'connections', 'unique-disconnect' );
2914
					$jetpack->do_stats( 'server_side' );
2915
				}
2916
				// increment number of times disconnected
2917
				$jetpack_unique_connection['disconnected'] += 1;
2918
			}
2919
2920
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2921
		}
2922
2923
		// Delete cached connected user data
2924
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2925
		delete_transient( $transient_key );
2926
2927
		// Delete all the sync related data. Since it could be taking up space.
2928
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2929
		Jetpack_Sync_Sender::get_instance()->uninstall();
2930
2931
		// Disable the Heartbeat cron
2932
		Jetpack_Heartbeat::init()->deactivate();
2933
	}
2934
2935
	/**
2936
	 * Unlinks the current user from the linked WordPress.com user
2937
	 */
2938
	public static function unlink_user( $user_id = null ) {
2939
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2940
			return false;
2941
2942
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2943
2944
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2945
			return false;
2946
2947
		if ( ! isset( $tokens[ $user_id ] ) )
2948
			return false;
2949
2950
		Jetpack::load_xml_rpc_client();
2951
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2952
		$xml->query( 'jetpack.unlink_user', $user_id );
2953
2954
		unset( $tokens[ $user_id ] );
2955
2956
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2957
2958
		/**
2959
		 * Fires after the current user has been unlinked from WordPress.com.
2960
		 *
2961
		 * @since 4.1.0
2962
		 *
2963
		 * @param int $user_id The current user's ID.
2964
		 */
2965
		do_action( 'jetpack_unlinked_user', $user_id );
2966
2967
		return true;
2968
	}
2969
2970
	/**
2971
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2972
	 */
2973
	public static function try_registration() {
2974
		// Let's get some testing in beta versions and such.
2975
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2976
			// Before attempting to connect, let's make sure that the domains are viable.
2977
			$domains_to_check = array_unique( array(
2978
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2979
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2980
			) );
2981
			foreach ( $domains_to_check as $domain ) {
2982
				$result = Jetpack_Data::is_usable_domain( $domain );
2983
				if ( is_wp_error( $result ) ) {
2984
					return $result;
2985
				}
2986
			}
2987
		}
2988
2989
		$result = Jetpack::register();
2990
2991
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2992
		if ( ! $result || is_wp_error( $result ) ) {
2993
			return $result;
2994
		} else {
2995
			return true;
2996
		}
2997
	}
2998
2999
	/**
3000
	 * Tracking an internal event log. Try not to put too much chaff in here.
3001
	 *
3002
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3003
	 */
3004
	public static function log( $code, $data = null ) {
3005
		// only grab the latest 200 entries
3006
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3007
3008
		// Append our event to the log
3009
		$log_entry = array(
3010
			'time'    => time(),
3011
			'user_id' => get_current_user_id(),
3012
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3013
			'code'    => $code,
3014
		);
3015
		// Don't bother storing it unless we've got some.
3016
		if ( ! is_null( $data ) ) {
3017
			$log_entry['data'] = $data;
3018
		}
3019
		$log[] = $log_entry;
3020
3021
		// Try add_option first, to make sure it's not autoloaded.
3022
		// @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...
3023
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3024
			Jetpack_Options::update_option( 'log', $log );
3025
		}
3026
3027
		/**
3028
		 * Fires when Jetpack logs an internal event.
3029
		 *
3030
		 * @since 3.0.0
3031
		 *
3032
		 * @param array $log_entry {
3033
		 *	Array of details about the log entry.
3034
		 *
3035
		 *	@param string time Time of the event.
3036
		 *	@param int user_id ID of the user who trigerred the event.
3037
		 *	@param int blog_id Jetpack Blog ID.
3038
		 *	@param string code Unique name for the event.
3039
		 *	@param string data Data about the event.
3040
		 * }
3041
		 */
3042
		do_action( 'jetpack_log_entry', $log_entry );
3043
	}
3044
3045
	/**
3046
	 * Get the internal event log.
3047
	 *
3048
	 * @param $event (string) - only return the specific log events
3049
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3050
	 *
3051
	 * @return array of log events || WP_Error for invalid params
3052
	 */
3053
	public static function get_log( $event = false, $num = false ) {
3054
		if ( $event && ! is_string( $event ) ) {
3055
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3056
		}
3057
3058
		if ( $num && ! is_numeric( $num ) ) {
3059
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3060
		}
3061
3062
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3063
3064
		// If nothing set - act as it did before, otherwise let's start customizing the output
3065
		if ( ! $num && ! $event ) {
3066
			return $entire_log;
3067
		} else {
3068
			$entire_log = array_reverse( $entire_log );
3069
		}
3070
3071
		$custom_log_output = array();
3072
3073
		if ( $event ) {
3074
			foreach ( $entire_log as $log_event ) {
3075
				if ( $event == $log_event[ 'code' ] ) {
3076
					$custom_log_output[] = $log_event;
3077
				}
3078
			}
3079
		} else {
3080
			$custom_log_output = $entire_log;
3081
		}
3082
3083
		if ( $num ) {
3084
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3085
		}
3086
3087
		return $custom_log_output;
3088
	}
3089
3090
	/**
3091
	 * Log modification of important settings.
3092
	 */
3093
	public static function log_settings_change( $option, $old_value, $value ) {
3094
		switch( $option ) {
3095
			case 'jetpack_sync_non_public_post_stati':
3096
				self::log( $option, $value );
3097
				break;
3098
		}
3099
	}
3100
3101
	/**
3102
	 * Return stat data for WPCOM sync
3103
	 */
3104
	public static function get_stat_data( $encode = true, $extended = true ) {
3105
		$data = Jetpack_Heartbeat::generate_stats_array();
3106
3107
		if ( $extended ) {
3108
			$additional_data = self::get_additional_stat_data();
3109
			$data = array_merge( $data, $additional_data );
3110
		}
3111
3112
		if ( $encode ) {
3113
			return json_encode( $data );
3114
		}
3115
3116
		return $data;
3117
	}
3118
3119
	/**
3120
	 * Get additional stat data to sync to WPCOM
3121
	 */
3122
	public static function get_additional_stat_data( $prefix = '' ) {
3123
		$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...
3124
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3125
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3126
		$return["{$prefix}site-count"]     = 0;
3127
3128
		if ( function_exists( 'get_blog_count' ) ) {
3129
			$return["{$prefix}site-count"] = get_blog_count();
3130
		}
3131
		return $return;
3132
	}
3133
3134
	private static function get_site_user_count() {
3135
		global $wpdb;
3136
3137
		if ( function_exists( 'wp_is_large_network' ) ) {
3138
			if ( wp_is_large_network( 'users' ) ) {
3139
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3140
			}
3141
		}
3142 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3143
			// It wasn't there, so regenerate the data and save the transient
3144
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3145
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3146
		}
3147
		return $user_count;
3148
	}
3149
3150
	/* Admin Pages */
3151
3152
	function admin_init() {
3153
		// If the plugin is not connected, display a connect message.
3154
		if (
3155
			// the plugin was auto-activated and needs its candy
3156
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3157
		||
3158
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3159
			! Jetpack_Options::get_option( 'activated' )
3160
		) {
3161
			Jetpack::plugin_initialize();
3162
		}
3163
3164
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3165
			Jetpack_Connection_Banner::init();
3166
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3167
			// Upgrade: 1.1 -> 1.1.1
3168
			// Check and see if host can verify the Jetpack servers' SSL certificate
3169
			$args = array();
3170
			Jetpack_Client::_wp_remote_request(
3171
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3172
				$args,
3173
				true
3174
			);
3175
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3176
			// Show the notice on the Dashboard only for now
3177
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3178
		}
3179
3180
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3181
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3182
		}
3183
3184
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3185
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3186
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3187
3188
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3189
			// Artificially throw errors in certain whitelisted cases during plugin activation
3190
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3191
		}
3192
3193
		// Jetpack Manage Activation Screen from .com
3194
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3195
3196
		// Add custom column in wp-admin/users.php to show whether user is linked.
3197
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3198
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3199
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3200
	}
3201
3202
	function admin_body_class( $admin_body_class = '' ) {
3203
		$classes = explode( ' ', trim( $admin_body_class ) );
3204
3205
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3206
3207
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3208
		return " $admin_body_class ";
3209
	}
3210
3211
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3212
		return $admin_body_class . ' jetpack-pagestyles ';
3213
	}
3214
3215
	/**
3216
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3217
	 *
3218
	 * @return null
3219
	 */
3220
	function prepare_manage_jetpack_notice() {
3221
3222
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3223
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3224
	}
3225
3226
	function manage_activate_screen() {
3227
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3228
	}
3229
	/**
3230
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3231
	 * This function artificially throws errors for such cases (whitelisted).
3232
	 *
3233
	 * @param string $plugin The activated plugin.
3234
	 */
3235
	function throw_error_on_activate_plugin( $plugin ) {
3236
		$active_modules = Jetpack::get_active_modules();
3237
3238
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3239
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3240
			$throw = false;
3241
3242
			// Try and make sure it really was the stats plugin
3243
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3244
				if ( 'stats.php' == basename( $plugin ) ) {
3245
					$throw = true;
3246
				}
3247
			} else {
3248
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3249
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3250
					$throw = true;
3251
				}
3252
			}
3253
3254
			if ( $throw ) {
3255
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3256
			}
3257
		}
3258
	}
3259
3260
	function intercept_plugin_error_scrape_init() {
3261
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3262
	}
3263
3264
	function intercept_plugin_error_scrape( $action, $result ) {
3265
		if ( ! $result ) {
3266
			return;
3267
		}
3268
3269
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3270
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3271
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3272
			}
3273
		}
3274
	}
3275
3276
	function add_remote_request_handlers() {
3277
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3278
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3279
	}
3280
3281
	function remote_request_handlers() {
3282
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3283
3284
		switch ( current_filter() ) {
3285
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3286
			$response = $this->upload_handler();
3287
			break;
3288
3289
		case 'wp_ajax_nopriv_jetpack_update_file' :
3290
			$response = $this->upload_handler( true );
3291
			break;
3292
		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...
3293
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3294
			break;
3295
		}
3296
3297
		if ( ! $response ) {
3298
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3299
		}
3300
3301
		if ( is_wp_error( $response ) ) {
3302
			$status_code       = $response->get_error_data();
3303
			$error             = $response->get_error_code();
3304
			$error_description = $response->get_error_message();
3305
3306
			if ( ! is_int( $status_code ) ) {
3307
				$status_code = 400;
3308
			}
3309
3310
			status_header( $status_code );
3311
			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...
3312
		}
3313
3314
		status_header( 200 );
3315
		if ( true === $response ) {
3316
			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...
3317
		}
3318
3319
		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...
3320
	}
3321
3322
	/**
3323
	 * Uploads a file gotten from the global $_FILES.
3324
	 * If `$update_media_item` is true and `post_id` is defined
3325
	 * the attachment file of the media item (gotten through of the post_id)
3326
	 * will be updated instead of add a new one.
3327
	 *
3328
	 * @param  boolean $update_media_item - update media attachment
3329
	 * @return array - An array describing the uploadind files process
3330
	 */
3331
	function upload_handler( $update_media_item = false ) {
3332
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3333
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3334
		}
3335
3336
		$user = wp_authenticate( '', '' );
3337
		if ( ! $user || is_wp_error( $user ) ) {
3338
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3339
		}
3340
3341
		wp_set_current_user( $user->ID );
3342
3343
		if ( ! current_user_can( 'upload_files' ) ) {
3344
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3345
		}
3346
3347
		if ( empty( $_FILES ) ) {
3348
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3349
		}
3350
3351
		foreach ( array_keys( $_FILES ) as $files_key ) {
3352
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3353
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3354
			}
3355
		}
3356
3357
		$media_keys = array_keys( $_FILES['media'] );
3358
3359
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3360
		if ( ! $token || is_wp_error( $token ) ) {
3361
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3362
		}
3363
3364
		$uploaded_files = array();
3365
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3366
		unset( $GLOBALS['post'] );
3367
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3368
			$file = array();
3369
			foreach ( $media_keys as $media_key ) {
3370
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3371
			}
3372
3373
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3374
3375
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3376
			if ( $hmac_provided !== $hmac_file ) {
3377
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3378
				continue;
3379
			}
3380
3381
			$_FILES['.jetpack.upload.'] = $file;
3382
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3383
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3384
				$post_id = 0;
3385
			}
3386
3387
			if ( $update_media_item ) {
3388
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3389
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3390
				}
3391
3392
				$media_array = $_FILES['media'];
3393
3394
				$file_array['name'] = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
3395
				$file_array['type'] = $media_array['type'][0];
3396
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3397
				$file_array['error'] = $media_array['error'][0];
3398
				$file_array['size'] = $media_array['size'][0];
3399
3400
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3401
3402
				if ( is_wp_error( $edited_media_item ) ) {
3403
					return $edited_media_item;
3404
				}
3405
3406
				$response = (object) array(
3407
					'id'   => (string) $post_id,
3408
					'file' => (string) $edited_media_item->post_title,
3409
					'url'  => (string) wp_get_attachment_url( $post_id ),
3410
					'type' => (string) $edited_media_item->post_mime_type,
3411
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3412
				);
3413
3414
				return (array) array( $response );
3415
			}
3416
3417
			$attachment_id = media_handle_upload(
3418
				'.jetpack.upload.',
3419
				$post_id,
3420
				array(),
3421
				array(
3422
					'action' => 'jetpack_upload_file',
3423
				)
3424
			);
3425
3426
			if ( ! $attachment_id ) {
3427
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3428
			} elseif ( is_wp_error( $attachment_id ) ) {
3429
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3430
			} else {
3431
				$attachment = get_post( $attachment_id );
3432
				$uploaded_files[$index] = (object) array(
3433
					'id'   => (string) $attachment_id,
3434
					'file' => $attachment->post_title,
3435
					'url'  => wp_get_attachment_url( $attachment_id ),
3436
					'type' => $attachment->post_mime_type,
3437
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3438
				);
3439
				// Zip files uploads are not supported unless they are done for installation purposed
3440
				// lets delete them in case something goes wrong in this whole process
3441
				if ( 'application/zip' === $attachment->post_mime_type ) {
3442
					// Schedule a cleanup for 2 hours from now in case of failed install.
3443
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3444
				}
3445
			}
3446
		}
3447
		if ( ! is_null( $global_post ) ) {
3448
			$GLOBALS['post'] = $global_post;
3449
		}
3450
3451
		return $uploaded_files;
3452
	}
3453
3454
	/**
3455
	 * Add help to the Jetpack page
3456
	 *
3457
	 * @since Jetpack (1.2.3)
3458
	 * @return false if not the Jetpack page
3459
	 */
3460
	function admin_help() {
3461
		$current_screen = get_current_screen();
3462
3463
		// Overview
3464
		$current_screen->add_help_tab(
3465
			array(
3466
				'id'		=> 'home',
3467
				'title'		=> __( 'Home', 'jetpack' ),
3468
				'content'	=>
3469
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3470
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3471
					'<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>',
3472
			)
3473
		);
3474
3475
		// Screen Content
3476
		if ( current_user_can( 'manage_options' ) ) {
3477
			$current_screen->add_help_tab(
3478
				array(
3479
					'id'		=> 'settings',
3480
					'title'		=> __( 'Settings', 'jetpack' ),
3481
					'content'	=>
3482
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3483
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3484
						'<ol>' .
3485
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3486
							'<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>' .
3487
						'</ol>' .
3488
						'<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>'
3489
				)
3490
			);
3491
		}
3492
3493
		// Help Sidebar
3494
		$current_screen->set_help_sidebar(
3495
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3496
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3497
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3498
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3499
		);
3500
	}
3501
3502
	function admin_menu_css() {
3503
		wp_enqueue_style( 'jetpack-icons' );
3504
	}
3505
3506
	function admin_menu_order() {
3507
		return true;
3508
	}
3509
3510 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3511
		$jp_menu_order = array();
3512
3513
		foreach ( $menu_order as $index => $item ) {
3514
			if ( $item != 'jetpack' ) {
3515
				$jp_menu_order[] = $item;
3516
			}
3517
3518
			if ( $index == 0 ) {
3519
				$jp_menu_order[] = 'jetpack';
3520
			}
3521
		}
3522
3523
		return $jp_menu_order;
3524
	}
3525
3526
	function admin_head() {
3527 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3528
			/** This action is documented in class.jetpack-admin-page.php */
3529
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3530
	}
3531
3532
	function admin_banner_styles() {
3533
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3534
3535 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3536
			wp_register_style(
3537
				'jetpack-dops-style',
3538
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3539
				array(),
3540
				JETPACK__VERSION
3541
			);
3542
		}
3543
3544
		wp_enqueue_style(
3545
			'jetpack',
3546
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3547
			array( 'jetpack-dops-style' ),
3548
			 JETPACK__VERSION . '-20121016'
3549
		);
3550
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3551
		wp_style_add_data( 'jetpack', 'suffix', $min );
3552
	}
3553
3554
	function plugin_action_links( $actions ) {
3555
3556
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3557
3558
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3559
			return array_merge(
3560
				$jetpack_home,
3561
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3562
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3563
				$actions
3564
				);
3565
			}
3566
3567
		return array_merge( $jetpack_home, $actions );
3568
	}
3569
3570
	/**
3571
	 * This is the first banner
3572
	 * It should be visible only to user that can update the option
3573
	 * Are not connected
3574
	 *
3575
	 * @return null
3576
	 */
3577
	function admin_jetpack_manage_notice() {
3578
		$screen = get_current_screen();
3579
3580
		// Don't show the connect notice on the jetpack settings page.
3581
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3582
			return;
3583
		}
3584
3585
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3586
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3587
		/**
3588
		 * I think it would be great to have different wordsing depending on where you are
3589
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3590
		 * etc..
3591
		 */
3592
3593
		?>
3594
		<div id="message" class="updated jp-banner">
3595
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3596
				<div class="jp-banner__description-container">
3597
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3598
					<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>
3599
					<p class="jp-banner__button-container">
3600
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3601
						<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>
3602
					</p>
3603
				</div>
3604
		</div>
3605
		<?php
3606
	}
3607
3608
	/**
3609
	 * Returns the url that the user clicks to remove the notice for the big banner
3610
	 * @return (string)
3611
	 */
3612
	function opt_out_jetpack_manage_url() {
3613
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3614
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3615
	}
3616
	/**
3617
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3618
	 * @return (string)
3619
	 */
3620
	function opt_in_jetpack_manage_url() {
3621
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3622
	}
3623
3624
	function opt_in_jetpack_manage_notice() {
3625
		?>
3626
		<div class="wrap">
3627
			<div id="message" class="jetpack-message is-opt-in">
3628
				<?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' ); ?>
3629
			</div>
3630
		</div>
3631
		<?php
3632
3633
	}
3634
	/**
3635
	 * Determines whether to show the notice of not true = display notice
3636
	 * @return (bool)
3637
	 */
3638
	function can_display_jetpack_manage_notice() {
3639
		// never display the notice to users that can't do anything about it anyways
3640
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3641
			return false;
3642
3643
		// don't display if we are in development more
3644
		if( Jetpack::is_development_mode() ) {
3645
			return false;
3646
		}
3647
		// don't display if the site is private
3648
		if(  ! Jetpack_Options::get_option( 'public' ) )
3649
			return false;
3650
3651
		/**
3652
		 * Should the Jetpack Remote Site Management notice be displayed.
3653
		 *
3654
		 * @since 3.3.0
3655
		 *
3656
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3657
		 */
3658
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3659
	}
3660
3661
	/*
3662
	 * Registration flow:
3663
	 * 1 - ::admin_page_load() action=register
3664
	 * 2 - ::try_registration()
3665
	 * 3 - ::register()
3666
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3667
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3668
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3669
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3670
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3671
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3672
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3673
	 *       jetpack_id, jetpack_secret, jetpack_public
3674
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3675
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3676
	 * 5 - user logs in with WP.com account
3677
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3678
	 *		- Jetpack_Client_Server::authorize()
3679
	 *		- Jetpack_Client_Server::get_token()
3680
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3681
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3682
	 *			- which responds with access_token, token_type, scope
3683
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3684
	 *		- Jetpack::activate_default_modules()
3685
	 *     		- Deactivates deprecated plugins
3686
	 *     		- Activates all default modules
3687
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3688
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3689
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3690
	 *     Done!
3691
	 */
3692
3693
	/**
3694
	 * Handles the page load events for the Jetpack admin page
3695
	 */
3696
	function admin_page_load() {
3697
		$error = false;
3698
3699
		// Make sure we have the right body class to hook stylings for subpages off of.
3700
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3701
3702
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3703
			// Should only be used in intermediate redirects to preserve state across redirects
3704
			Jetpack::restate();
3705
		}
3706
3707
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3708
			// User clicked in the iframe to link their accounts
3709
			if ( ! Jetpack::is_user_connected() ) {
3710
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3711
				if ( isset( $_GET['notes_iframe'] ) )
3712
					$connect_url .= '&notes_iframe';
3713
				wp_redirect( $connect_url );
3714
				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...
3715
			} else {
3716
				if ( ! isset( $_GET['calypso_env'] ) ) {
3717
					Jetpack::state( 'message', 'already_authorized' );
3718
					wp_safe_redirect( Jetpack::admin_url() );
3719
				} else {
3720
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3721
					$connect_url .= '&already_authorized=true';
3722
					wp_redirect( $connect_url );
3723
				}
3724
			}
3725
		}
3726
3727
3728
		if ( isset( $_GET['action'] ) ) {
3729
			switch ( $_GET['action'] ) {
3730
			case 'authorize':
3731
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3732
					Jetpack::state( 'message', 'already_authorized' );
3733
					wp_safe_redirect( Jetpack::admin_url() );
3734
					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...
3735
				}
3736
				Jetpack::log( 'authorize' );
3737
				$client_server = new Jetpack_Client_Server;
3738
				$client_server->client_authorize();
3739
				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...
3740
			case 'register' :
3741
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3742
					$error = 'cheatin';
3743
					break;
3744
				}
3745
				check_admin_referer( 'jetpack-register' );
3746
				Jetpack::log( 'register' );
3747
				Jetpack::maybe_set_version_option();
3748
				$registered = Jetpack::try_registration();
3749
				if ( is_wp_error( $registered ) ) {
3750
					$error = $registered->get_error_code();
3751
					Jetpack::state( 'error', $error );
3752
					Jetpack::state( 'error', $registered->get_error_message() );
3753
					break;
3754
				}
3755
3756
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3757
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3758
3759
				wp_redirect( $this->build_connect_url( true, $redirect, $from ) );
3760
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3761
			case 'activate' :
3762
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3763
					$error = 'cheatin';
3764
					break;
3765
				}
3766
3767
				$module = stripslashes( $_GET['module'] );
3768
				check_admin_referer( "jetpack_activate-$module" );
3769
				Jetpack::log( 'activate', $module );
3770
				Jetpack::activate_module( $module );
3771
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3772
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3773
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3774
			case 'activate_default_modules' :
3775
				check_admin_referer( 'activate_default_modules' );
3776
				Jetpack::log( 'activate_default_modules' );
3777
				Jetpack::restate();
3778
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3779
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3780
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3781
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3782
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3783
				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...
3784
			case 'disconnect' :
3785
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3786
					$error = 'cheatin';
3787
					break;
3788
				}
3789
3790
				check_admin_referer( 'jetpack-disconnect' );
3791
				Jetpack::log( 'disconnect' );
3792
				Jetpack::disconnect();
3793
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3794
				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...
3795
			case 'reconnect' :
3796
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3797
					$error = 'cheatin';
3798
					break;
3799
				}
3800
3801
				check_admin_referer( 'jetpack-reconnect' );
3802
				Jetpack::log( 'reconnect' );
3803
				$this->disconnect();
3804
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3805
				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...
3806 View Code Duplication
			case 'deactivate' :
3807
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3808
					$error = 'cheatin';
3809
					break;
3810
				}
3811
3812
				$modules = stripslashes( $_GET['module'] );
3813
				check_admin_referer( "jetpack_deactivate-$modules" );
3814
				foreach ( explode( ',', $modules ) as $module ) {
3815
					Jetpack::log( 'deactivate', $module );
3816
					Jetpack::deactivate_module( $module );
3817
					Jetpack::state( 'message', 'module_deactivated' );
3818
				}
3819
				Jetpack::state( 'module', $modules );
3820
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3821
				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...
3822
			case 'unlink' :
3823
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3824
				check_admin_referer( 'jetpack-unlink' );
3825
				Jetpack::log( 'unlink' );
3826
				$this->unlink_user();
3827
				Jetpack::state( 'message', 'unlinked' );
3828
				if ( 'sub-unlink' == $redirect ) {
3829
					wp_safe_redirect( admin_url() );
3830
				} else {
3831
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3832
				}
3833
				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...
3834
			default:
3835
				/**
3836
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3837
				 *
3838
				 * @since 2.6.0
3839
				 *
3840
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3841
				 */
3842
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3843
			}
3844
		}
3845
3846
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3847
			self::activate_new_modules( true );
3848
		}
3849
3850
		$message_code = Jetpack::state( 'message' );
3851
		if ( Jetpack::state( 'optin-manage' ) ) {
3852
			$activated_manage = $message_code;
3853
			$message_code = 'jetpack-manage';
3854
		}
3855
3856
		switch ( $message_code ) {
3857
		case 'jetpack-manage':
3858
			$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>';
3859
			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...
3860
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3861
			}
3862
			break;
3863
3864
		}
3865
3866
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3867
3868
		if ( ! empty( $deactivated_plugins ) ) {
3869
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3870
			$deactivated_titles  = array();
3871
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3872
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3873
					continue;
3874
				}
3875
3876
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3877
			}
3878
3879
			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...
3880
				if ( $this->message ) {
3881
					$this->message .= "<br /><br />\n";
3882
				}
3883
3884
				$this->message .= wp_sprintf(
3885
					_n(
3886
						'Jetpack contains the most recent version of the old %l plugin.',
3887
						'Jetpack contains the most recent versions of the old %l plugins.',
3888
						count( $deactivated_titles ),
3889
						'jetpack'
3890
					),
3891
					$deactivated_titles
3892
				);
3893
3894
				$this->message .= "<br />\n";
3895
3896
				$this->message .= _n(
3897
					'The old version has been deactivated and can be removed from your site.',
3898
					'The old versions have been deactivated and can be removed from your site.',
3899
					count( $deactivated_titles ),
3900
					'jetpack'
3901
				);
3902
			}
3903
		}
3904
3905
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3906
3907
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3908
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3909
		}
3910
3911 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3912
			/**
3913
			 * Fires when a module configuration page is loaded.
3914
			 * The dynamic part of the hook is the configure parameter from the URL.
3915
			 *
3916
			 * @since 1.1.0
3917
			 */
3918
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3919
		}
3920
3921
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3922
	}
3923
3924
	function admin_notices() {
3925
3926
		if ( $this->error ) {
3927
?>
3928
<div id="message" class="jetpack-message jetpack-err">
3929
	<div class="squeezer">
3930
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3931
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3932
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3933
<?php	endif; ?>
3934
	</div>
3935
</div>
3936
<?php
3937
		}
3938
3939
		if ( $this->message ) {
3940
?>
3941
<div id="message" class="jetpack-message">
3942
	<div class="squeezer">
3943
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3944
	</div>
3945
</div>
3946
<?php
3947
		}
3948
3949
		if ( $this->privacy_checks ) :
3950
			$module_names = $module_slugs = array();
3951
3952
			$privacy_checks = explode( ',', $this->privacy_checks );
3953
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3954
			foreach ( $privacy_checks as $module_slug ) {
3955
				$module = Jetpack::get_module( $module_slug );
3956
				if ( ! $module ) {
3957
					continue;
3958
				}
3959
3960
				$module_slugs[] = $module_slug;
3961
				$module_names[] = "<strong>{$module['name']}</strong>";
3962
			}
3963
3964
			$module_slugs = join( ',', $module_slugs );
3965
?>
3966
<div id="message" class="jetpack-message jetpack-err">
3967
	<div class="squeezer">
3968
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3969
		<p><?php
3970
			echo wp_kses(
3971
				wptexturize(
3972
					wp_sprintf(
3973
						_nx(
3974
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3975
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3976
							count( $privacy_checks ),
3977
							'%l = list of Jetpack module/feature names',
3978
							'jetpack'
3979
						),
3980
						$module_names
3981
					)
3982
				),
3983
				array( 'strong' => true )
3984
			);
3985
3986
			echo "\n<br />\n";
3987
3988
			echo wp_kses(
3989
				sprintf(
3990
					_nx(
3991
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3992
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3993
						count( $privacy_checks ),
3994
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3995
						'jetpack'
3996
					),
3997
					wp_nonce_url(
3998
						Jetpack::admin_url(
3999
							array(
4000
								'page'   => 'jetpack',
4001
								'action' => 'deactivate',
4002
								'module' => urlencode( $module_slugs ),
4003
							)
4004
						),
4005
						"jetpack_deactivate-$module_slugs"
4006
					),
4007
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4008
				),
4009
				array( 'a' => array( 'href' => true, 'title' => true ) )
4010
			);
4011
		?></p>
4012
	</div>
4013
</div>
4014
<?php endif;
4015
	// only display the notice if the other stuff is not there
4016
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4017
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4018
			$this->opt_in_jetpack_manage_notice();
4019
		}
4020
	}
4021
4022
	/**
4023
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4024
	 */
4025
	function stat( $group, $detail ) {
4026
		if ( ! isset( $this->stats[ $group ] ) )
4027
			$this->stats[ $group ] = array();
4028
		$this->stats[ $group ][] = $detail;
4029
	}
4030
4031
	/**
4032
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4033
	 */
4034
	function do_stats( $method = '' ) {
4035
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4036
			foreach ( $this->stats as $group => $stats ) {
4037
				if ( is_array( $stats ) && count( $stats ) ) {
4038
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4039
					if ( 'server_side' === $method ) {
4040
						self::do_server_side_stat( $args );
4041
					} else {
4042
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4043
					}
4044
				}
4045
				unset( $this->stats[ $group ] );
4046
			}
4047
		}
4048
	}
4049
4050
	/**
4051
	 * Runs stats code for a one-off, server-side.
4052
	 *
4053
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4054
	 *
4055
	 * @return bool If it worked.
4056
	 */
4057
	static function do_server_side_stat( $args ) {
4058
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4059
		if ( is_wp_error( $response ) )
4060
			return false;
4061
4062
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4063
			return false;
4064
4065
		return true;
4066
	}
4067
4068
	/**
4069
	 * Builds the stats url.
4070
	 *
4071
	 * @param $args array|string The arguments to append to the URL.
4072
	 *
4073
	 * @return string The URL to be pinged.
4074
	 */
4075
	static function build_stats_url( $args ) {
4076
		$defaults = array(
4077
			'v'    => 'wpcom2',
4078
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4079
		);
4080
		$args     = wp_parse_args( $args, $defaults );
4081
		/**
4082
		 * Filter the URL used as the Stats tracking pixel.
4083
		 *
4084
		 * @since 2.3.2
4085
		 *
4086
		 * @param string $url Base URL used as the Stats tracking pixel.
4087
		 */
4088
		$base_url = apply_filters(
4089
			'jetpack_stats_base_url',
4090
			'https://pixel.wp.com/g.gif'
4091
		);
4092
		$url      = add_query_arg( $args, $base_url );
4093
		return $url;
4094
	}
4095
4096
	static function translate_current_user_to_role() {
4097
		foreach ( self::$capability_translations as $role => $cap ) {
4098
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4099
				return $role;
4100
			}
4101
		}
4102
4103
		return false;
4104
	}
4105
4106
	static function translate_user_to_role( $user ) {
4107
		foreach ( self::$capability_translations as $role => $cap ) {
4108
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4109
				return $role;
4110
			}
4111
		}
4112
4113
		return false;
4114
    }
4115
4116
	static function translate_role_to_cap( $role ) {
4117
		if ( ! isset( self::$capability_translations[$role] ) ) {
4118
			return false;
4119
		}
4120
4121
		return self::$capability_translations[$role];
4122
	}
4123
4124
	static function sign_role( $role, $user_id = null ) {
4125
		if ( empty( $user_id ) ) {
4126
			$user_id = (int) get_current_user_id();
4127
		}
4128
4129
		if ( ! $user_id  ) {
4130
			return false;
4131
		}
4132
4133
		$token = Jetpack_Data::get_access_token();
4134
		if ( ! $token || is_wp_error( $token ) ) {
4135
			return false;
4136
		}
4137
4138
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4139
	}
4140
4141
4142
	/**
4143
	 * Builds a URL to the Jetpack connection auth page
4144
	 *
4145
	 * @since 3.9.5
4146
	 *
4147
	 * @param bool $raw If true, URL will not be escaped.
4148
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4149
	 *                              If string, will be a custom redirect.
4150
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4151
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4152
	 *
4153
	 * @return string Connect URL
4154
	 */
4155
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4156
		$site_id = Jetpack_Options::get_option( 'id' );
4157
		$token = Jetpack_Options::get_option( 'blog_token' );
4158
4159
		if ( $register || ! $token || ! $site_id ) {
4160
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4161
4162
			if ( ! empty( $redirect ) ) {
4163
				$url = add_query_arg(
4164
					'redirect',
4165
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4166
					$url
4167
				);
4168
			}
4169
4170
			if( is_network_admin() ) {
4171
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4172
			}
4173
		} else {
4174
4175
			// Checking existing token
4176
			$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4177
				sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4178
				'1.1'
4179
			);
4180
4181
			if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4182
				// Generating a register URL instead to refresh the existing token
4183
				return $this->build_connect_url( $raw, $redirect, $from, true );
4184
			}
4185
4186
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4187
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4188
			}
4189
4190
			$role = self::translate_current_user_to_role();
4191
			$signed_role = self::sign_role( $role );
4192
4193
			$user = wp_get_current_user();
4194
4195
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4196
			$redirect = $redirect
4197
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4198
				: $jetpack_admin_page;
4199
4200
			if( isset( $_REQUEST['is_multisite'] ) ) {
4201
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4202
			}
4203
4204
			$secrets = Jetpack::generate_secrets( 'authorize' );
4205
4206
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4207
				? get_site_icon_url()
4208
				: false;
4209
4210
			/**
4211
			 * Filter the type of authorization.
4212
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4213
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4214
			 *
4215
			 * @since 4.3.3
4216
			 *
4217
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4218
			 */
4219
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4220
4221
			$args = urlencode_deep(
4222
				array(
4223
					'response_type' => 'code',
4224
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4225
					'redirect_uri'  => add_query_arg(
4226
						array(
4227
							'action'   => 'authorize',
4228
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4229
							'redirect' => urlencode( $redirect ),
4230
						),
4231
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4232
					),
4233
					'state'         => $user->ID,
4234
					'scope'         => $signed_role,
4235
					'user_email'    => $user->user_email,
4236
					'user_login'    => $user->user_login,
4237
					'is_active'     => Jetpack::is_active(),
4238
					'jp_version'    => JETPACK__VERSION,
4239
					'auth_type'     => $auth_type,
4240
					'secret'        => $secrets['secret_1'],
4241
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4242
					'blogname'      => get_option( 'blogname' ),
4243
					'site_url'      => site_url(),
4244
					'home_url'      => home_url(),
4245
					'site_icon'     => $site_icon,
4246
				)
4247
			);
4248
4249
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4250
		}
4251
4252
		if ( $from ) {
4253
			$url = add_query_arg( 'from', $from, $url );
4254
		}
4255
4256
4257
		if ( isset( $_GET['calypso_env'] ) ) {
4258
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4259
		}
4260
4261
		return $raw ? $url : esc_url( $url );
4262
	}
4263
4264
	function build_reconnect_url( $raw = false ) {
4265
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4266
		return $raw ? $url : esc_url( $url );
4267
	}
4268
4269
	public static function admin_url( $args = null ) {
4270
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4271
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4272
		return $url;
4273
	}
4274
4275
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4276
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4277
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4278
	}
4279
4280
	function dismiss_jetpack_notice() {
4281
4282
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4283
			return;
4284
		}
4285
4286
		switch( $_GET['jetpack-notice'] ) {
4287
			case 'dismiss':
4288
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4289
4290
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4291
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4292
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4293
				}
4294
				break;
4295 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...
4296
4297
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4298
					// Don't show the banner again
4299
4300
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4301
					// redirect back to the page that had the notice
4302
					if ( wp_get_referer() ) {
4303
						wp_safe_redirect( wp_get_referer() );
4304
					} else {
4305
						// Take me to Jetpack
4306
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4307
					}
4308
				}
4309
				break;
4310 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...
4311
4312
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4313
					// Don't show the banner again
4314
4315
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4316
					// redirect back to the page that had the notice
4317
					if ( wp_get_referer() ) {
4318
						wp_safe_redirect( wp_get_referer() );
4319
					} else {
4320
						// Take me to Jetpack
4321
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4322
					}
4323
				}
4324
				break;
4325
			case 'jetpack-manage-opt-in':
4326
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4327
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4328
4329
					$redirection_url = Jetpack::admin_url();
4330
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4331
4332
					// Don't redirect form the Jetpack Setting Page
4333
					$referer_parsed = parse_url ( wp_get_referer() );
4334
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4335
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4336
						// Take the user to Jetpack home except when on the setting page
4337
						$redirection_url = wp_get_referer();
4338
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4339
					}
4340
					// Also update the JSON API FULL MANAGEMENT Option
4341
					Jetpack::activate_module( 'manage', false, false );
4342
4343
					// Special Message when option in.
4344
					Jetpack::state( 'optin-manage', 'true' );
4345
					// Activate the Module if not activated already
4346
4347
					// Redirect properly
4348
					wp_safe_redirect( $redirection_url );
4349
4350
				}
4351
				break;
4352
		}
4353
	}
4354
4355
	public static function admin_screen_configure_module( $module_id ) {
4356
4357
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4358
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4359
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4360
				/**
4361
				 * Fires to diplay a custom module activation screen.
4362
				 *
4363
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4364
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4365
				 *
4366
				 * @module manage
4367
				 *
4368
				 * @since 3.8.0
4369
				 *
4370
				 * @param int $module_id Module ID.
4371
				 */
4372
				do_action( 'display_activate_module_setting_' . $module_id );
4373
			} else {
4374
				self::display_activate_module_link( $module_id );
4375
			}
4376
4377
			return false;
4378
		} ?>
4379
4380
		<div id="jp-settings-screen" style="position: relative">
4381
			<h3>
4382
			<?php
4383
				$module = Jetpack::get_module( $module_id );
4384
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4385
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4386
			?>
4387
			</h3>
4388
			<?php
4389
				/**
4390
				 * Fires within the displayed message when a feature configuation is updated.
4391
				 *
4392
				 * @since 3.4.0
4393
				 *
4394
				 * @param int $module_id Module ID.
4395
				 */
4396
				do_action( 'jetpack_notices_update_settings', $module_id );
4397
				/**
4398
				 * Fires when a feature configuation screen is loaded.
4399
				 * The dynamic part of the hook, $module_id, is the module ID.
4400
				 *
4401
				 * @since 1.1.0
4402
				 */
4403
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4404
			?>
4405
		</div><?php
4406
	}
4407
4408
	/**
4409
	 * Display link to activate the module to see the settings screen.
4410
	 * @param  string $module_id
4411
	 * @return null
4412
	 */
4413
	public static function display_activate_module_link( $module_id ) {
4414
4415
		$info =  Jetpack::get_module( $module_id );
4416
		$extra = '';
4417
		$activate_url = wp_nonce_url(
4418
				Jetpack::admin_url(
4419
					array(
4420
						'page'   => 'jetpack',
4421
						'action' => 'activate',
4422
						'module' => $module_id,
4423
					)
4424
				),
4425
				"jetpack_activate-$module_id"
4426
			);
4427
4428
		?>
4429
4430
		<div class="wrap configure-module">
4431
			<div id="jp-settings-screen">
4432
				<?php
4433
				if ( $module_id == 'json-api' ) {
4434
4435
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4436
4437
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4438
4439
					$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' );
4440
4441
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4442
				} ?>
4443
4444
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4445
				<div class="narrow">
4446
					<p><?php echo  $info['description']; ?></p>
4447
					<?php if( $extra ) { ?>
4448
					<p><?php echo esc_html( $extra ); ?></p>
4449
					<?php } ?>
4450
					<p>
4451
						<?php
4452
						if( wp_get_referer() ) {
4453
							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() );
4454
						} else {
4455
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4456
						} ?>
4457
					</p>
4458
				</div>
4459
4460
			</div>
4461
		</div>
4462
4463
		<?php
4464
	}
4465
4466
	public static function sort_modules( $a, $b ) {
4467
		if ( $a['sort'] == $b['sort'] )
4468
			return 0;
4469
4470
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4471
	}
4472
4473
	function ajax_recheck_ssl() {
4474
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4475
		$result = Jetpack::permit_ssl( true );
4476
		wp_send_json( array(
4477
			'enabled' => $result,
4478
			'message' => get_transient( 'jetpack_https_test_message' )
4479
		) );
4480
	}
4481
4482
/* Client API */
4483
4484
	/**
4485
	 * Returns the requested Jetpack API URL
4486
	 *
4487
	 * @return string
4488
	 */
4489
	public static function api_url( $relative_url ) {
4490
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4491
	}
4492
4493
	/**
4494
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4495
	 */
4496
	public static function fix_url_for_bad_hosts( $url ) {
4497
		if ( 0 !== strpos( $url, 'https://' ) ) {
4498
			return $url;
4499
		}
4500
4501
		switch ( JETPACK_CLIENT__HTTPS ) {
4502
			case 'ALWAYS' :
4503
				return $url;
4504
			case 'NEVER' :
4505
				return set_url_scheme( $url, 'http' );
4506
			// default : case 'AUTO' :
4507
		}
4508
4509
		// we now return the unmodified SSL URL by default, as a security precaution
4510
		return $url;
4511
	}
4512
4513
	/**
4514
	 * Checks to see if the URL is using SSL to connect with Jetpack
4515
	 *
4516
	 * @since 2.3.3
4517
	 * @return boolean
4518
	 */
4519
	public static function permit_ssl( $force_recheck = false ) {
4520
		// Do some fancy tests to see if ssl is being supported
4521
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4522
			$message = '';
4523
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4524
				$ssl = 0;
4525
			} else {
4526
				switch ( JETPACK_CLIENT__HTTPS ) {
4527
					case 'NEVER':
4528
						$ssl = 0;
4529
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4530
						break;
4531
					case 'ALWAYS':
4532
					case 'AUTO':
4533
					default:
4534
						$ssl = 1;
4535
						break;
4536
				}
4537
4538
				// If it's not 'NEVER', test to see
4539
				if ( $ssl ) {
4540
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4541
						$ssl = 0;
4542
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4543
					} else {
4544
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4545
						if ( is_wp_error( $response ) ) {
4546
							$ssl = 0;
4547
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4548
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4549
							$ssl = 0;
4550
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4551
						}
4552
					}
4553
				}
4554
			}
4555
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4556
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4557
		}
4558
4559
		return (bool) $ssl;
4560
	}
4561
4562
	/*
4563
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4564
	 */
4565
	public function alert_auto_ssl_fail() {
4566
		if ( ! current_user_can( 'manage_options' ) )
4567
			return;
4568
4569
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4570
		?>
4571
4572
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4573
			<div class="jp-banner__content">
4574
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4575
				<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>
4576
				<p>
4577
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4578
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4579
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4580
				</p>
4581
				<p>
4582
					<?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' ),
4583
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4584
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4585
				</p>
4586
			</div>
4587
		</div>
4588
		<style>
4589
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4590
		</style>
4591
		<script type="text/javascript">
4592
			jQuery( document ).ready( function( $ ) {
4593
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4594
					var $this = $( this );
4595
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4596
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4597
					e.preventDefault();
4598
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4599
					$.post( ajaxurl, data )
4600
					  .done( function( response ) {
4601
					  	if ( response.enabled ) {
4602
					  		$( '#jetpack-ssl-warning' ).hide();
4603
					  	} else {
4604
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4605
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4606
					  	}
4607
					  }.bind( $this ) );
4608
				} );
4609
			} );
4610
		</script>
4611
4612
		<?php
4613
	}
4614
4615
	/**
4616
	 * Returns the Jetpack XML-RPC API
4617
	 *
4618
	 * @return string
4619
	 */
4620
	public static function xmlrpc_api_url() {
4621
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4622
		return untrailingslashit( $base ) . '/xmlrpc.php';
4623
	}
4624
4625
	/**
4626
	 * Creates two secret tokens and the end of life timestamp for them.
4627
	 *
4628
	 * Note these tokens are unique per call, NOT static per site for connecting.
4629
	 *
4630
	 * @since 2.6
4631
	 * @return array
4632
	 */
4633
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4634
		if ( ! $user_id ) {
4635
			$user_id = get_current_user_id();
4636
		}
4637
4638
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
4639
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4640
4641
		if (
4642
			isset( $secrets[ $secret_name ] ) &&
4643
			$secrets[ $secret_name ]['exp'] > time()
4644
		) {
4645
			return $secrets[ $secret_name ];
4646
		}
4647
4648
		$secret_value = array(
4649
			'secret_1'  => wp_generate_password( 32, false ),
4650
			'secret_2'  => wp_generate_password( 32, false ),
4651
			'exp'       => time() + $exp,
4652
		);
4653
4654
		$secrets[ $secret_name ] = $secret_value;
4655
4656
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4657
		return $secrets[ $secret_name ];
4658
	}
4659
4660
	public static function get_secrets( $action, $user_id ) {
4661
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4662
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4663
4664
		if ( ! isset( $secrets[ $secret_name ] ) ) {
4665
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4666
		}
4667
4668
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
4669
			self::delete_secrets( $action, $user_id );
4670
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4671
		}
4672
4673
		return $secrets[ $secret_name ];
4674
	}
4675
4676
	public static function delete_secrets( $action, $user_id ) {
4677
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4678
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4679
		if ( isset( $secrets[ $secret_name ] ) ) {
4680
			unset( $secrets[ $secret_name ] );
4681
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4682
		}
4683
	}
4684
4685
	/**
4686
	 * Builds the timeout limit for queries talking with the wpcom servers.
4687
	 *
4688
	 * Based on local php max_execution_time in php.ini
4689
	 *
4690
	 * @since 2.6
4691
	 * @return int
4692
	 **/
4693
	public function get_remote_query_timeout_limit() {
4694
	    $timeout = (int) ini_get( 'max_execution_time' );
4695
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4696
				$timeout = 30;
4697
	    return intval( $timeout / 2 );
4698
	}
4699
4700
4701
	/**
4702
	 * Takes the response from the Jetpack register new site endpoint and
4703
	 * verifies it worked properly.
4704
	 *
4705
	 * @since 2.6
4706
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4707
	 **/
4708
	public function validate_remote_register_response( $response ) {
4709
	  if ( is_wp_error( $response ) ) {
4710
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4711
		}
4712
4713
		$code   = wp_remote_retrieve_response_code( $response );
4714
		$entity = wp_remote_retrieve_body( $response );
4715
		if ( $entity )
4716
			$registration_response = json_decode( $entity );
4717
		else
4718
			$registration_response = false;
4719
4720
		$code_type = intval( $code / 100 );
4721
		if ( 5 == $code_type ) {
4722
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4723
		} elseif ( 408 == $code ) {
4724
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4725
		} elseif ( ! empty( $registration_response->error ) ) {
4726
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4727
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
4728
			} else {
4729
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4730
			}
4731
4732
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4733
		} elseif ( 200 != $code ) {
4734
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4735
		}
4736
4737
		// Jetpack ID error block
4738
		if ( empty( $registration_response->jetpack_id ) ) {
4739
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4740
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4741
			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 );
4742
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4743
			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 );
4744
		}
4745
4746
	    return $registration_response;
4747
	}
4748
	/**
4749
	 * @return bool|WP_Error
4750
	 */
4751
	public static function register() {
4752
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4753
		$secrets = Jetpack::generate_secrets( 'register' );
4754
4755 View Code Duplication
		if (
4756
			empty( $secrets['secret_1'] ) ||
4757
			empty( $secrets['secret_2'] ) ||
4758
			empty( $secrets['exp'] )
4759
		) {
4760
			return new Jetpack_Error( 'missing_secrets' );
4761
		}
4762
4763
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4764
4765
		$gmt_offset = get_option( 'gmt_offset' );
4766
		if ( ! $gmt_offset ) {
4767
			$gmt_offset = 0;
4768
		}
4769
4770
		$stats_options = get_option( 'stats_options' );
4771
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4772
4773
		$args = array(
4774
			'method'  => 'POST',
4775
			'body'    => array(
4776
				'siteurl'         => site_url(),
4777
				'home'            => home_url(),
4778
				'gmt_offset'      => $gmt_offset,
4779
				'timezone_string' => (string) get_option( 'timezone_string' ),
4780
				'site_name'       => (string) get_option( 'blogname' ),
4781
				'secret_1'        => $secrets['secret_1'],
4782
				'secret_2'        => $secrets['secret_2'],
4783
				'site_lang'       => get_locale(),
4784
				'timeout'         => $timeout,
4785
				'stats_id'        => $stats_id,
4786
				'state'           => get_current_user_id(),
4787
			),
4788
			'headers' => array(
4789
				'Accept' => 'application/json',
4790
			),
4791
			'timeout' => $timeout,
4792
		);
4793
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4794
4795
		// Make sure the response is valid and does not contain any Jetpack errors
4796
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4797
		if ( is_wp_error( $registration_details ) ) {
4798
			return $registration_details;
4799
		} elseif ( ! $registration_details ) {
4800
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
4801
		}
4802
4803 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4804
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
4805
		}
4806
4807
		if ( isset( $registration_details->jetpack_public ) ) {
4808
			$jetpack_public = (int) $registration_details->jetpack_public;
4809
		} else {
4810
			$jetpack_public = false;
4811
		}
4812
4813
		Jetpack_Options::update_options(
4814
			array(
4815
				'id'         => (int)    $registration_details->jetpack_id,
4816
				'blog_token' => (string) $registration_details->jetpack_secret,
4817
				'public'     => $jetpack_public,
4818
			)
4819
		);
4820
4821
		/**
4822
		 * Fires when a site is registered on WordPress.com.
4823
		 *
4824
		 * @since 3.7.0
4825
		 *
4826
		 * @param int $json->jetpack_id Jetpack Blog ID.
4827
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4828
		 * @param int|bool $jetpack_public Is the site public.
4829
		 */
4830
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
4831
4832
		// Initialize Jump Start for the first and only time.
4833
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4834
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4835
4836
			$jetpack = Jetpack::init();
4837
4838
			$jetpack->stat( 'jumpstart', 'unique-views' );
4839
			$jetpack->do_stats( 'server_side' );
4840
		};
4841
4842
		return true;
4843
	}
4844
4845
	/**
4846
	 * If the db version is showing something other that what we've got now, bump it to current.
4847
	 *
4848
	 * @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...
4849
	 */
4850
	public static function maybe_set_version_option() {
4851
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4852
		if ( JETPACK__VERSION != $version ) {
4853
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4854
4855
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4856
				/** This action is documented in class.jetpack.php */
4857
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4858
			}
4859
4860
			return true;
4861
		}
4862
		return false;
4863
	}
4864
4865
/* Client Server API */
4866
4867
	/**
4868
	 * Loads the Jetpack XML-RPC client
4869
	 */
4870
	public static function load_xml_rpc_client() {
4871
		require_once ABSPATH . WPINC . '/class-IXR.php';
4872
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4873
	}
4874
4875
	/**
4876
	 * Resets the saved authentication state in between testing requests.
4877
	 */
4878
	public function reset_saved_auth_state() {
4879
		$this->xmlrpc_verification = null;
4880
		$this->rest_authentication_status = null;
4881
	}
4882
4883
	function verify_xml_rpc_signature() {
4884
		if ( $this->xmlrpc_verification ) {
4885
			return $this->xmlrpc_verification;
4886
		}
4887
4888
		// It's not for us
4889
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4890
			return false;
4891
		}
4892
4893
		@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...
4894
		if (
4895
			empty( $token_key )
4896
		||
4897
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4898
		) {
4899
			return false;
4900
		}
4901
4902
		if ( '0' === $user_id ) {
4903
			$token_type = 'blog';
4904
			$user_id = 0;
4905
		} else {
4906
			$token_type = 'user';
4907
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4908
				return false;
4909
			}
4910
			$user_id = (int) $user_id;
4911
4912
			$user = new WP_User( $user_id );
4913
			if ( ! $user || ! $user->exists() ) {
4914
				return false;
4915
			}
4916
		}
4917
4918
		$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...
4919
		if ( ! $token ) {
4920
			return false;
4921
		}
4922
4923
		$token_check = "$token_key.";
4924
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4925
			return false;
4926
		}
4927
4928
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4929
4930
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4931
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4932
			$post_data   = $_POST;
4933
			$file_hashes = array();
4934
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4935
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4936
					continue;
4937
				}
4938
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4939
				$file_hashes[$post_data_key] = $post_data_value;
4940
			}
4941
4942
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4943
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4944
				$post_data[$post_data_key] = $post_data_value;
4945
			}
4946
4947
			ksort( $post_data );
4948
4949
			$body = http_build_query( stripslashes_deep( $post_data ) );
4950
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4951
			$body = file_get_contents( 'php://input' );
4952
		} else {
4953
			$body = null;
4954
		}
4955
4956
		$signature = $jetpack_signature->sign_current_request(
4957
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4958
		);
4959
4960
		if ( ! $signature ) {
4961
			return false;
4962
		} else if ( is_wp_error( $signature ) ) {
4963
			return $signature;
4964
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4965
			return false;
4966
		}
4967
4968
		$timestamp = (int) $_GET['timestamp'];
4969
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4970
4971
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4972
			return false;
4973
		}
4974
4975
		$this->xmlrpc_verification = array(
4976
			'type'    => $token_type,
4977
			'user_id' => $token->external_user_id,
4978
		);
4979
4980
		return $this->xmlrpc_verification;
4981
	}
4982
4983
	/**
4984
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4985
	 */
4986
	function authenticate_jetpack( $user, $username, $password ) {
4987
		if ( is_a( $user, 'WP_User' ) ) {
4988
			return $user;
4989
		}
4990
4991
		$token_details = $this->verify_xml_rpc_signature();
4992
4993
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4994
			return $user;
4995
		}
4996
4997
		if ( 'user' !== $token_details['type'] ) {
4998
			return $user;
4999
		}
5000
5001
		if ( ! $token_details['user_id'] ) {
5002
			return $user;
5003
		}
5004
5005
		nocache_headers();
5006
5007
		return new WP_User( $token_details['user_id'] );
5008
	}
5009
5010
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5011
	// Uses the existing XMLRPC request signing implementation.
5012
	function wp_rest_authenticate( $user ) {
5013
		if ( ! empty( $user ) ) {
5014
			// Another authentication method is in effect.
5015
			return $user;
5016
		}
5017
5018
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5019
			// Nothing to do for this authentication method.
5020
			return null;
5021
		}
5022
5023
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5024
			// Nothing to do for this authentication method.
5025
			return null;
5026
		}
5027
5028
		// Ensure that we always have the request body available.  At this
5029
		// point, the WP REST API code to determine the request body has not
5030
		// run yet.  That code may try to read from 'php://input' later, but
5031
		// this can only be done once per request in PHP versions prior to 5.6.
5032
		// So we will go ahead and perform this read now if needed, and save
5033
		// the request body where both the Jetpack signature verification code
5034
		// and the WP REST API code can see it.
5035
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5036
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5037
		}
5038
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5039
5040
		// Only support specific request parameters that have been tested and
5041
		// are known to work with signature verification.  A different method
5042
		// can be passed to the WP REST API via the '?_method=' parameter if
5043
		// needed.
5044
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5045
			$this->rest_authentication_status = new WP_Error(
5046
				'rest_invalid_request',
5047
				__( 'This request method is not supported.', 'jetpack' ),
5048
				array( 'status' => 400 )
5049
			);
5050
			return null;
5051
		}
5052
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5053
			$this->rest_authentication_status = new WP_Error(
5054
				'rest_invalid_request',
5055
				__( 'This request method does not support body parameters.', 'jetpack' ),
5056
				array( 'status' => 400 )
5057
			);
5058
			return null;
5059
		}
5060
5061
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
5062
			$content_type = $_SERVER['CONTENT_TYPE'];
5063
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
5064
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
5065
		}
5066
5067
		if (
5068
			isset( $content_type ) &&
5069
			$content_type !== 'application/x-www-form-urlencoded' &&
5070
			$content_type !== 'application/json'
5071
		) {
5072
			$this->rest_authentication_status = new WP_Error(
5073
				'rest_invalid_request',
5074
				__( 'This Content-Type is not supported.', 'jetpack' ),
5075
				array( 'status' => 400 )
5076
			);
5077
			return null;
5078
		}
5079
5080
		$verified = $this->verify_xml_rpc_signature();
5081
5082
		if ( is_wp_error( $verified ) ) {
5083
			$this->rest_authentication_status = $verified;
5084
			return null;
5085
		}
5086
5087
		if (
5088
			$verified &&
5089
			isset( $verified['type'] ) &&
5090
			'user' === $verified['type'] &&
5091
			! empty( $verified['user_id'] )
5092
		) {
5093
			// Authentication successful.
5094
			$this->rest_authentication_status = true;
5095
			return $verified['user_id'];
5096
		}
5097
5098
		// Something else went wrong.  Probably a signature error.
5099
		$this->rest_authentication_status = new WP_Error(
5100
			'rest_invalid_signature',
5101
			__( 'The request is not signed correctly.', 'jetpack' ),
5102
			array( 'status' => 400 )
5103
		);
5104
		return null;
5105
	}
5106
5107
	/**
5108
	 * Report authentication status to the WP REST API.
5109
	 *
5110
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5111
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5112
	 */
5113
	public function wp_rest_authentication_errors( $value ) {
5114
		if ( $value !== null ) {
5115
			return $value;
5116
		}
5117
		return $this->rest_authentication_status;
5118
	}
5119
5120
	function add_nonce( $timestamp, $nonce ) {
5121
		global $wpdb;
5122
		static $nonces_used_this_request = array();
5123
5124
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5125
			return $nonces_used_this_request["$timestamp:$nonce"];
5126
		}
5127
5128
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5129
		$timestamp = (int) $timestamp;
5130
		$nonce     = esc_sql( $nonce );
5131
5132
		// Raw query so we can avoid races: add_option will also update
5133
		$show_errors = $wpdb->show_errors( false );
5134
5135
		$old_nonce = $wpdb->get_row(
5136
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5137
		);
5138
5139
		if ( is_null( $old_nonce ) ) {
5140
			$return = $wpdb->query(
5141
				$wpdb->prepare(
5142
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5143
					"jetpack_nonce_{$timestamp}_{$nonce}",
5144
					time(),
5145
					'no'
5146
				)
5147
			);
5148
		} else {
5149
			$return = false;
5150
		}
5151
5152
		$wpdb->show_errors( $show_errors );
5153
5154
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5155
5156
		return $return;
5157
	}
5158
5159
	/**
5160
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5161
	 * Capture it here so we can verify the signature later.
5162
	 */
5163
	function xmlrpc_methods( $methods ) {
5164
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5165
		return $methods;
5166
	}
5167
5168
	function public_xmlrpc_methods( $methods ) {
5169
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5170
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5171
		}
5172
		return $methods;
5173
	}
5174
5175
	function jetpack_getOptions( $args ) {
5176
		global $wp_xmlrpc_server;
5177
5178
		$wp_xmlrpc_server->escape( $args );
5179
5180
		$username	= $args[1];
5181
		$password	= $args[2];
5182
5183
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5184
			return $wp_xmlrpc_server->error;
5185
		}
5186
5187
		$options = array();
5188
		$user_data = $this->get_connected_user_data();
5189
		if ( is_array( $user_data ) ) {
5190
			$options['jetpack_user_id'] = array(
5191
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5192
				'readonly'      => true,
5193
				'value'         => $user_data['ID'],
5194
			);
5195
			$options['jetpack_user_login'] = array(
5196
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5197
				'readonly'      => true,
5198
				'value'         => $user_data['login'],
5199
			);
5200
			$options['jetpack_user_email'] = array(
5201
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5202
				'readonly'      => true,
5203
				'value'         => $user_data['email'],
5204
			);
5205
			$options['jetpack_user_site_count'] = array(
5206
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5207
				'readonly'      => true,
5208
				'value'         => $user_data['site_count'],
5209
			);
5210
		}
5211
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5212
		$args = stripslashes_deep( $args );
5213
		return $wp_xmlrpc_server->wp_getOptions( $args );
5214
	}
5215
5216
	function xmlrpc_options( $options ) {
5217
		$jetpack_client_id = false;
5218
		if ( self::is_active() ) {
5219
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5220
		}
5221
		$options['jetpack_version'] = array(
5222
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5223
				'readonly'      => true,
5224
				'value'         => JETPACK__VERSION,
5225
		);
5226
5227
		$options['jetpack_client_id'] = array(
5228
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5229
				'readonly'      => true,
5230
				'value'         => $jetpack_client_id,
5231
		);
5232
		return $options;
5233
	}
5234
5235
	public static function clean_nonces( $all = false ) {
5236
		global $wpdb;
5237
5238
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5239
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5240
5241
		if ( true !== $all ) {
5242
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5243
			$sql_args[] = time() - 3600;
5244
		}
5245
5246
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5247
5248
		$sql = $wpdb->prepare( $sql, $sql_args );
5249
5250
		for ( $i = 0; $i < 1000; $i++ ) {
5251
			if ( ! $wpdb->query( $sql ) ) {
5252
				break;
5253
			}
5254
		}
5255
	}
5256
5257
	/**
5258
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5259
	 * SET: state( $key, $value );
5260
	 * GET: $value = state( $key );
5261
	 *
5262
	 * @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...
5263
	 * @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...
5264
	 * @param bool $restate private
5265
	 */
5266
	public static function state( $key = null, $value = null, $restate = false ) {
5267
		static $state = array();
5268
		static $path, $domain;
5269
		if ( ! isset( $path ) ) {
5270
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5271
			$admin_url = Jetpack::admin_url();
5272
			$bits      = parse_url( $admin_url );
5273
5274
			if ( is_array( $bits ) ) {
5275
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5276
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5277
			} else {
5278
				$path = $domain = null;
5279
			}
5280
		}
5281
5282
		// Extract state from cookies and delete cookies
5283
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5284
			$yum = $_COOKIE[ 'jetpackState' ];
5285
			unset( $_COOKIE[ 'jetpackState' ] );
5286
			foreach ( $yum as $k => $v ) {
5287
				if ( strlen( $v ) )
5288
					$state[ $k ] = $v;
5289
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5290
			}
5291
		}
5292
5293
		if ( $restate ) {
5294
			foreach ( $state as $k => $v ) {
5295
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5296
			}
5297
			return;
5298
		}
5299
5300
		// Get a state variable
5301
		if ( isset( $key ) && ! isset( $value ) ) {
5302
			if ( array_key_exists( $key, $state ) )
5303
				return $state[ $key ];
5304
			return null;
5305
		}
5306
5307
		// Set a state variable
5308
		if ( isset ( $key ) && isset( $value ) ) {
5309
			if( is_array( $value ) && isset( $value[0] ) ) {
5310
				$value = $value[0];
5311
			}
5312
			$state[ $key ] = $value;
5313
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5314
		}
5315
	}
5316
5317
	public static function restate() {
5318
		Jetpack::state( null, null, true );
5319
	}
5320
5321
	public static function check_privacy( $file ) {
5322
		static $is_site_publicly_accessible = null;
5323
5324
		if ( is_null( $is_site_publicly_accessible ) ) {
5325
			$is_site_publicly_accessible = false;
5326
5327
			Jetpack::load_xml_rpc_client();
5328
			$rpc = new Jetpack_IXR_Client();
5329
5330
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5331
			if ( $success ) {
5332
				$response = $rpc->getResponse();
5333
				if ( $response ) {
5334
					$is_site_publicly_accessible = true;
5335
				}
5336
			}
5337
5338
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5339
		}
5340
5341
		if ( $is_site_publicly_accessible ) {
5342
			return;
5343
		}
5344
5345
		$module_slug = self::get_module_slug( $file );
5346
5347
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5348
		if ( ! $privacy_checks ) {
5349
			$privacy_checks = $module_slug;
5350
		} else {
5351
			$privacy_checks .= ",$module_slug";
5352
		}
5353
5354
		Jetpack::state( 'privacy_checks', $privacy_checks );
5355
	}
5356
5357
	/**
5358
	 * Helper method for multicall XMLRPC.
5359
	 */
5360
	public static function xmlrpc_async_call() {
5361
		global $blog_id;
5362
		static $clients = array();
5363
5364
		$client_blog_id = is_multisite() ? $blog_id : 0;
5365
5366
		if ( ! isset( $clients[$client_blog_id] ) ) {
5367
			Jetpack::load_xml_rpc_client();
5368
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5369
			if ( function_exists( 'ignore_user_abort' ) ) {
5370
				ignore_user_abort( true );
5371
			}
5372
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5373
		}
5374
5375
		$args = func_get_args();
5376
5377
		if ( ! empty( $args[0] ) ) {
5378
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5379
		} elseif ( is_multisite() ) {
5380
			foreach ( $clients as $client_blog_id => $client ) {
5381
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5382
					continue;
5383
				}
5384
5385
				$switch_success = switch_to_blog( $client_blog_id, true );
5386
				if ( ! $switch_success ) {
5387
					continue;
5388
				}
5389
5390
				flush();
5391
				$client->query();
5392
5393
				restore_current_blog();
5394
			}
5395
		} else {
5396
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5397
				flush();
5398
				$clients[0]->query();
5399
			}
5400
		}
5401
	}
5402
5403
	public static function staticize_subdomain( $url ) {
5404
5405
		// Extract hostname from URL
5406
		$host = parse_url( $url, PHP_URL_HOST );
5407
5408
		// Explode hostname on '.'
5409
		$exploded_host = explode( '.', $host );
5410
5411
		// Retrieve the name and TLD
5412
		if ( count( $exploded_host ) > 1 ) {
5413
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5414
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5415
			// Rebuild domain excluding subdomains
5416
			$domain = $name . '.' . $tld;
5417
		} else {
5418
			$domain = $host;
5419
		}
5420
		// Array of Automattic domains
5421
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5422
5423
		// Return $url if not an Automattic domain
5424
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5425
			return $url;
5426
		}
5427
5428
		if ( is_ssl() ) {
5429
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5430
		}
5431
5432
		srand( crc32( basename( $url ) ) );
5433
		$static_counter = rand( 0, 2 );
5434
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5435
5436
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5437
	}
5438
5439
/* JSON API Authorization */
5440
5441
	/**
5442
	 * Handles the login action for Authorizing the JSON API
5443
	 */
5444
	function login_form_json_api_authorization() {
5445
		$this->verify_json_api_authorization_request();
5446
5447
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5448
5449
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5450
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5451
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5452
	}
5453
5454
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5455
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5456
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5457
			return $url;
5458
		}
5459
5460
		$parsed_url = parse_url( $url );
5461
		$url = strtok( $url, '?' );
5462
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5463
		if ( ! empty( $parsed_url['query'] ) )
5464
			$url .= "&{$parsed_url['query']}";
5465
5466
		return $url;
5467
	}
5468
5469
	// Make sure the POSTed request is handled by the same action
5470
	function preserve_action_in_login_form_for_json_api_authorization() {
5471
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5472
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5473
	}
5474
5475
	// If someone logs in to approve API access, store the Access Code in usermeta
5476
	function store_json_api_authorization_token( $user_login, $user ) {
5477
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5478
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5479
		$token = wp_generate_password( 32, false );
5480
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5481
	}
5482
5483
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5484
	function allow_wpcom_public_api_domain( $domains ) {
5485
		$domains[] = 'public-api.wordpress.com';
5486
		return $domains;
5487
	}
5488
5489
	// Add the Access Code details to the public-api.wordpress.com redirect
5490
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5491
		return add_query_arg(
5492
			urlencode_deep(
5493
				array(
5494
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5495
					'jetpack-user-id' => (int) $user->ID,
5496
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5497
				)
5498
			),
5499
			$redirect_to
5500
		);
5501
	}
5502
5503
5504
	/**
5505
	 * Verifies the request by checking the signature
5506
	 *
5507
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5508
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5509
	 *
5510
	 * @param null|array $environment
5511
	 */
5512
	function verify_json_api_authorization_request( $environment = null ) {
5513
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5514
5515
		$environment = is_null( $environment )
5516
			? $_REQUEST
5517
			: $environment;
5518
5519
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envToken is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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