Completed
Push — add/connection-banner-to-dashb... ( d32723 )
by
unknown
11:40
created

Jetpack::jetpack_connection_banner_callback()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 10
rs 9.4285
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_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
567
568
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
569
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
570
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
571
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
572
573
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
574
575
		/**
576
		 * These actions run checks to load additional files.
577
		 * They check for external files or plugins, so they need to run as late as possible.
578
		 */
579
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
580
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
581
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
582
583
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
584
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
585
586
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
587
588
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
589
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
590
591
		// A filter to control all just in time messages
592
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
593
594
		// Update the Jetpack plan from API on heartbeats
595
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
596
597
		/**
598
		 * This is the hack to concatinate all css files into one.
599
		 * For description and reasoning see the implode_frontend_css method
600
		 *
601
		 * Super late priority so we catch all the registered styles
602
		 */
603
		if( !is_admin() ) {
604
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
605
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
606
		}
607
608
		/**
609
		 * These are sync actions that we need to keep track of for jitms
610
		 */
611
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
612
	}
613
614
	function jetpack_track_last_sync_callback( $params ) {
615
		if ( is_array( $params ) && isset( $params[0] ) ) {
616
			$option = $params[0];
617
			if ( 'active_plugins' === $option ) {
618
				// use the cache if we can, but not terribly important if it gets evicted
619
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
620
			}
621
		}
622
623
		return $params;
624
	}
625
626
	function jetpack_connection_banner_callback() {
627
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
628
629
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
630
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
631
			wp_send_json_success();
632
		}
633
		
634
		wp_die();
635
	}
636
	
637
	function jetpack_admin_ajax_tracks_callback() {
638
		// Check for nonce
639
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
640
			wp_die( 'Permissions check failed.' );
641
		}
642
643
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
644
			wp_die( 'No valid event name or type.' );
645
		}
646
647
		$tracks_data = array();
648
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
649
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
650
		}
651
652
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
653
		wp_send_json_success();
654
		wp_die();
655
	}
656
657
	/**
658
	 * The callback for the JITM ajax requests.
659
	 */
660
	function jetpack_jitm_ajax_callback() {
661
		// Check for nonce
662
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
663
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
664
		}
665
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
666
			$module_slug = $_REQUEST['jitmModule'];
667
			Jetpack::log( 'activate', $module_slug );
668
			Jetpack::activate_module( $module_slug, false, false );
669
			Jetpack::state( 'message', 'no_message' );
670
671
			//A Jetpack module is being activated through a JITM, track it
672
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
673
			$this->do_stats( 'server_side' );
674
675
			wp_send_json_success();
676
		}
677
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
678
			// get the hide_jitm options array
679
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
680
			$module_slug = $_REQUEST['jitmModule'];
681
682
			if( ! $jetpack_hide_jitm ) {
683
				$jetpack_hide_jitm = array(
684
					$module_slug => 'hide'
685
				);
686
			} else {
687
				$jetpack_hide_jitm[$module_slug] = 'hide';
688
			}
689
690
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
691
692
			//jitm is being dismissed forever, track it
693
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
694
			$this->do_stats( 'server_side' );
695
696
			wp_send_json_success();
697
		}
698 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
699
			$module_slug = $_REQUEST['jitmModule'];
700
701
			// User went to WordPress.com, track this
702
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
703
			$this->do_stats( 'server_side' );
704
705
			wp_send_json_success();
706
		}
707 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
708
			$track = $_REQUEST['jitmModule'];
709
710
			// User is viewing JITM, track it.
711
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
712
			$this->do_stats( 'server_side' );
713
714
			wp_send_json_success();
715
		}
716
	}
717
718
	/**
719
	 * If there are any stats that need to be pushed, but haven't been, push them now.
720
	 */
721
	function __destruct() {
722
		if ( ! empty( $this->stats ) ) {
723
			$this->do_stats( 'server_side' );
724
		}
725
	}
726
727
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
728
		switch( $cap ) {
729
			case 'jetpack_connect' :
730
			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...
731
				if ( Jetpack::is_development_mode() ) {
732
					$caps = array( 'do_not_allow' );
733
					break;
734
				}
735
				/**
736
				 * Pass through. If it's not development mode, these should match disconnect.
737
				 * Let users disconnect if it's development mode, just in case things glitch.
738
				 */
739
			case 'jetpack_disconnect' :
740
				/**
741
				 * In multisite, can individual site admins manage their own connection?
742
				 *
743
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
744
				 */
745
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
746
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
747
						/**
748
						 * We need to update the option name -- it's terribly unclear which
749
						 * direction the override goes.
750
						 *
751
						 * @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...
752
						 */
753
						$caps = array( 'do_not_allow' );
754
						break;
755
					}
756
				}
757
758
				$caps = array( 'manage_options' );
759
				break;
760
			case 'jetpack_manage_modules' :
761
			case 'jetpack_activate_modules' :
762
			case 'jetpack_deactivate_modules' :
763
				$caps = array( 'manage_options' );
764
				break;
765
			case 'jetpack_configure_modules' :
766
				$caps = array( 'manage_options' );
767
				break;
768
			case 'jetpack_network_admin_page':
769
			case 'jetpack_network_settings_page':
770
				$caps = array( 'manage_network_plugins' );
771
				break;
772
			case 'jetpack_network_sites_page':
773
				$caps = array( 'manage_sites' );
774
				break;
775
			case 'jetpack_admin_page' :
776
				if ( Jetpack::is_development_mode() ) {
777
					$caps = array( 'manage_options' );
778
					break;
779
				} else {
780
					$caps = array( 'read' );
781
				}
782
				break;
783
			case 'jetpack_connect_user' :
784
				if ( Jetpack::is_development_mode() ) {
785
					$caps = array( 'do_not_allow' );
786
					break;
787
				}
788
				$caps = array( 'read' );
789
				break;
790
		}
791
		return $caps;
792
	}
793
794
	function require_jetpack_authentication() {
795
		// Don't let anyone authenticate
796
		$_COOKIE = array();
797
		remove_all_filters( 'authenticate' );
798
		remove_all_actions( 'wp_login_failed' );
799
800
		if ( Jetpack::is_active() ) {
801
			// Allow Jetpack authentication
802
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
803
		}
804
	}
805
806
	/**
807
	 * Load language files
808
	 * @action plugins_loaded
809
	 */
810
	public static function plugin_textdomain() {
811
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
812
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
813
	}
814
815
	/**
816
	 * Register assets for use in various modules and the Jetpack admin page.
817
	 *
818
	 * @uses wp_script_is, wp_register_script, plugins_url
819
	 * @action wp_loaded
820
	 * @return null
821
	 */
822
	public function register_assets() {
823
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
824
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
825
		}
826
827 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
828
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
829
		}
830
831 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
832
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
833
		}
834
835 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
836
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
837
		}
838
839
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
840
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
841
842
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
843
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
844
			if ( ! is_numeric( $fb_app_id ) ) {
845
				$fb_app_id = '';
846
			}
847
			wp_localize_script(
848
				'jetpack-facebook-embed',
849
				'jpfbembed',
850
				array(
851
					'appid' => $fb_app_id,
852
					'locale' => $this->get_locale(),
853
				)
854
			);
855
		}
856
857
		/**
858
		 * As jetpack_register_genericons is by default fired off a hook,
859
		 * the hook may have already fired by this point.
860
		 * So, let's just trigger it manually.
861
		 */
862
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
863
		jetpack_register_genericons();
864
865
		/**
866
		 * Register the social logos
867
		 */
868
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
869
		jetpack_register_social_logos();
870
871 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
872
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
873
	}
874
875
	/**
876
	 * Guess locale from language code.
877
	 *
878
	 * @param string $lang Language code.
879
	 * @return string|bool
880
	 */
881 View Code Duplication
	function guess_locale_from_lang( $lang ) {
882
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
883
			return 'en_US';
884
		}
885
886
		if ( ! class_exists( 'GP_Locales' ) ) {
887
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
888
				return false;
889
			}
890
891
			require JETPACK__GLOTPRESS_LOCALES_PATH;
892
		}
893
894
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
895
			// WP.com: get_locale() returns 'it'
896
			$locale = GP_Locales::by_slug( $lang );
897
		} else {
898
			// Jetpack: get_locale() returns 'it_IT';
899
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
900
		}
901
902
		if ( ! $locale ) {
903
			return false;
904
		}
905
906
		if ( empty( $locale->facebook_locale ) ) {
907
			if ( empty( $locale->wp_locale ) ) {
908
				return false;
909
			} else {
910
				// Facebook SDK is smart enough to fall back to en_US if a
911
				// locale isn't supported. Since supported Facebook locales
912
				// can fall out of sync, we'll attempt to use the known
913
				// wp_locale value and rely on said fallback.
914
				return $locale->wp_locale;
915
			}
916
		}
917
918
		return $locale->facebook_locale;
919
	}
920
921
	/**
922
	 * Get the locale.
923
	 *
924
	 * @return string|bool
925
	 */
926
	function get_locale() {
927
		$locale = $this->guess_locale_from_lang( get_locale() );
928
929
		if ( ! $locale ) {
930
			$locale = 'en_US';
931
		}
932
933
		return $locale;
934
	}
935
936
	/**
937
	 * Device Pixels support
938
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
939
	 */
940
	function devicepx() {
941
		if ( Jetpack::is_active() ) {
942
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
943
		}
944
	}
945
946
	/**
947
	 * Return the network_site_url so that .com knows what network this site is a part of.
948
	 * @param  bool $option
949
	 * @return string
950
	 */
951
	public function jetpack_main_network_site_option( $option ) {
952
		return network_site_url();
953
	}
954
	/**
955
	 * Network Name.
956
	 */
957
	static function network_name( $option = null ) {
958
		global $current_site;
959
		return $current_site->site_name;
960
	}
961
	/**
962
	 * Does the network allow new user and site registrations.
963
	 * @return string
964
	 */
965
	static function network_allow_new_registrations( $option = null ) {
966
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
967
	}
968
	/**
969
	 * Does the network allow admins to add new users.
970
	 * @return boolian
971
	 */
972
	static function network_add_new_users( $option = null ) {
973
		return (bool) get_site_option( 'add_new_users' );
974
	}
975
	/**
976
	 * File upload psace left per site in MB.
977
	 *  -1 means NO LIMIT.
978
	 * @return number
979
	 */
980
	static function network_site_upload_space( $option = null ) {
981
		// value in MB
982
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
983
	}
984
985
	/**
986
	 * Network allowed file types.
987
	 * @return string
988
	 */
989
	static function network_upload_file_types( $option = null ) {
990
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
991
	}
992
993
	/**
994
	 * Maximum file upload size set by the network.
995
	 * @return number
996
	 */
997
	static function network_max_upload_file_size( $option = null ) {
998
		// value in KB
999
		return get_site_option( 'fileupload_maxk', 300 );
1000
	}
1001
1002
	/**
1003
	 * Lets us know if a site allows admins to manage the network.
1004
	 * @return array
1005
	 */
1006
	static function network_enable_administration_menus( $option = null ) {
1007
		return get_site_option( 'menu_items' );
1008
	}
1009
1010
	/**
1011
	 * If a user has been promoted to or demoted from admin, we need to clear the
1012
	 * jetpack_other_linked_admins transient.
1013
	 *
1014
	 * @since 4.3.2
1015
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1016
	 *
1017
	 * @param int    $user_id   The user ID whose role changed.
1018
	 * @param string $role      The new role.
1019
	 * @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...
1020
	 */
1021
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1022
		if ( 'administrator' == $role
1023
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1024
			|| is_null( $old_roles )
1025
		) {
1026
			delete_transient( 'jetpack_other_linked_admins' );
1027
		}
1028
	}
1029
1030
	/**
1031
	 * Checks to see if there are any other users available to become primary
1032
	 * Users must both:
1033
	 * - Be linked to wpcom
1034
	 * - Be an admin
1035
	 *
1036
	 * @return mixed False if no other users are linked, Int if there are.
1037
	 */
1038
	static function get_other_linked_admins() {
1039
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1040
1041
		if ( false === $other_linked_users ) {
1042
			$admins = get_users( array( 'role' => 'administrator' ) );
1043
			if ( count( $admins ) > 1 ) {
1044
				$available = array();
1045
				foreach ( $admins as $admin ) {
1046
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1047
						$available[] = $admin->ID;
1048
					}
1049
				}
1050
1051
				$count_connected_admins = count( $available );
1052
				if ( count( $available ) > 1 ) {
1053
					$other_linked_users = $count_connected_admins;
1054
				} else {
1055
					$other_linked_users = 0;
1056
				}
1057
			} else {
1058
				$other_linked_users = 0;
1059
			}
1060
1061
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1062
		}
1063
1064
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1065
	}
1066
1067
	/**
1068
	 * Return whether we are dealing with a multi network setup or not.
1069
	 * The reason we are type casting this is because we want to avoid the situation where
1070
	 * the result is false since when is_main_network_option return false it cases
1071
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1072
	 * database which could be set to anything as opposed to what this function returns.
1073
	 * @param  bool  $option
1074
	 *
1075
	 * @return boolean
1076
	 */
1077
	public function is_main_network_option( $option ) {
1078
		// return '1' or ''
1079
		return (string) (bool) Jetpack::is_multi_network();
1080
	}
1081
1082
	/**
1083
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1084
	 *
1085
	 * @param  string  $option
1086
	 * @return boolean
1087
	 */
1088
	public function is_multisite( $option ) {
1089
		return (string) (bool) is_multisite();
1090
	}
1091
1092
	/**
1093
	 * Implemented since there is no core is multi network function
1094
	 * Right now there is no way to tell if we which network is the dominant network on the system
1095
	 *
1096
	 * @since  3.3
1097
	 * @return boolean
1098
	 */
1099
	public static function is_multi_network() {
1100
		global  $wpdb;
1101
1102
		// if we don't have a multi site setup no need to do any more
1103
		if ( ! is_multisite() ) {
1104
			return false;
1105
		}
1106
1107
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1108
		if ( $num_sites > 1 ) {
1109
			return true;
1110
		} else {
1111
			return false;
1112
		}
1113
	}
1114
1115
	/**
1116
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1117
	 * @return null
1118
	 */
1119
	function update_jetpack_main_network_site_option() {
1120
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1121
	}
1122
	/**
1123
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1124
	 *
1125
	 */
1126
	function update_jetpack_network_settings() {
1127
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1128
		// Only sync this info for the main network site.
1129
	}
1130
1131
	/**
1132
	 * Get back if the current site is single user site.
1133
	 *
1134
	 * @return bool
1135
	 */
1136
	public static function is_single_user_site() {
1137
		global $wpdb;
1138
1139 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1140
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1141
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1142
		}
1143
		return 1 === (int) $some_users;
1144
	}
1145
1146
	/**
1147
	 * Returns true if the site has file write access false otherwise.
1148
	 * @return string ( '1' | '0' )
1149
	 **/
1150
	public static function file_system_write_access() {
1151
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1152
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1153
		}
1154
1155
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1156
1157
		$filesystem_method = get_filesystem_method();
1158
		if ( $filesystem_method === 'direct' ) {
1159
			return 1;
1160
		}
1161
1162
		ob_start();
1163
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1164
		ob_end_clean();
1165
		if ( $filesystem_credentials_are_stored ) {
1166
			return 1;
1167
		}
1168
		return 0;
1169
	}
1170
1171
	/**
1172
	 * Finds out if a site is using a version control system.
1173
	 * @return string ( '1' | '0' )
1174
	 **/
1175
	public static function is_version_controlled() {
1176
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1177
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1178
	}
1179
1180
	/**
1181
	 * Determines whether the current theme supports featured images or not.
1182
	 * @return string ( '1' | '0' )
1183
	 */
1184
	public static function featured_images_enabled() {
1185
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1186
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1187
	}
1188
1189
	/**
1190
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1191
	 *
1192
	 * @deprecated 4.7 use get_avatar_url instead.
1193
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1194
	 * @param int $size Size of the avatar image
1195
	 * @param string $default URL to a default image to use if no avatar is available
1196
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1197
	 *
1198
	 * @return array
1199
	 */
1200
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1201
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1202
		return get_avatar_url( $id_or_email, array(
1203
			'size' => $size,
1204
			'default' => $default,
1205
			'force_default' => $force_display,
1206
		) );
1207
	}
1208
1209
	/**
1210
	 * jetpack_updates is saved in the following schema:
1211
	 *
1212
	 * array (
1213
	 *      'plugins'                       => (int) Number of plugin updates available.
1214
	 *      'themes'                        => (int) Number of theme updates available.
1215
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1216
	 *      'translations'                  => (int) Number of translation updates available.
1217
	 *      'total'                         => (int) Total of all available updates.
1218
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1219
	 * )
1220
	 * @return array
1221
	 */
1222
	public static function get_updates() {
1223
		$update_data = wp_get_update_data();
1224
1225
		// Stores the individual update counts as well as the total count.
1226
		if ( isset( $update_data['counts'] ) ) {
1227
			$updates = $update_data['counts'];
1228
		}
1229
1230
		// If we need to update WordPress core, let's find the latest version number.
1231 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1232
			$cur = get_preferred_from_update_core();
1233
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1234
				$updates['wp_update_version'] = $cur->current;
1235
			}
1236
		}
1237
		return isset( $updates ) ? $updates : array();
1238
	}
1239
1240
	public static function get_update_details() {
1241
		$update_details = array(
1242
			'update_core' => get_site_transient( 'update_core' ),
1243
			'update_plugins' => get_site_transient( 'update_plugins' ),
1244
			'update_themes' => get_site_transient( 'update_themes' ),
1245
		);
1246
		return $update_details;
1247
	}
1248
1249
	public static function refresh_update_data() {
1250
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1251
1252
	}
1253
1254
	public static function refresh_theme_data() {
1255
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1256
	}
1257
1258
	/**
1259
	 * Is Jetpack active?
1260
	 */
1261
	public static function is_active() {
1262
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1263
	}
1264
1265
	/**
1266
	 * Make an API call to WordPress.com for plan status
1267
	 *
1268
	 * @uses Jetpack_Options::get_option()
1269
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1270
	 * @uses update_option()
1271
	 *
1272
	 * @access public
1273
	 * @static
1274
	 *
1275
	 * @return bool True if plan is updated, false if no update
1276
	 */
1277
	public static function refresh_active_plan_from_wpcom() {
1278
		// Make the API request
1279
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1280
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1281
1282
		// Bail if there was an error or malformed response
1283
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1284
			return false;
1285
		}
1286
1287
		// Decode the results
1288
		$results = json_decode( $response['body'], true );
1289
1290
		// Bail if there were no results or plan details returned
1291
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1292
			return false;
1293
		}
1294
1295
		// Store the option and return true if updated
1296
		return update_option( 'jetpack_active_plan', $results['plan'] );
1297
	}
1298
1299
	/**
1300
	 * Get the plan that this Jetpack site is currently using
1301
	 *
1302
	 * @uses get_option()
1303
	 *
1304
	 * @access public
1305
	 * @static
1306
	 *
1307
	 * @return array Active Jetpack plan details
1308
	 */
1309
	public static function get_active_plan() {
1310
		$plan = get_option( 'jetpack_active_plan', array() );
1311
1312
		// Set the default options
1313
		if ( empty( $plan ) || ( isset( $plan['product_slug'] ) && 'jetpack_free' === $plan['product_slug'] ) ) {
1314
			$plan = wp_parse_args( $plan, array(
1315
				'product_slug' => 'jetpack_free',
1316
				'supports'     => array(),
1317
				'class'        => 'free',
1318
			) );
1319
		}
1320
1321
		// Define what paid modules are supported by personal plans
1322
		$personal_plans = array(
1323
			'jetpack_personal',
1324
			'jetpack_personal_monthly',
1325
			'personal-bundle',
1326
		);
1327
1328
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1329
			$plan['supports'] = array(
1330
				'akismet',
1331
			);
1332
			$plan['class'] = 'personal';
1333
		}
1334
1335
		// Define what paid modules are supported by premium plans
1336
		$premium_plans = array(
1337
			'jetpack_premium',
1338
			'jetpack_premium_monthly',
1339
			'value_bundle',
1340
		);
1341
1342 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1343
			$plan['supports'] = array(
1344
				'videopress',
1345
				'akismet',
1346
				'vaultpress',
1347
				'wordads',
1348
			);
1349
			$plan['class'] = 'premium';
1350
		}
1351
1352
		// Define what paid modules are supported by professional plans
1353
		$business_plans = array(
1354
			'jetpack_business',
1355
			'jetpack_business_monthly',
1356
			'business-bundle',
1357
		);
1358
1359 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1360
			$plan['supports'] = array(
1361
				'videopress',
1362
				'akismet',
1363
				'vaultpress',
1364
				'seo-tools',
1365
				'google-analytics',
1366
				'wordads',
1367
			);
1368
			$plan['class'] = 'business';
1369
		}
1370
1371
		// Make sure we have an array here in the event database data is stale
1372
		if ( ! isset( $plan['supports'] ) ) {
1373
			$plan['supports'] = array();
1374
		}
1375
1376
		return $plan;
1377
	}
1378
1379
	/**
1380
	 * Determine whether the active plan supports a particular feature
1381
	 *
1382
	 * @uses Jetpack::get_active_plan()
1383
	 *
1384
	 * @access public
1385
	 * @static
1386
	 *
1387
	 * @return bool True if plan supports feature, false if not
1388
	 */
1389
	public static function active_plan_supports( $feature ) {
1390
		$plan = Jetpack::get_active_plan();
1391
1392
		if ( in_array( $feature, $plan['supports'] ) ) {
1393
			return true;
1394
		}
1395
1396
		return false;
1397
	}
1398
1399
	/**
1400
	 * Is Jetpack in development (offline) mode?
1401
	 */
1402
	public static function is_development_mode() {
1403
		$development_mode = false;
1404
1405
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1406
			$development_mode = JETPACK_DEV_DEBUG;
1407
		} elseif ( $site_url = site_url() ) {
1408
			$development_mode = false === strpos( $site_url, '.' );
1409
		}
1410
1411
		/**
1412
		 * Filters Jetpack's development mode.
1413
		 *
1414
		 * @see https://jetpack.com/support/development-mode/
1415
		 *
1416
		 * @since 2.2.1
1417
		 *
1418
		 * @param bool $development_mode Is Jetpack's development mode active.
1419
		 */
1420
		return apply_filters( 'jetpack_development_mode', $development_mode );
1421
	}
1422
1423
	/**
1424
	* Get Jetpack development mode notice text and notice class.
1425
	*
1426
	* Mirrors the checks made in Jetpack::is_development_mode
1427
	*
1428
	*/
1429
	public static function show_development_mode_notice() {
1430
		if ( Jetpack::is_development_mode() ) {
1431
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1432
				$notice = sprintf(
1433
					/* translators: %s is a URL */
1434
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1435
					'https://jetpack.com/support/development-mode/'
1436
				);
1437
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1438
				$notice = sprintf(
1439
					/* translators: %s is a URL */
1440
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1441
					'https://jetpack.com/support/development-mode/'
1442
				);
1443
			} else {
1444
				$notice = sprintf(
1445
					/* translators: %s is a URL */
1446
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1447
					'https://jetpack.com/support/development-mode/'
1448
				);
1449
			}
1450
1451
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1452
		}
1453
1454
		// Throw up a notice if using a development version and as for feedback.
1455
		if ( Jetpack::is_development_version() ) {
1456
			/* translators: %s is a URL */
1457
			$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/' );
1458
1459
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1460
		}
1461
		// Throw up a notice if using staging mode
1462
		if ( Jetpack::is_staging_site() ) {
1463
			/* translators: %s is a URL */
1464
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1465
1466
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1467
		}
1468
	}
1469
1470
	/**
1471
	 * Whether Jetpack's version maps to a public release, or a development version.
1472
	 */
1473
	public static function is_development_version() {
1474
		/**
1475
		 * Allows filtering whether this is a development version of Jetpack.
1476
		 *
1477
		 * This filter is especially useful for tests.
1478
		 *
1479
		 * @since 4.3.0
1480
		 *
1481
		 * @param bool $development_version Is this a develoment version of Jetpack?
1482
		 */
1483
		return (bool) apply_filters(
1484
			'jetpack_development_version',
1485
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1486
		);
1487
	}
1488
1489
	/**
1490
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1491
	 */
1492
	public static function is_user_connected( $user_id = false ) {
1493
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1494
		if ( ! $user_id ) {
1495
			return false;
1496
		}
1497
1498
		return (bool) Jetpack_Data::get_access_token( $user_id );
1499
	}
1500
1501
	/**
1502
	 * Get the wpcom user data of the current|specified connected user.
1503
	 */
1504
	public static function get_connected_user_data( $user_id = null ) {
1505
		if ( ! $user_id ) {
1506
			$user_id = get_current_user_id();
1507
		}
1508
1509
		$transient_key = "jetpack_connected_user_data_$user_id";
1510
1511
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1512
			return $cached_user_data;
1513
		}
1514
1515
		Jetpack::load_xml_rpc_client();
1516
		$xml = new Jetpack_IXR_Client( array(
1517
			'user_id' => $user_id,
1518
		) );
1519
		$xml->query( 'wpcom.getUser' );
1520
		if ( ! $xml->isError() ) {
1521
			$user_data = $xml->getResponse();
1522
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1523
			return $user_data;
1524
		}
1525
1526
		return false;
1527
	}
1528
1529
	/**
1530
	 * Get the wpcom email of the current|specified connected user.
1531
	 */
1532 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1533
		if ( ! $user_id ) {
1534
			$user_id = get_current_user_id();
1535
		}
1536
		Jetpack::load_xml_rpc_client();
1537
		$xml = new Jetpack_IXR_Client( array(
1538
			'user_id' => $user_id,
1539
		) );
1540
		$xml->query( 'wpcom.getUserEmail' );
1541
		if ( ! $xml->isError() ) {
1542
			return $xml->getResponse();
1543
		}
1544
		return false;
1545
	}
1546
1547
	/**
1548
	 * Get the wpcom email of the master user.
1549
	 */
1550
	public static function get_master_user_email() {
1551
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1552
		if ( $master_user_id ) {
1553
			return self::get_connected_user_email( $master_user_id );
1554
		}
1555
		return '';
1556
	}
1557
1558
	function current_user_is_connection_owner() {
1559
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1560
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1561
	}
1562
1563
	/**
1564
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1565
	 */
1566
	function extra_oembed_providers() {
1567
		// Cloudup: https://dev.cloudup.com/#oembed
1568
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1569
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1570
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1571
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1572
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1573
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1574
	}
1575
1576
	/**
1577
	 * Synchronize connected user role changes
1578
	 */
1579
	function user_role_change( $user_id ) {
1580
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1581
		Jetpack_Sync_Users::user_role_change( $user_id );
1582
	}
1583
1584
	/**
1585
	 * Loads the currently active modules.
1586
	 */
1587
	public static function load_modules() {
1588
		if ( ! self::is_active() && !self::is_development_mode() ) {
1589
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1590
				return;
1591
			}
1592
		}
1593
1594
		$version = Jetpack_Options::get_option( 'version' );
1595 View Code Duplication
		if ( ! $version ) {
1596
			$version = $old_version = JETPACK__VERSION . ':' . time();
1597
			/** This action is documented in class.jetpack.php */
1598
			do_action( 'updating_jetpack_version', $version, false );
1599
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1600
		}
1601
		list( $version ) = explode( ':', $version );
1602
1603
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1604
1605
		$modules_data = array();
1606
1607
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1608
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1609
			$updated_modules = array();
1610
			foreach ( $modules as $module ) {
1611
				$modules_data[ $module ] = Jetpack::get_module( $module );
1612
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1613
					continue;
1614
				}
1615
1616
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1617
					continue;
1618
				}
1619
1620
				$updated_modules[] = $module;
1621
			}
1622
1623
			$modules = array_diff( $modules, $updated_modules );
1624
		}
1625
1626
		$is_development_mode = Jetpack::is_development_mode();
1627
1628
		foreach ( $modules as $index => $module ) {
1629
			// If we're in dev mode, disable modules requiring a connection
1630
			if ( $is_development_mode ) {
1631
				// Prime the pump if we need to
1632
				if ( empty( $modules_data[ $module ] ) ) {
1633
					$modules_data[ $module ] = Jetpack::get_module( $module );
1634
				}
1635
				// If the module requires a connection, but we're in local mode, don't include it.
1636
				if ( $modules_data[ $module ]['requires_connection'] ) {
1637
					continue;
1638
				}
1639
			}
1640
1641
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1642
				continue;
1643
			}
1644
1645
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1646
				unset( $modules[ $index ] );
1647
				self::update_active_modules( array_values( $modules ) );
1648
				continue;
1649
			}
1650
1651
			/**
1652
			 * Fires when a specific module is loaded.
1653
			 * The dynamic part of the hook, $module, is the module slug.
1654
			 *
1655
			 * @since 1.1.0
1656
			 */
1657
			do_action( 'jetpack_module_loaded_' . $module );
1658
		}
1659
1660
		/**
1661
		 * Fires when all the modules are loaded.
1662
		 *
1663
		 * @since 1.1.0
1664
		 */
1665
		do_action( 'jetpack_modules_loaded' );
1666
1667
		// 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.
1668
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1669
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1670
	}
1671
1672
	/**
1673
	 * Check if Jetpack's REST API compat file should be included
1674
	 * @action plugins_loaded
1675
	 * @return null
1676
	 */
1677
	public function check_rest_api_compat() {
1678
		/**
1679
		 * Filters the list of REST API compat files to be included.
1680
		 *
1681
		 * @since 2.2.5
1682
		 *
1683
		 * @param array $args Array of REST API compat files to include.
1684
		 */
1685
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1686
1687
		if ( function_exists( 'bbpress' ) )
1688
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1689
1690
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1691
			require_once $_jetpack_rest_api_compat_include;
1692
	}
1693
1694
	/**
1695
	 * Gets all plugins currently active in values, regardless of whether they're
1696
	 * traditionally activated or network activated.
1697
	 *
1698
	 * @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...
1699
	 */
1700
	public static function get_active_plugins() {
1701
		$active_plugins = (array) get_option( 'active_plugins', array() );
1702
1703
		if ( is_multisite() ) {
1704
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1705
			// whereas active_plugins stores them in the values.
1706
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1707
			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...
1708
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1709
			}
1710
		}
1711
1712
		sort( $active_plugins );
1713
1714
		return array_unique( $active_plugins );
1715
	}
1716
1717
	/**
1718
	 * Gets and parses additional plugin data to send with the heartbeat data
1719
	 *
1720
	 * @since 3.8.1
1721
	 *
1722
	 * @return array Array of plugin data
1723
	 */
1724
	public static function get_parsed_plugin_data() {
1725
		if ( ! function_exists( 'get_plugins' ) ) {
1726
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1727
		}
1728
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1729
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1730
		$active_plugins = Jetpack::get_active_plugins();
1731
1732
		$plugins = array();
1733
		foreach ( $all_plugins as $path => $plugin_data ) {
1734
			$plugins[ $path ] = array(
1735
					'is_active' => in_array( $path, $active_plugins ),
1736
					'file'      => $path,
1737
					'name'      => $plugin_data['Name'],
1738
					'version'   => $plugin_data['Version'],
1739
					'author'    => $plugin_data['Author'],
1740
			);
1741
		}
1742
1743
		return $plugins;
1744
	}
1745
1746
	/**
1747
	 * Gets and parses theme data to send with the heartbeat data
1748
	 *
1749
	 * @since 3.8.1
1750
	 *
1751
	 * @return array Array of theme data
1752
	 */
1753
	public static function get_parsed_theme_data() {
1754
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1755
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1756
1757
		$themes = array();
1758
		foreach ( $all_themes as $slug => $theme_data ) {
1759
			$theme_headers = array();
1760
			foreach ( $header_keys as $header_key ) {
1761
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1762
			}
1763
1764
			$themes[ $slug ] = array(
1765
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1766
					'slug' => $slug,
1767
					'theme_root' => $theme_data->get_theme_root_uri(),
1768
					'parent' => $theme_data->parent(),
1769
					'headers' => $theme_headers
1770
			);
1771
		}
1772
1773
		return $themes;
1774
	}
1775
1776
	/**
1777
	 * Checks whether a specific plugin is active.
1778
	 *
1779
	 * We don't want to store these in a static variable, in case
1780
	 * there are switch_to_blog() calls involved.
1781
	 */
1782
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1783
		return in_array( $plugin, self::get_active_plugins() );
1784
	}
1785
1786
	/**
1787
	 * Check if Jetpack's Open Graph tags should be used.
1788
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1789
	 *
1790
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1791
	 * @action plugins_loaded
1792
	 * @return null
1793
	 */
1794
	public function check_open_graph() {
1795
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1796
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1797
		}
1798
1799
		$active_plugins = self::get_active_plugins();
1800
1801
		if ( ! empty( $active_plugins ) ) {
1802
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1803
				if ( in_array( $plugin, $active_plugins ) ) {
1804
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1805
					break;
1806
				}
1807
			}
1808
		}
1809
1810
		/**
1811
		 * Allow the addition of Open Graph Meta Tags to all pages.
1812
		 *
1813
		 * @since 2.0.3
1814
		 *
1815
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1816
		 */
1817
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1818
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1819
		}
1820
	}
1821
1822
	/**
1823
	 * Check if Jetpack's Twitter tags should be used.
1824
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1825
	 *
1826
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1827
	 * @action plugins_loaded
1828
	 * @return null
1829
	 */
1830
	public function check_twitter_tags() {
1831
1832
		$active_plugins = self::get_active_plugins();
1833
1834
		if ( ! empty( $active_plugins ) ) {
1835
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1836
				if ( in_array( $plugin, $active_plugins ) ) {
1837
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1838
					break;
1839
				}
1840
			}
1841
		}
1842
1843
		/**
1844
		 * Allow Twitter Card Meta tags to be disabled.
1845
		 *
1846
		 * @since 2.6.0
1847
		 *
1848
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1849
		 */
1850
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1851
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1852
		}
1853
	}
1854
1855
	/**
1856
	 * Allows plugins to submit security reports.
1857
 	 *
1858
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1859
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1860
	 * @param array   $args         See definitions above
1861
	 */
1862
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1863
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1864
	}
1865
1866
/* Jetpack Options API */
1867
1868
	public static function get_option_names( $type = 'compact' ) {
1869
		return Jetpack_Options::get_option_names( $type );
1870
	}
1871
1872
	/**
1873
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1874
 	 *
1875
	 * @param string $name    Option name
1876
	 * @param mixed  $default (optional)
1877
	 */
1878
	public static function get_option( $name, $default = false ) {
1879
		return Jetpack_Options::get_option( $name, $default );
1880
	}
1881
1882
	/**
1883
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1884
 	 *
1885
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1886
	 * @param string $name  Option name
1887
	 * @param mixed  $value Option value
1888
	 */
1889
	public static function update_option( $name, $value ) {
1890
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1891
		return Jetpack_Options::update_option( $name, $value );
1892
	}
1893
1894
	/**
1895
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1896
 	 *
1897
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1898
	 * @param array $array array( option name => option value, ... )
1899
	 */
1900
	public static function update_options( $array ) {
1901
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1902
		return Jetpack_Options::update_options( $array );
1903
	}
1904
1905
	/**
1906
	 * Deletes the given option.  May be passed multiple option names as an array.
1907
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1908
	 *
1909
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1910
	 * @param string|array $names
1911
	 */
1912
	public static function delete_option( $names ) {
1913
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1914
		return Jetpack_Options::delete_option( $names );
1915
	}
1916
1917
	/**
1918
	 * Enters a user token into the user_tokens option
1919
	 *
1920
	 * @param int $user_id
1921
	 * @param string $token
1922
	 * return bool
1923
	 */
1924
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1925
		// not designed for concurrent updates
1926
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1927
		if ( ! is_array( $user_tokens ) )
1928
			$user_tokens = array();
1929
		$user_tokens[$user_id] = $token;
1930
		if ( $is_master_user ) {
1931
			$master_user = $user_id;
1932
			$options     = compact( 'user_tokens', 'master_user' );
1933
		} else {
1934
			$options = compact( 'user_tokens' );
1935
		}
1936
		return Jetpack_Options::update_options( $options );
1937
	}
1938
1939
	/**
1940
	 * Returns an array of all PHP files in the specified absolute path.
1941
	 * Equivalent to glob( "$absolute_path/*.php" ).
1942
	 *
1943
	 * @param string $absolute_path The absolute path of the directory to search.
1944
	 * @return array Array of absolute paths to the PHP files.
1945
	 */
1946
	public static function glob_php( $absolute_path ) {
1947
		if ( function_exists( 'glob' ) ) {
1948
			return glob( "$absolute_path/*.php" );
1949
		}
1950
1951
		$absolute_path = untrailingslashit( $absolute_path );
1952
		$files = array();
1953
		if ( ! $dir = @opendir( $absolute_path ) ) {
1954
			return $files;
1955
		}
1956
1957
		while ( false !== $file = readdir( $dir ) ) {
1958
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1959
				continue;
1960
			}
1961
1962
			$file = "$absolute_path/$file";
1963
1964
			if ( ! is_file( $file ) ) {
1965
				continue;
1966
			}
1967
1968
			$files[] = $file;
1969
		}
1970
1971
		closedir( $dir );
1972
1973
		return $files;
1974
	}
1975
1976
	public static function activate_new_modules( $redirect = false ) {
1977
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1978
			return;
1979
		}
1980
1981
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1982 View Code Duplication
		if ( ! $jetpack_old_version ) {
1983
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1984
			/** This action is documented in class.jetpack.php */
1985
			do_action( 'updating_jetpack_version', $version, false );
1986
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1987
		}
1988
1989
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1990
1991
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1992
			return;
1993
		}
1994
1995
		$active_modules     = Jetpack::get_active_modules();
1996
		$reactivate_modules = array();
1997
		foreach ( $active_modules as $active_module ) {
1998
			$module = Jetpack::get_module( $active_module );
1999
			if ( ! isset( $module['changed'] ) ) {
2000
				continue;
2001
			}
2002
2003
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2004
				continue;
2005
			}
2006
2007
			$reactivate_modules[] = $active_module;
2008
			Jetpack::deactivate_module( $active_module );
2009
		}
2010
2011
		$new_version = JETPACK__VERSION . ':' . time();
2012
		/** This action is documented in class.jetpack.php */
2013
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2014
		Jetpack_Options::update_options(
2015
			array(
2016
				'version'     => $new_version,
2017
				'old_version' => $jetpack_old_version,
2018
			)
2019
		);
2020
2021
		Jetpack::state( 'message', 'modules_activated' );
2022
		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...
2023
2024
		if ( $redirect ) {
2025
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2026
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2027
				$page = $_GET['page'];
2028
			}
2029
2030
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2031
			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...
2032
		}
2033
	}
2034
2035
	/**
2036
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2037
	 * Make sure to tuck away module "library" files in a sub-directory.
2038
	 */
2039
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2040
		static $modules = null;
2041
2042
		if ( ! isset( $modules ) ) {
2043
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2044
			// Use the cache if we're on the front-end and it's available...
2045
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2046
				$modules = $available_modules_option[ JETPACK__VERSION ];
2047
			} else {
2048
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2049
2050
				$modules = array();
2051
2052
				foreach ( $files as $file ) {
2053
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2054
						continue;
2055
					}
2056
2057
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2058
				}
2059
2060
				Jetpack_Options::update_option( 'available_modules', array(
2061
					JETPACK__VERSION => $modules,
2062
				) );
2063
			}
2064
		}
2065
2066
		/**
2067
		 * Filters the array of modules available to be activated.
2068
		 *
2069
		 * @since 2.4.0
2070
		 *
2071
		 * @param array $modules Array of available modules.
2072
		 * @param string $min_version Minimum version number required to use modules.
2073
		 * @param string $max_version Maximum version number required to use modules.
2074
		 */
2075
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2076
2077
		if ( ! $min_version && ! $max_version ) {
2078
			return array_keys( $mods );
2079
		}
2080
2081
		$r = array();
2082
		foreach ( $mods as $slug => $introduced ) {
2083
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2084
				continue;
2085
			}
2086
2087
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2088
				continue;
2089
			}
2090
2091
			$r[] = $slug;
2092
		}
2093
2094
		return $r;
2095
	}
2096
2097
	/**
2098
	 * Default modules loaded on activation.
2099
	 */
2100
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2101
		$return = array();
2102
2103
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2104
			$module_data = Jetpack::get_module( $module );
2105
2106
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2107
				case 'yes' :
2108
					$return[] = $module;
2109
					break;
2110
				case 'public' :
2111
					if ( Jetpack_Options::get_option( 'public' ) ) {
2112
						$return[] = $module;
2113
					}
2114
					break;
2115
				case 'no' :
2116
				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...
2117
					break;
2118
			}
2119
		}
2120
		/**
2121
		 * Filters the array of default modules.
2122
		 *
2123
		 * @since 2.5.0
2124
		 *
2125
		 * @param array $return Array of default modules.
2126
		 * @param string $min_version Minimum version number required to use modules.
2127
		 * @param string $max_version Maximum version number required to use modules.
2128
		 */
2129
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2130
	}
2131
2132
	/**
2133
	 * Checks activated modules during auto-activation to determine
2134
	 * if any of those modules are being deprecated.  If so, close
2135
	 * them out, and add any replacement modules.
2136
	 *
2137
	 * Runs at priority 99 by default.
2138
	 *
2139
	 * This is run late, so that it can still activate a module if
2140
	 * the new module is a replacement for another that the user
2141
	 * currently has active, even if something at the normal priority
2142
	 * would kibosh everything.
2143
	 *
2144
	 * @since 2.6
2145
	 * @uses jetpack_get_default_modules filter
2146
	 * @param array $modules
2147
	 * @return array
2148
	 */
2149
	function handle_deprecated_modules( $modules ) {
2150
		$deprecated_modules = array(
2151
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2152
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2153
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2154
		);
2155
2156
		// Don't activate SSO if they never completed activating WPCC.
2157
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2158
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2159
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2160
				$deprecated_modules['wpcc'] = null;
2161
			}
2162
		}
2163
2164
		foreach ( $deprecated_modules as $module => $replacement ) {
2165
			if ( Jetpack::is_module_active( $module ) ) {
2166
				self::deactivate_module( $module );
2167
				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...
2168
					$modules[] = $replacement;
2169
				}
2170
			}
2171
		}
2172
2173
		return array_unique( $modules );
2174
	}
2175
2176
	/**
2177
	 * Checks activated plugins during auto-activation to determine
2178
	 * if any of those plugins are in the list with a corresponding module
2179
	 * that is not compatible with the plugin. The module will not be allowed
2180
	 * to auto-activate.
2181
	 *
2182
	 * @since 2.6
2183
	 * @uses jetpack_get_default_modules filter
2184
	 * @param array $modules
2185
	 * @return array
2186
	 */
2187
	function filter_default_modules( $modules ) {
2188
2189
		$active_plugins = self::get_active_plugins();
2190
2191
		if ( ! empty( $active_plugins ) ) {
2192
2193
			// For each module we'd like to auto-activate...
2194
			foreach ( $modules as $key => $module ) {
2195
				// If there are potential conflicts for it...
2196
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2197
					// For each potential conflict...
2198
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2199
						// If that conflicting plugin is active...
2200
						if ( in_array( $plugin, $active_plugins ) ) {
2201
							// Remove that item from being auto-activated.
2202
							unset( $modules[ $key ] );
2203
						}
2204
					}
2205
				}
2206
			}
2207
		}
2208
2209
		return $modules;
2210
	}
2211
2212
	/**
2213
	 * Extract a module's slug from its full path.
2214
	 */
2215
	public static function get_module_slug( $file ) {
2216
		return str_replace( '.php', '', basename( $file ) );
2217
	}
2218
2219
	/**
2220
	 * Generate a module's path from its slug.
2221
	 */
2222
	public static function get_module_path( $slug ) {
2223
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2224
	}
2225
2226
	/**
2227
	 * Load module data from module file. Headers differ from WordPress
2228
	 * plugin headers to avoid them being identified as standalone
2229
	 * plugins on the WordPress plugins page.
2230
	 */
2231
	public static function get_module( $module ) {
2232
		$headers = array(
2233
			'name'                      => 'Module Name',
2234
			'description'               => 'Module Description',
2235
			'jumpstart_desc'            => 'Jumpstart Description',
2236
			'sort'                      => 'Sort Order',
2237
			'recommendation_order'      => 'Recommendation Order',
2238
			'introduced'                => 'First Introduced',
2239
			'changed'                   => 'Major Changes In',
2240
			'deactivate'                => 'Deactivate',
2241
			'free'                      => 'Free',
2242
			'requires_connection'       => 'Requires Connection',
2243
			'auto_activate'             => 'Auto Activate',
2244
			'module_tags'               => 'Module Tags',
2245
			'feature'                   => 'Feature',
2246
			'additional_search_queries' => 'Additional Search Queries',
2247
		);
2248
2249
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2250
2251
		$mod = Jetpack::get_file_data( $file, $headers );
2252
		if ( empty( $mod['name'] ) ) {
2253
			return false;
2254
		}
2255
2256
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2257
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2258
		$mod['deactivate']              = empty( $mod['deactivate'] );
2259
		$mod['free']                    = empty( $mod['free'] );
2260
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2261
2262
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2263
			$mod['auto_activate'] = 'No';
2264
		} else {
2265
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2266
		}
2267
2268
		if ( $mod['module_tags'] ) {
2269
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2270
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2271
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2272
		} else {
2273
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2274
		}
2275
2276
		if ( $mod['feature'] ) {
2277
			$mod['feature'] = explode( ',', $mod['feature'] );
2278
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2279
		} else {
2280
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2281
		}
2282
2283
		/**
2284
		 * Filters the feature array on a module.
2285
		 *
2286
		 * This filter allows you to control where each module is filtered: Recommended,
2287
		 * Jumpstart, and the default "Other" listing.
2288
		 *
2289
		 * @since 3.5.0
2290
		 *
2291
		 * @param array   $mod['feature'] The areas to feature this module:
2292
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2293
		 *     'Recommended' shows on the main Jetpack admin screen.
2294
		 *     'Other' should be the default if no other value is in the array.
2295
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2296
		 * @param array   $mod All the currently assembled module data.
2297
		 */
2298
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2299
2300
		/**
2301
		 * Filter the returned data about a module.
2302
		 *
2303
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2304
		 * so please be careful.
2305
		 *
2306
		 * @since 3.6.0
2307
		 *
2308
		 * @param array   $mod    The details of the requested module.
2309
		 * @param string  $module The slug of the module, e.g. sharedaddy
2310
		 * @param string  $file   The path to the module source file.
2311
		 */
2312
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2313
	}
2314
2315
	/**
2316
	 * Like core's get_file_data implementation, but caches the result.
2317
	 */
2318
	public static function get_file_data( $file, $headers ) {
2319
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2320
		$file_name = basename( $file );
2321
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2322
		$key              = md5( $file_name . serialize( $headers ) );
2323
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2324
2325
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2326
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2327
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2328
		}
2329
2330
		$data = get_file_data( $file, $headers );
2331
2332
		// Strip out any old Jetpack versions that are cluttering the option.
2333
		//
2334
		// We maintain the data for the current version of Jetpack plus the previous version
2335
		// to prevent repeated DB hits on large sites hosted with multiple web servers
2336
		// on a single database (since all web servers might not be updated simultaneously)
2337
2338
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2339
2340
		if ( count( $file_data_option ) > 2 ) {
2341
			$count = 0;
2342
			krsort( $file_data_option );
2343
			foreach ( $file_data_option as $version => $values ) {
2344
				$count++;
2345
				if ( $count > 2 && JETPACK__VERSION != $version ) {
2346
					unset( $file_data_option[ $version ] );
2347
				}
2348
			}
2349
		}
2350
2351
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2352
2353
		return $data;
2354
	}
2355
2356
2357
	/**
2358
	 * Return translated module tag.
2359
	 *
2360
	 * @param string $tag Tag as it appears in each module heading.
2361
	 *
2362
	 * @return mixed
2363
	 */
2364
	public static function translate_module_tag( $tag ) {
2365
		return jetpack_get_module_i18n_tag( $tag );
2366
	}
2367
2368
	/**
2369
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2370
	 *
2371
	 * @since 3.9.2
2372
	 *
2373
	 * @param array $modules
2374
	 *
2375
	 * @return string|void
2376
	 */
2377
	public static function get_translated_modules( $modules ) {
2378
		foreach ( $modules as $index => $module ) {
2379
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2380
			if ( isset( $module['name'] ) ) {
2381
				$modules[ $index ]['name'] = $i18n_module['name'];
2382
			}
2383
			if ( isset( $module['description'] ) ) {
2384
				$modules[ $index ]['description'] = $i18n_module['description'];
2385
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2386
			}
2387
		}
2388
		return $modules;
2389
	}
2390
2391
	/**
2392
	 * Get a list of activated modules as an array of module slugs.
2393
	 */
2394
	public static function get_active_modules() {
2395
		$active = Jetpack_Options::get_option( 'active_modules' );
2396
2397
		if ( ! is_array( $active ) ) {
2398
			$active = array();
2399
		}
2400
2401
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2402
			$active[] = 'vaultpress';
2403
		} else {
2404
			$active = array_diff( $active, array( 'vaultpress' ) );
2405
		}
2406
2407
		//If protect is active on the main site of a multisite, it should be active on all sites.
2408
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2409
			$active[] = 'protect';
2410
		}
2411
2412
		return array_unique( $active );
2413
	}
2414
2415
	/**
2416
	 * Check whether or not a Jetpack module is active.
2417
	 *
2418
	 * @param string $module The slug of a Jetpack module.
2419
	 * @return bool
2420
	 *
2421
	 * @static
2422
	 */
2423
	public static function is_module_active( $module ) {
2424
		return in_array( $module, self::get_active_modules() );
2425
	}
2426
2427
	public static function is_module( $module ) {
2428
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2429
	}
2430
2431
	/**
2432
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2433
	 *
2434
	 * @param bool $catch True to start catching, False to stop.
2435
	 *
2436
	 * @static
2437
	 */
2438
	public static function catch_errors( $catch ) {
2439
		static $display_errors, $error_reporting;
2440
2441
		if ( $catch ) {
2442
			$display_errors  = @ini_set( 'display_errors', 1 );
2443
			$error_reporting = @error_reporting( E_ALL );
2444
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2445
		} else {
2446
			@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...
2447
			@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...
2448
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2449
		}
2450
	}
2451
2452
	/**
2453
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2454
	 */
2455
	public static function catch_errors_on_shutdown() {
2456
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2457
	}
2458
2459
	/**
2460
	 * Rewrite any string to make paths easier to read.
2461
	 *
2462
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2463
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2464
	 *
2465
	 * @param $string
2466
	 * @return mixed
2467
	 */
2468
	public static function alias_directories( $string ) {
2469
		// ABSPATH has a trailing slash.
2470
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2471
		// WP_CONTENT_DIR does not have a trailing slash.
2472
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2473
2474
		return $string;
2475
	}
2476
2477
	public static function activate_default_modules(
2478
		$min_version = false,
2479
		$max_version = false,
2480
		$other_modules = array(),
2481
		$redirect = true,
2482
		$send_state_messages = true
2483
	) {
2484
		$jetpack = Jetpack::init();
2485
2486
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2487
		$modules = array_merge( $other_modules, $modules );
2488
2489
		// Look for standalone plugins and disable if active.
2490
2491
		$to_deactivate = array();
2492
		foreach ( $modules as $module ) {
2493
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2494
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2495
			}
2496
		}
2497
2498
		$deactivated = array();
2499
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2500
			list( $probable_file, $probable_title ) = $deactivate_me;
2501
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2502
				$deactivated[] = $module;
2503
			}
2504
		}
2505
2506
		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...
2507
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2508
2509
			$url = add_query_arg(
2510
				array(
2511
					'action'   => 'activate_default_modules',
2512
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2513
				),
2514
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2515
			);
2516
			wp_safe_redirect( $url );
2517
			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...
2518
		}
2519
2520
		/**
2521
		 * Fires before default modules are activated.
2522
		 *
2523
		 * @since 1.9.0
2524
		 *
2525
		 * @param string $min_version Minimum version number required to use modules.
2526
		 * @param string $max_version Maximum version number required to use modules.
2527
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2528
		 */
2529
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2530
2531
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2532
		Jetpack::restate();
2533
		Jetpack::catch_errors( true );
2534
2535
		$active = Jetpack::get_active_modules();
2536
2537
		foreach ( $modules as $module ) {
2538
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2539
				$active[] = $module;
2540
				self::update_active_modules( $active );
2541
				continue;
2542
			}
2543
2544
			if ( $send_state_messages && in_array( $module, $active ) ) {
2545
				$module_info = Jetpack::get_module( $module );
2546 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2547
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2548
					if ( $active_state = Jetpack::state( $state ) ) {
2549
						$active_state = explode( ',', $active_state );
2550
					} else {
2551
						$active_state = array();
2552
					}
2553
					$active_state[] = $module;
2554
					Jetpack::state( $state, implode( ',', $active_state ) );
2555
				}
2556
				continue;
2557
			}
2558
2559
			$file = Jetpack::get_module_path( $module );
2560
			if ( ! file_exists( $file ) ) {
2561
				continue;
2562
			}
2563
2564
			// we'll override this later if the plugin can be included without fatal error
2565
			if ( $redirect ) {
2566
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2567
			}
2568
2569
			if ( $send_state_messages ) {
2570
				Jetpack::state( 'error', 'module_activation_failed' );
2571
				Jetpack::state( 'module', $module );
2572
			}
2573
2574
			ob_start();
2575
			require $file;
2576
2577
			$active[] = $module;
2578
2579 View Code Duplication
			if ( $send_state_messages ) {
2580
2581
				$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...
2582
				if ( $active_state = Jetpack::state( $state ) ) {
2583
					$active_state = explode( ',', $active_state );
2584
				} else {
2585
					$active_state = array();
2586
				}
2587
				$active_state[] = $module;
2588
				Jetpack::state( $state, implode( ',', $active_state ) );
2589
			}
2590
2591
			Jetpack::update_active_modules( $active );
2592
2593
			ob_end_clean();
2594
		}
2595
2596
		if ( $send_state_messages ) {
2597
			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...
2598
			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...
2599
		}
2600
2601
		Jetpack::catch_errors( false );
2602
		/**
2603
		 * Fires when default modules are activated.
2604
		 *
2605
		 * @since 1.9.0
2606
		 *
2607
		 * @param string $min_version Minimum version number required to use modules.
2608
		 * @param string $max_version Maximum version number required to use modules.
2609
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2610
		 */
2611
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2612
	}
2613
2614
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2615
		/**
2616
		 * Fires before a module is activated.
2617
		 *
2618
		 * @since 2.6.0
2619
		 *
2620
		 * @param string $module Module slug.
2621
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2622
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2623
		 */
2624
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2625
2626
		$jetpack = Jetpack::init();
2627
2628
		if ( ! strlen( $module ) )
2629
			return false;
2630
2631
		if ( ! Jetpack::is_module( $module ) )
2632
			return false;
2633
2634
		// If it's already active, then don't do it again
2635
		$active = Jetpack::get_active_modules();
2636
		foreach ( $active as $act ) {
2637
			if ( $act == $module )
2638
				return true;
2639
		}
2640
2641
		$module_data = Jetpack::get_module( $module );
2642
2643
		if ( ! Jetpack::is_active() ) {
2644
			if ( !Jetpack::is_development_mode() )
2645
				return false;
2646
2647
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2648
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2649
				return false;
2650
		}
2651
2652
		// Check and see if the old plugin is active
2653
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2654
			// Deactivate the old plugin
2655
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2656
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2657
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2658
				Jetpack::state( 'deactivated_plugins', $module );
2659
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2660
				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...
2661
			}
2662
		}
2663
2664
		// Protect won't work with mis-configured IPs
2665
		if ( 'protect' === $module ) {
2666
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2667
			if ( ! jetpack_protect_get_ip() ) {
2668
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2669
				return false;
2670
			}
2671
		}
2672
2673
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2674
		Jetpack::state( 'module', $module );
2675
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2676
2677
		Jetpack::catch_errors( true );
2678
		ob_start();
2679
		require Jetpack::get_module_path( $module );
2680
		/** This action is documented in class.jetpack.php */
2681
		do_action( 'jetpack_activate_module', $module );
2682
		$active[] = $module;
2683
		Jetpack::update_active_modules( $active );
2684
2685
		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...
2686
		ob_end_clean();
2687
		Jetpack::catch_errors( false );
2688
2689
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2690 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2691
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2692
2693
			//Jump start is being dismissed send data to MC Stats
2694
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2695
2696
			$jetpack->do_stats( 'server_side' );
2697
		}
2698
2699
		if ( $redirect ) {
2700
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2701
		}
2702
		if ( $exit ) {
2703
			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...
2704
		}
2705
		return true;
2706
	}
2707
2708
	function activate_module_actions( $module ) {
2709
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2710
	}
2711
2712
	public static function deactivate_module( $module ) {
2713
		/**
2714
		 * Fires when a module is deactivated.
2715
		 *
2716
		 * @since 1.9.0
2717
		 *
2718
		 * @param string $module Module slug.
2719
		 */
2720
		do_action( 'jetpack_pre_deactivate_module', $module );
2721
2722
		$jetpack = Jetpack::init();
2723
2724
		$active = Jetpack::get_active_modules();
2725
		$new    = array_filter( array_diff( $active, (array) $module ) );
2726
2727
		// A flag for Jump Start so it's not shown again.
2728 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2729
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2730
2731
			//Jump start is being dismissed send data to MC Stats
2732
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2733
2734
			$jetpack->do_stats( 'server_side' );
2735
		}
2736
2737
		return self::update_active_modules( $new );
2738
	}
2739
2740
	public static function enable_module_configurable( $module ) {
2741
		$module = Jetpack::get_module_slug( $module );
2742
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2743
	}
2744
2745
	public static function module_configuration_url( $module ) {
2746
		$module = Jetpack::get_module_slug( $module );
2747
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2748
	}
2749
2750
	public static function module_configuration_load( $module, $method ) {
2751
		$module = Jetpack::get_module_slug( $module );
2752
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2753
	}
2754
2755
	public static function module_configuration_head( $module, $method ) {
2756
		$module = Jetpack::get_module_slug( $module );
2757
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2758
	}
2759
2760
	public static function module_configuration_screen( $module, $method ) {
2761
		$module = Jetpack::get_module_slug( $module );
2762
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2763
	}
2764
2765
	public static function module_configuration_activation_screen( $module, $method ) {
2766
		$module = Jetpack::get_module_slug( $module );
2767
		add_action( 'display_activate_module_setting_' . $module, $method );
2768
	}
2769
2770
/* Installation */
2771
2772
	public static function bail_on_activation( $message, $deactivate = true ) {
2773
?>
2774
<!doctype html>
2775
<html>
2776
<head>
2777
<meta charset="<?php bloginfo( 'charset' ); ?>">
2778
<style>
2779
* {
2780
	text-align: center;
2781
	margin: 0;
2782
	padding: 0;
2783
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2784
}
2785
p {
2786
	margin-top: 1em;
2787
	font-size: 18px;
2788
}
2789
</style>
2790
<body>
2791
<p><?php echo esc_html( $message ); ?></p>
2792
</body>
2793
</html>
2794
<?php
2795
		if ( $deactivate ) {
2796
			$plugins = get_option( 'active_plugins' );
2797
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2798
			$update  = false;
2799
			foreach ( $plugins as $i => $plugin ) {
2800
				if ( $plugin === $jetpack ) {
2801
					$plugins[$i] = false;
2802
					$update = true;
2803
				}
2804
			}
2805
2806
			if ( $update ) {
2807
				update_option( 'active_plugins', array_filter( $plugins ) );
2808
			}
2809
		}
2810
		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...
2811
	}
2812
2813
	/**
2814
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2815
	 * @static
2816
	 */
2817
	public static function plugin_activation( $network_wide ) {
2818
		Jetpack_Options::update_option( 'activated', 1 );
2819
2820
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2821
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2822
		}
2823
2824
		if ( $network_wide )
2825
			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...
2826
2827
		// For firing one-off events (notices) immediately after activation
2828
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2829
2830
		Jetpack::plugin_initialize();
2831
	}
2832
	/**
2833
	 * Runs before bumping version numbers up to a new version
2834
	 * @param  (string) $version    Version:timestamp
2835
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2836
	 * @return null              [description]
2837
	 */
2838
	public static function do_version_bump( $version, $old_version ) {
2839
2840
		if ( ! $old_version ) { // For new sites
2841
			// Setting up jetpack manage
2842
			Jetpack::activate_manage();
2843
		}
2844
	}
2845
2846
	/**
2847
	 * Sets the internal version number and activation state.
2848
	 * @static
2849
	 */
2850
	public static function plugin_initialize() {
2851
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2852
			Jetpack_Options::update_option( 'activated', 2 );
2853
		}
2854
2855 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2856
			$version = $old_version = JETPACK__VERSION . ':' . time();
2857
			/** This action is documented in class.jetpack.php */
2858
			do_action( 'updating_jetpack_version', $version, false );
2859
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2860
		}
2861
2862
		Jetpack::load_modules();
2863
2864
		Jetpack_Options::delete_option( 'do_activate' );
2865
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
2866
	}
2867
2868
	/**
2869
	 * Removes all connection options
2870
	 * @static
2871
	 */
2872
	public static function plugin_deactivation( ) {
2873
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2874
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2875
			Jetpack_Network::init()->deactivate();
2876
		} else {
2877
			Jetpack::disconnect( false );
2878
			//Jetpack_Heartbeat::init()->deactivate();
2879
		}
2880
	}
2881
2882
	/**
2883
	 * Disconnects from the Jetpack servers.
2884
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2885
	 * @static
2886
	 */
2887
	public static function disconnect( $update_activated_state = true ) {
2888
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2889
		Jetpack::clean_nonces( true );
2890
2891
		// If the site is in an IDC because sync is not allowed,
2892
		// let's make sure to not disconnect the production site.
2893
		if ( ! self::validate_sync_error_idc_option() ) {
2894
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2895
			Jetpack::load_xml_rpc_client();
2896
			$xml = new Jetpack_IXR_Client();
2897
			$xml->query( 'jetpack.deregister' );
2898
		}
2899
2900
		Jetpack_Options::delete_option(
2901
			array(
2902
				'blog_token',
2903
				'user_token',
2904
				'user_tokens',
2905
				'master_user',
2906
				'time_diff',
2907
				'fallback_no_verify_ssl_certs',
2908
			)
2909
		);
2910
2911
		Jetpack_IDC::clear_all_idc_options();
2912
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
2913
2914
		if ( $update_activated_state ) {
2915
			Jetpack_Options::update_option( 'activated', 4 );
2916
		}
2917
2918
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2919
			// Check then record unique disconnection if site has never been disconnected previously
2920
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2921
				$jetpack_unique_connection['disconnected'] = 1;
2922
			} else {
2923
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2924
					//track unique disconnect
2925
					$jetpack = Jetpack::init();
2926
2927
					$jetpack->stat( 'connections', 'unique-disconnect' );
2928
					$jetpack->do_stats( 'server_side' );
2929
				}
2930
				// increment number of times disconnected
2931
				$jetpack_unique_connection['disconnected'] += 1;
2932
			}
2933
2934
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2935
		}
2936
2937
		// Delete cached connected user data
2938
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2939
		delete_transient( $transient_key );
2940
2941
		// Delete all the sync related data. Since it could be taking up space.
2942
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2943
		Jetpack_Sync_Sender::get_instance()->uninstall();
2944
2945
		// Disable the Heartbeat cron
2946
		Jetpack_Heartbeat::init()->deactivate();
2947
	}
2948
2949
	/**
2950
	 * Unlinks the current user from the linked WordPress.com user
2951
	 */
2952
	public static function unlink_user( $user_id = null ) {
2953
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2954
			return false;
2955
2956
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2957
2958
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2959
			return false;
2960
2961
		if ( ! isset( $tokens[ $user_id ] ) )
2962
			return false;
2963
2964
		Jetpack::load_xml_rpc_client();
2965
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2966
		$xml->query( 'jetpack.unlink_user', $user_id );
2967
2968
		unset( $tokens[ $user_id ] );
2969
2970
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2971
2972
		/**
2973
		 * Fires after the current user has been unlinked from WordPress.com.
2974
		 *
2975
		 * @since 4.1.0
2976
		 *
2977
		 * @param int $user_id The current user's ID.
2978
		 */
2979
		do_action( 'jetpack_unlinked_user', $user_id );
2980
2981
		return true;
2982
	}
2983
2984
	/**
2985
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2986
	 */
2987
	public static function try_registration() {
2988
		// Let's get some testing in beta versions and such.
2989
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2990
			// Before attempting to connect, let's make sure that the domains are viable.
2991
			$domains_to_check = array_unique( array(
2992
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2993
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2994
			) );
2995
			foreach ( $domains_to_check as $domain ) {
2996
				$result = Jetpack_Data::is_usable_domain( $domain );
2997
				if ( is_wp_error( $result ) ) {
2998
					return $result;
2999
				}
3000
			}
3001
		}
3002
3003
		$result = Jetpack::register();
3004
3005
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3006
		if ( ! $result || is_wp_error( $result ) ) {
3007
			return $result;
3008
		} else {
3009
			return true;
3010
		}
3011
	}
3012
3013
	/**
3014
	 * Tracking an internal event log. Try not to put too much chaff in here.
3015
	 *
3016
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3017
	 */
3018
	public static function log( $code, $data = null ) {
3019
		// only grab the latest 200 entries
3020
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3021
3022
		// Append our event to the log
3023
		$log_entry = array(
3024
			'time'    => time(),
3025
			'user_id' => get_current_user_id(),
3026
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3027
			'code'    => $code,
3028
		);
3029
		// Don't bother storing it unless we've got some.
3030
		if ( ! is_null( $data ) ) {
3031
			$log_entry['data'] = $data;
3032
		}
3033
		$log[] = $log_entry;
3034
3035
		// Try add_option first, to make sure it's not autoloaded.
3036
		// @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...
3037
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3038
			Jetpack_Options::update_option( 'log', $log );
3039
		}
3040
3041
		/**
3042
		 * Fires when Jetpack logs an internal event.
3043
		 *
3044
		 * @since 3.0.0
3045
		 *
3046
		 * @param array $log_entry {
3047
		 *	Array of details about the log entry.
3048
		 *
3049
		 *	@param string time Time of the event.
3050
		 *	@param int user_id ID of the user who trigerred the event.
3051
		 *	@param int blog_id Jetpack Blog ID.
3052
		 *	@param string code Unique name for the event.
3053
		 *	@param string data Data about the event.
3054
		 * }
3055
		 */
3056
		do_action( 'jetpack_log_entry', $log_entry );
3057
	}
3058
3059
	/**
3060
	 * Get the internal event log.
3061
	 *
3062
	 * @param $event (string) - only return the specific log events
3063
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3064
	 *
3065
	 * @return array of log events || WP_Error for invalid params
3066
	 */
3067
	public static function get_log( $event = false, $num = false ) {
3068
		if ( $event && ! is_string( $event ) ) {
3069
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3070
		}
3071
3072
		if ( $num && ! is_numeric( $num ) ) {
3073
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3074
		}
3075
3076
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3077
3078
		// If nothing set - act as it did before, otherwise let's start customizing the output
3079
		if ( ! $num && ! $event ) {
3080
			return $entire_log;
3081
		} else {
3082
			$entire_log = array_reverse( $entire_log );
3083
		}
3084
3085
		$custom_log_output = array();
3086
3087
		if ( $event ) {
3088
			foreach ( $entire_log as $log_event ) {
3089
				if ( $event == $log_event[ 'code' ] ) {
3090
					$custom_log_output[] = $log_event;
3091
				}
3092
			}
3093
		} else {
3094
			$custom_log_output = $entire_log;
3095
		}
3096
3097
		if ( $num ) {
3098
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3099
		}
3100
3101
		return $custom_log_output;
3102
	}
3103
3104
	/**
3105
	 * Log modification of important settings.
3106
	 */
3107
	public static function log_settings_change( $option, $old_value, $value ) {
3108
		switch( $option ) {
3109
			case 'jetpack_sync_non_public_post_stati':
3110
				self::log( $option, $value );
3111
				break;
3112
		}
3113
	}
3114
3115
	/**
3116
	 * Return stat data for WPCOM sync
3117
	 */
3118
	public static function get_stat_data( $encode = true, $extended = true ) {
3119
		$data = Jetpack_Heartbeat::generate_stats_array();
3120
3121
		if ( $extended ) {
3122
			$additional_data = self::get_additional_stat_data();
3123
			$data = array_merge( $data, $additional_data );
3124
		}
3125
3126
		if ( $encode ) {
3127
			return json_encode( $data );
3128
		}
3129
3130
		return $data;
3131
	}
3132
3133
	/**
3134
	 * Get additional stat data to sync to WPCOM
3135
	 */
3136
	public static function get_additional_stat_data( $prefix = '' ) {
3137
		$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...
3138
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3139
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3140
		$return["{$prefix}site-count"]     = 0;
3141
3142
		if ( function_exists( 'get_blog_count' ) ) {
3143
			$return["{$prefix}site-count"] = get_blog_count();
3144
		}
3145
		return $return;
3146
	}
3147
3148
	private static function get_site_user_count() {
3149
		global $wpdb;
3150
3151
		if ( function_exists( 'wp_is_large_network' ) ) {
3152
			if ( wp_is_large_network( 'users' ) ) {
3153
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3154
			}
3155
		}
3156 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3157
			// It wasn't there, so regenerate the data and save the transient
3158
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3159
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3160
		}
3161
		return $user_count;
3162
	}
3163
3164
	/* Admin Pages */
3165
3166
	function admin_init() {
3167
		// If the plugin is not connected, display a connect message.
3168
		if (
3169
			// the plugin was auto-activated and needs its candy
3170
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3171
		||
3172
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3173
			! Jetpack_Options::get_option( 'activated' )
3174
		) {
3175
			Jetpack::plugin_initialize();
3176
		}
3177
3178
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3179
			Jetpack_Connection_Banner::init();
3180
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3181
			// Upgrade: 1.1 -> 1.1.1
3182
			// Check and see if host can verify the Jetpack servers' SSL certificate
3183
			$args = array();
3184
			Jetpack_Client::_wp_remote_request(
3185
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3186
				$args,
3187
				true
3188
			);
3189
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3190
			// Show the notice on the Dashboard only for now
3191
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3192
		}
3193
3194
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3195
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3196
		}
3197
3198
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3199
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3200
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3201
3202
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3203
			// Artificially throw errors in certain whitelisted cases during plugin activation
3204
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3205
		}
3206
3207
		// Jetpack Manage Activation Screen from .com
3208
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3209
3210
		// Add custom column in wp-admin/users.php to show whether user is linked.
3211
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3212
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3213
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3214
	}
3215
3216
	function admin_body_class( $admin_body_class = '' ) {
3217
		$classes = explode( ' ', trim( $admin_body_class ) );
3218
3219
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3220
3221
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3222
		return " $admin_body_class ";
3223
	}
3224
3225
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3226
		return $admin_body_class . ' jetpack-pagestyles ';
3227
	}
3228
3229
	/**
3230
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3231
	 *
3232
	 * @return null
3233
	 */
3234
	function prepare_manage_jetpack_notice() {
3235
3236
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3237
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3238
	}
3239
3240
	function manage_activate_screen() {
3241
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3242
	}
3243
	/**
3244
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3245
	 * This function artificially throws errors for such cases (whitelisted).
3246
	 *
3247
	 * @param string $plugin The activated plugin.
3248
	 */
3249
	function throw_error_on_activate_plugin( $plugin ) {
3250
		$active_modules = Jetpack::get_active_modules();
3251
3252
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3253
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3254
			$throw = false;
3255
3256
			// Try and make sure it really was the stats plugin
3257
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3258
				if ( 'stats.php' == basename( $plugin ) ) {
3259
					$throw = true;
3260
				}
3261
			} else {
3262
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3263
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3264
					$throw = true;
3265
				}
3266
			}
3267
3268
			if ( $throw ) {
3269
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3270
			}
3271
		}
3272
	}
3273
3274
	function intercept_plugin_error_scrape_init() {
3275
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3276
	}
3277
3278
	function intercept_plugin_error_scrape( $action, $result ) {
3279
		if ( ! $result ) {
3280
			return;
3281
		}
3282
3283
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3284
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3285
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3286
			}
3287
		}
3288
	}
3289
3290
	function add_remote_request_handlers() {
3291
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3292
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3293
	}
3294
3295
	function remote_request_handlers() {
3296
		$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...
3297
3298
		switch ( current_filter() ) {
3299
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3300
			$response = $this->upload_handler();
3301
			break;
3302
3303
		case 'wp_ajax_nopriv_jetpack_update_file' :
3304
			$response = $this->upload_handler( true );
3305
			break;
3306
		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...
3307
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3308
			break;
3309
		}
3310
3311
		if ( ! $response ) {
3312
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3313
		}
3314
3315
		if ( is_wp_error( $response ) ) {
3316
			$status_code       = $response->get_error_data();
3317
			$error             = $response->get_error_code();
3318
			$error_description = $response->get_error_message();
3319
3320
			if ( ! is_int( $status_code ) ) {
3321
				$status_code = 400;
3322
			}
3323
3324
			status_header( $status_code );
3325
			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...
3326
		}
3327
3328
		status_header( 200 );
3329
		if ( true === $response ) {
3330
			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...
3331
		}
3332
3333
		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...
3334
	}
3335
3336
	/**
3337
	 * Uploads a file gotten from the global $_FILES.
3338
	 * If `$update_media_item` is true and `post_id` is defined
3339
	 * the attachment file of the media item (gotten through of the post_id)
3340
	 * will be updated instead of add a new one.
3341
	 *
3342
	 * @param  boolean $update_media_item - update media attachment
3343
	 * @return array - An array describing the uploadind files process
3344
	 */
3345
	function upload_handler( $update_media_item = false ) {
3346
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3347
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3348
		}
3349
3350
		$user = wp_authenticate( '', '' );
3351
		if ( ! $user || is_wp_error( $user ) ) {
3352
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3353
		}
3354
3355
		wp_set_current_user( $user->ID );
3356
3357
		if ( ! current_user_can( 'upload_files' ) ) {
3358
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3359
		}
3360
3361
		if ( empty( $_FILES ) ) {
3362
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3363
		}
3364
3365
		foreach ( array_keys( $_FILES ) as $files_key ) {
3366
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3367
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3368
			}
3369
		}
3370
3371
		$media_keys = array_keys( $_FILES['media'] );
3372
3373
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3374
		if ( ! $token || is_wp_error( $token ) ) {
3375
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3376
		}
3377
3378
		$uploaded_files = array();
3379
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3380
		unset( $GLOBALS['post'] );
3381
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3382
			$file = array();
3383
			foreach ( $media_keys as $media_key ) {
3384
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3385
			}
3386
3387
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3388
3389
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3390
			if ( $hmac_provided !== $hmac_file ) {
3391
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3392
				continue;
3393
			}
3394
3395
			$_FILES['.jetpack.upload.'] = $file;
3396
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3397
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3398
				$post_id = 0;
3399
			}
3400
3401
			if ( $update_media_item ) {
3402
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3403
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3404
				}
3405
3406
				$media_array = $_FILES['media'];
3407
3408
				$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...
3409
				$file_array['type'] = $media_array['type'][0];
3410
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3411
				$file_array['error'] = $media_array['error'][0];
3412
				$file_array['size'] = $media_array['size'][0];
3413
3414
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3415
3416
				if ( is_wp_error( $edited_media_item ) ) {
3417
					return $edited_media_item;
3418
				}
3419
3420
				$response = (object) array(
3421
					'id'   => (string) $post_id,
3422
					'file' => (string) $edited_media_item->post_title,
3423
					'url'  => (string) wp_get_attachment_url( $post_id ),
3424
					'type' => (string) $edited_media_item->post_mime_type,
3425
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3426
				);
3427
3428
				return (array) array( $response );
3429
			}
3430
3431
			$attachment_id = media_handle_upload(
3432
				'.jetpack.upload.',
3433
				$post_id,
3434
				array(),
3435
				array(
3436
					'action' => 'jetpack_upload_file',
3437
				)
3438
			);
3439
3440
			if ( ! $attachment_id ) {
3441
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3442
			} elseif ( is_wp_error( $attachment_id ) ) {
3443
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3444
			} else {
3445
				$attachment = get_post( $attachment_id );
3446
				$uploaded_files[$index] = (object) array(
3447
					'id'   => (string) $attachment_id,
3448
					'file' => $attachment->post_title,
3449
					'url'  => wp_get_attachment_url( $attachment_id ),
3450
					'type' => $attachment->post_mime_type,
3451
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3452
				);
3453
				// Zip files uploads are not supported unless they are done for installation purposed
3454
				// lets delete them in case something goes wrong in this whole process
3455
				if ( 'application/zip' === $attachment->post_mime_type ) {
3456
					// Schedule a cleanup for 2 hours from now in case of failed install.
3457
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3458
				}
3459
			}
3460
		}
3461
		if ( ! is_null( $global_post ) ) {
3462
			$GLOBALS['post'] = $global_post;
3463
		}
3464
3465
		return $uploaded_files;
3466
	}
3467
3468
	/**
3469
	 * Add help to the Jetpack page
3470
	 *
3471
	 * @since Jetpack (1.2.3)
3472
	 * @return false if not the Jetpack page
3473
	 */
3474
	function admin_help() {
3475
		$current_screen = get_current_screen();
3476
3477
		// Overview
3478
		$current_screen->add_help_tab(
3479
			array(
3480
				'id'		=> 'home',
3481
				'title'		=> __( 'Home', 'jetpack' ),
3482
				'content'	=>
3483
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3484
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3485
					'<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>',
3486
			)
3487
		);
3488
3489
		// Screen Content
3490
		if ( current_user_can( 'manage_options' ) ) {
3491
			$current_screen->add_help_tab(
3492
				array(
3493
					'id'		=> 'settings',
3494
					'title'		=> __( 'Settings', 'jetpack' ),
3495
					'content'	=>
3496
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3497
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3498
						'<ol>' .
3499
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3500
							'<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>' .
3501
						'</ol>' .
3502
						'<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>'
3503
				)
3504
			);
3505
		}
3506
3507
		// Help Sidebar
3508
		$current_screen->set_help_sidebar(
3509
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3510
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3511
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3512
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3513
		);
3514
	}
3515
3516
	function admin_menu_css() {
3517
		wp_enqueue_style( 'jetpack-icons' );
3518
	}
3519
3520
	function admin_menu_order() {
3521
		return true;
3522
	}
3523
3524 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3525
		$jp_menu_order = array();
3526
3527
		foreach ( $menu_order as $index => $item ) {
3528
			if ( $item != 'jetpack' ) {
3529
				$jp_menu_order[] = $item;
3530
			}
3531
3532
			if ( $index == 0 ) {
3533
				$jp_menu_order[] = 'jetpack';
3534
			}
3535
		}
3536
3537
		return $jp_menu_order;
3538
	}
3539
3540
	function admin_head() {
3541 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3542
			/** This action is documented in class.jetpack-admin-page.php */
3543
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3544
	}
3545
3546
	function admin_banner_styles() {
3547
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3548
3549 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3550
			wp_register_style(
3551
				'jetpack-dops-style',
3552
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3553
				array(),
3554
				JETPACK__VERSION
3555
			);
3556
		}
3557
3558
		wp_enqueue_style(
3559
			'jetpack',
3560
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3561
			array( 'jetpack-dops-style' ),
3562
			 JETPACK__VERSION . '-20121016'
3563
		);
3564
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3565
		wp_style_add_data( 'jetpack', 'suffix', $min );
3566
	}
3567
3568
	function plugin_action_links( $actions ) {
3569
3570
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3571
3572
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3573
			return array_merge(
3574
				$jetpack_home,
3575
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3576
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3577
				$actions
3578
				);
3579
			}
3580
3581
		return array_merge( $jetpack_home, $actions );
3582
	}
3583
3584
	/**
3585
	 * This is the first banner
3586
	 * It should be visible only to user that can update the option
3587
	 * Are not connected
3588
	 *
3589
	 * @return null
3590
	 */
3591
	function admin_jetpack_manage_notice() {
3592
		$screen = get_current_screen();
3593
3594
		// Don't show the connect notice on the jetpack settings page.
3595
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3596
			return;
3597
		}
3598
3599
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3600
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3601
		/**
3602
		 * I think it would be great to have different wordsing depending on where you are
3603
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3604
		 * etc..
3605
		 */
3606
3607
		?>
3608
		<div id="message" class="updated jp-banner">
3609
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3610
				<div class="jp-banner__description-container">
3611
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3612
					<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>
3613
					<p class="jp-banner__button-container">
3614
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3615
						<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>
3616
					</p>
3617
				</div>
3618
		</div>
3619
		<?php
3620
	}
3621
3622
	/**
3623
	 * Returns the url that the user clicks to remove the notice for the big banner
3624
	 * @return (string)
3625
	 */
3626
	function opt_out_jetpack_manage_url() {
3627
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3628
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3629
	}
3630
	/**
3631
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3632
	 * @return (string)
3633
	 */
3634
	function opt_in_jetpack_manage_url() {
3635
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3636
	}
3637
3638
	function opt_in_jetpack_manage_notice() {
3639
		?>
3640
		<div class="wrap">
3641
			<div id="message" class="jetpack-message is-opt-in">
3642
				<?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' ); ?>
3643
			</div>
3644
		</div>
3645
		<?php
3646
3647
	}
3648
	/**
3649
	 * Determines whether to show the notice of not true = display notice
3650
	 * @return (bool)
3651
	 */
3652
	function can_display_jetpack_manage_notice() {
3653
		// never display the notice to users that can't do anything about it anyways
3654
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3655
			return false;
3656
3657
		// don't display if we are in development more
3658
		if( Jetpack::is_development_mode() ) {
3659
			return false;
3660
		}
3661
		// don't display if the site is private
3662
		if(  ! Jetpack_Options::get_option( 'public' ) )
3663
			return false;
3664
3665
		/**
3666
		 * Should the Jetpack Remote Site Management notice be displayed.
3667
		 *
3668
		 * @since 3.3.0
3669
		 *
3670
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3671
		 */
3672
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3673
	}
3674
3675
	/*
3676
	 * Registration flow:
3677
	 * 1 - ::admin_page_load() action=register
3678
	 * 2 - ::try_registration()
3679
	 * 3 - ::register()
3680
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3681
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3682
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3683
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3684
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3685
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3686
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3687
	 *       jetpack_id, jetpack_secret, jetpack_public
3688
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3689
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3690
	 * 5 - user logs in with WP.com account
3691
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3692
	 *		- Jetpack_Client_Server::authorize()
3693
	 *		- Jetpack_Client_Server::get_token()
3694
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3695
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3696
	 *			- which responds with access_token, token_type, scope
3697
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3698
	 *		- Jetpack::activate_default_modules()
3699
	 *     		- Deactivates deprecated plugins
3700
	 *     		- Activates all default modules
3701
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3702
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3703
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3704
	 *     Done!
3705
	 */
3706
3707
	/**
3708
	 * Handles the page load events for the Jetpack admin page
3709
	 */
3710
	function admin_page_load() {
3711
		$error = false;
3712
3713
		// Make sure we have the right body class to hook stylings for subpages off of.
3714
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3715
3716
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3717
			// Should only be used in intermediate redirects to preserve state across redirects
3718
			Jetpack::restate();
3719
		}
3720
3721
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3722
			// User clicked in the iframe to link their accounts
3723
			if ( ! Jetpack::is_user_connected() ) {
3724
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3725
				if ( isset( $_GET['notes_iframe'] ) )
3726
					$connect_url .= '&notes_iframe';
3727
				wp_redirect( $connect_url );
3728
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3729
			} else {
3730
				if ( ! isset( $_GET['calypso_env'] ) ) {
3731
					Jetpack::state( 'message', 'already_authorized' );
3732
					wp_safe_redirect( Jetpack::admin_url() );
3733
				} else {
3734
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3735
					$connect_url .= '&already_authorized=true';
3736
					wp_redirect( $connect_url );
3737
				}
3738
			}
3739
		}
3740
3741
3742
		if ( isset( $_GET['action'] ) ) {
3743
			switch ( $_GET['action'] ) {
3744
			case 'authorize':
3745
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3746
					Jetpack::state( 'message', 'already_authorized' );
3747
					wp_safe_redirect( Jetpack::admin_url() );
3748
					exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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