Completed
Push — add/at-flag-filter ( f6a129...0e6d82 )
by
unknown
09:48
created

class.jetpack.php (67 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
		'jetpack-search-widget',
62
		'jetpack-simple-payments-widget-style',
63
	);
64
65
	/**
66
	 * Contains all assets that have had their URL rewritten to minified versions.
67
	 *
68
	 * @var array
69
	 */
70
	static $min_assets = array();
0 ignored issues
show
The visibility should be declared for property $min_assets.

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...
71
72
	public $plugins_to_deactivate = array(
73
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
74
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
75
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
76
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
77
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
78
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
79
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
80
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
81
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
82
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
83
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
84
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
85
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
86
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
87
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
88
	);
89
90
	static $capability_translations = array(
0 ignored issues
show
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...
91
		'administrator' => 'manage_options',
92
		'editor'        => 'edit_others_posts',
93
		'author'        => 'publish_posts',
94
		'contributor'   => 'edit_posts',
95
		'subscriber'    => 'read',
96
	);
97
98
	/**
99
	 * Map of modules that have conflicts with plugins and should not be auto-activated
100
	 * if the plugins are active.  Used by filter_default_modules
101
	 *
102
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
103
	 * change `module-slug` and add this to your plugin:
104
	 *
105
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
106
	 * function my_jetpack_get_default_modules( $modules ) {
107
	 *     return array_diff( $modules, array( 'module-slug' ) );
108
	 * }
109
	 *
110
	 * @var array
111
	 */
112
	private $conflicting_plugins = array(
113
		'comments'          => array(
114
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
115
			'Disqus'                               => 'disqus-comment-system/disqus.php',
116
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
117
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
118
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
119
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
120
		),
121
		'comment-likes' => array(
122
			'Epoch'                                => 'epoch/plugincore.php',
123
		),
124
		'contact-form'      => array(
125
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
126
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
127
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
128
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
129
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
130
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
131
		),
132
		'minileven'         => array(
133
			'WPtouch'                              => 'wptouch/wptouch.php',
134
		),
135
		'latex'             => array(
136
			'LaTeX for WordPress'                  => 'latex/latex.php',
137
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
138
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
139
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
140
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
141
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
142
		),
143
		'protect'           => array(
144
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
145
			'Captcha'                              => 'captcha/captcha.php',
146
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
147
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
148
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
149
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
150
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
151
			'Security-protection'                  => 'security-protection/security-protection.php',
152
			'Login Security'                       => 'login-security/login-security.php',
153
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
154
			'Wordfence Security'                   => 'wordfence/wordfence.php',
155
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
156
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
157
		),
158
		'random-redirect'   => array(
159
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
160
		),
161
		'related-posts'     => array(
162
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
163
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
164
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
165
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
166
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
167
			'outbrain'                             => 'outbrain/outbrain.php',
168
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
169
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
170
		),
171
		'sharedaddy'        => array(
172
			'AddThis'                              => 'addthis/addthis_social_widget.php',
173
			'Add To Any'                           => 'add-to-any/add-to-any.php',
174
			'ShareThis'                            => 'share-this/sharethis.php',
175
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
176
		),
177
		'seo-tools' => array(
178
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
179
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
180
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
181
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
182
			'The SEO Framework'                    => 'autodescription/autodescription.php',
183
		),
184
		'verification-tools' => array(
185
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
186
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
187
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
188
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
189
			'The SEO Framework'                    => 'autodescription/autodescription.php',
190
		),
191
		'widget-visibility' => array(
192
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
193
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
194
		),
195
		'sitemaps' => array(
196
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
197
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
198
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
199
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
200
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
201
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
202
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
203
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
204
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
205
			'The SEO Framework'                    => 'autodescription/autodescription.php',
206
			'Sitemap'                              => 'sitemap/sitemap.php',
207
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
208
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
209
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
210
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
211
		),
212
		'lazy-images' => array(
213
			'Lazy Load'              => 'lazy-load/lazy-load.php',
214
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
215
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
216
		),
217
	);
218
219
	/**
220
	 * Plugins for which we turn off our Facebook OG Tags implementation.
221
	 *
222
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
223
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
224
	 *
225
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
226
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
227
	 */
228
	private $open_graph_conflicting_plugins = array(
229
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
230
		                                                         // 2 Click Social Media Buttons
231
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
232
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
233
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
234
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
235
		                                                         // Open Graph Meta Tags by Heateor
236
		'facebook/facebook.php',                                 // Facebook (official plugin)
237
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
238
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
239
		                                                         // Facebook Featured Image & OG Meta Tags
240
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
241
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
242
		                                                         // Facebook Open Graph Meta Tags for WordPress
243
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
244
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
245
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
246
		                                                         // Fedmich's Facebook Open Graph Meta
247
		'network-publisher/networkpub.php',                      // Network Publisher
248
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
249
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
250
		                                                         // NextScripts SNAP
251
		'og-tags/og-tags.php',                                   // OG Tags
252
		'opengraph/opengraph.php',                               // Open Graph
253
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
254
		                                                         // Open Graph Protocol Framework
255
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
256
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
257
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
258
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
259
		'sharepress/sharepress.php',                             // SharePress
260
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
261
		'social-discussions/social-discussions.php',             // Social Discussions
262
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
263
		'socialize/socialize.php',                               // Socialize
264
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
265
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
266
		                                                         // Tweet, Like, Google +1 and Share
267
		'wordbooker/wordbooker.php',                             // Wordbooker
268
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
269
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
270
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
271
		                                                         // WP Facebook Like Send & Open Graph Meta
272
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
273
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
274
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
275
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
276
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
277
	);
278
279
	/**
280
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
281
	 */
282
	private $twitter_cards_conflicting_plugins = array(
283
	//	'twitter/twitter.php',                       // The official one handles this on its own.
284
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
285
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
286
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
287
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
288
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
289
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
290
		'twitter-cards/twitter-cards.php',           // Twitter Cards
291
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
292
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
293
	);
294
295
	/**
296
	 * Message to display in admin_notice
297
	 * @var string
298
	 */
299
	public $message = '';
300
301
	/**
302
	 * Error to display in admin_notice
303
	 * @var string
304
	 */
305
	public $error = '';
306
307
	/**
308
	 * Modules that need more privacy description.
309
	 * @var string
310
	 */
311
	public $privacy_checks = '';
312
313
	/**
314
	 * Stats to record once the page loads
315
	 *
316
	 * @var array
317
	 */
318
	public $stats = array();
319
320
	/**
321
	 * Jetpack_Sync object
322
	 */
323
	public $sync;
324
325
	/**
326
	 * Verified data for JSON authorization request
327
	 */
328
	public $json_api_authorization_request = array();
329
330
	/**
331
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
332
	 */
333
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
334
335
	/**
336
	 * Holds the singleton instance of this class
337
	 * @since 2.3.3
338
	 * @var Jetpack
339
	 */
340
	static $instance = false;
0 ignored issues
show
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...
341
342
	/**
343
	 * Singleton
344
	 * @static
345
	 */
346
	public static function init() {
347
		if ( ! self::$instance ) {
348
			self::$instance = new Jetpack;
349
350
			self::$instance->plugin_upgrade();
351
		}
352
353
		return self::$instance;
354
	}
355
356
	/**
357
	 * Must never be called statically
358
	 */
359
	function plugin_upgrade() {
360
		if ( Jetpack::is_active() ) {
361
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
362
			if ( JETPACK__VERSION != $version ) {
363
				// Prevent multiple upgrades at once - only a single process should trigger
364
				// an upgrade to avoid stampedes
365
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
366
					return;
367
				}
368
369
				// Set a short lock to prevent multiple instances of the upgrade
370
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
371
372
				// check which active modules actually exist and remove others from active_modules list
373
				$unfiltered_modules = Jetpack::get_active_modules();
374
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
375
				if ( array_diff( $unfiltered_modules, $modules ) ) {
376
					Jetpack::update_active_modules( $modules );
377
				}
378
379
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
380
381
				// Upgrade to 4.3.0
382
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
383
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
384
				}
385
386
				// Make sure Markdown for posts gets turned back on
387
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
388
					update_option( 'wpcom_publish_posts_with_markdown', true );
389
				}
390
391
				if ( did_action( 'wp_loaded' ) ) {
392
					self::upgrade_on_load();
393
				} else {
394
					add_action(
395
						'wp_loaded',
396
						array( __CLASS__, 'upgrade_on_load' )
397
					);
398
				}
399
			}
400
		}
401
	}
402
403
	/**
404
	 * Runs upgrade routines that need to have modules loaded.
405
	 */
406
	static function upgrade_on_load() {
407
408
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
409
		// This can happen in case Jetpack has been just upgraded and is
410
		// being initialized late during the page load. In this case we wait
411
		// until the next proper admin page load with Jetpack active.
412
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
413
			delete_transient( self::$plugin_upgrade_lock_key );
414
415
			return;
416
		}
417
418
		Jetpack::maybe_set_version_option();
419
420
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
421
			Jetpack_Widget_Conditions::migrate_post_type_rules();
422
		}
423
424
		if (
425
			class_exists( 'Jetpack_Sitemap_Manager' )
426
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
427
		) {
428
			do_action( 'jetpack_sitemaps_purge_data' );
429
		}
430
431
		delete_transient( self::$plugin_upgrade_lock_key );
432
	}
433
434
	static function activate_manage( ) {
435
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
436
			self::activate_module( 'manage', false, false );
437
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
438
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
439
		}
440
	}
441
442
	static function update_active_modules( $modules ) {
443
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
444
445
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
446
447
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
448
			$new_active_modules = array_diff( $modules, $current_modules );
449
			foreach( $new_active_modules as $module ) {
450
				/**
451
				 * Fires when a specific module is activated.
452
				 *
453
				 * @since 1.9.0
454
				 *
455
				 * @param string $module Module slug.
456
				 * @param boolean $success whether the module was activated. @since 4.2
457
				 */
458
				do_action( 'jetpack_activate_module', $module, $success );
459
460
				/**
461
				 * Fires when a module is activated.
462
				 * The dynamic part of the filter, $module, is the module slug.
463
				 *
464
				 * @since 1.9.0
465
				 *
466
				 * @param string $module Module slug.
467
				 */
468
				do_action( "jetpack_activate_module_$module", $module );
469
			}
470
471
			$new_deactive_modules = array_diff( $current_modules, $modules );
472
			foreach( $new_deactive_modules as $module ) {
473
				/**
474
				 * Fired after a module has been deactivated.
475
				 *
476
				 * @since 4.2.0
477
				 *
478
				 * @param string $module Module slug.
479
				 * @param boolean $success whether the module was deactivated.
480
				 */
481
				do_action( 'jetpack_deactivate_module', $module, $success );
482
				/**
483
				 * Fires when a module is deactivated.
484
				 * The dynamic part of the filter, $module, is the module slug.
485
				 *
486
				 * @since 1.9.0
487
				 *
488
				 * @param string $module Module slug.
489
				 */
490
				do_action( "jetpack_deactivate_module_$module", $module );
491
			}
492
		}
493
494
		return $success;
495
	}
496
497
	static function delete_active_modules() {
498
		self::update_active_modules( array() );
499
	}
500
501
	/**
502
	 * Constructor.  Initializes WordPress hooks
503
	 */
504
	private function __construct() {
505
		/*
506
		 * Check for and alert any deprecated hooks
507
		 */
508
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
509
510
		/*
511
		 * Enable enhanced handling of previewing sites in Calypso
512
		 */
513
		if ( Jetpack::is_active() ) {
514
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
515
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
516
		}
517
518
		/*
519
		 * Load things that should only be in Network Admin.
520
		 *
521
		 * For now blow away everything else until a more full
522
		 * understanding of what is needed at the network level is
523
		 * available
524
		 */
525
		if( is_multisite() ) {
526
			Jetpack_Network::init();
527
		}
528
529
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
530
531
		// Unlink user before deleting the user from .com
532
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
533
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
534
535
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
536
			@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...
537
538
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
539
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
540
541
			$this->require_jetpack_authentication();
542
543
			if ( Jetpack::is_active() ) {
544
				// Hack to preserve $HTTP_RAW_POST_DATA
545
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
546
547
				$signed = $this->verify_xml_rpc_signature();
548 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
549
					// The actual API methods.
550
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
551
				} else {
552
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
553
					// active Jetpack connection, so that additional users can link their account.
554
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
555
				}
556 View Code Duplication
			} else {
557
				// The bootstrap API methods.
558
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
559
				$signed = $this->verify_xml_rpc_signature();
560
				if ( $signed && ! is_wp_error( $signed ) ) {
561
					// the jetpack Provision method is available for blog-token-signed requests
562
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
563
				}
564
			}
565
566
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
567
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
568
		} elseif (
569
			is_admin() &&
570
			isset( $_POST['action'] ) && (
571
				'jetpack_upload_file' == $_POST['action'] ||
572
				'jetpack_update_file' == $_POST['action']
573
			)
574
		) {
575
			$this->require_jetpack_authentication();
576
			$this->add_remote_request_handlers();
577
		} else {
578
			if ( Jetpack::is_active() ) {
579
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
580
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
581
			}
582
		}
583
584
		if ( Jetpack::is_active() ) {
585
			Jetpack_Heartbeat::init();
586
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
587
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
588
				Jetpack_Search_Performance_Logger::init();
589
			}
590
		}
591
592
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
593
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
594
595
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
596
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
597
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
598
		}
599
600
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
601
602
		add_action( 'admin_init', array( $this, 'admin_init' ) );
603
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
604
605
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
606
607
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
608
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
609
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
610
611
		// returns HTTPS support status
612
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
613
614
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
615
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
616
617
		// JITM AJAX callback function
618
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
619
620
		// Universal ajax callback for all tracking events triggered via js
621
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
622
623
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
624
625
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
626
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
627
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
628
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
629
630
		// gutenberg locale
631
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_gutenberg_locale' ) );
632
633
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
634
635
		/**
636
		 * These actions run checks to load additional files.
637
		 * They check for external files or plugins, so they need to run as late as possible.
638
		 */
639
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
640
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
641
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
642
643
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
644
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
645
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
646
647
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
648
649
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
650
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
651
652
		// A filter to control all just in time messages
653
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
654
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
655
656
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
657
		// We should make sure to only do this for front end links.
658
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
659
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
660
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
661
662
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
663
			//so they point moderation links on emails to Calypso
664
			jetpack_require_lib( 'functions.wp-notify' );
665
		}
666
667
		// Update the Jetpack plan from API on heartbeats
668
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
669
670
		/**
671
		 * This is the hack to concatenate all css files into one.
672
		 * For description and reasoning see the implode_frontend_css method
673
		 *
674
		 * Super late priority so we catch all the registered styles
675
		 */
676
		if( !is_admin() ) {
677
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
678
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
679
		}
680
681
		/**
682
		 * These are sync actions that we need to keep track of for jitms
683
		 */
684
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
685
686
		// Actually push the stats on shutdown.
687
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
688
			add_action( 'shutdown', array( $this, 'push_stats' ) );
689
		}
690
	}
691
692
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
693
		$post = get_post( $post_id );
694
695
		if ( empty( $post ) ) {
696
			return $default_url;
697
		}
698
699
		$post_type = $post->post_type;
700
701
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
702
		// https://en.support.wordpress.com/custom-post-types/
703
		$allowed_post_types = array(
704
			'post' => 'post',
705
			'page' => 'page',
706
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
707
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
708
		);
709
710
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
711
			return $default_url;
712
		}
713
714
		$path_prefix = $allowed_post_types[ $post_type ];
715
716
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
0 ignored issues
show
Equals sign not aligned correctly; expected 1 space but found 2 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...
717
718
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
719
	}
720
721
	function point_edit_comment_links_to_calypso( $url ) {
722
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
723
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
724
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
725
			Jetpack::build_raw_urls( get_home_url() ),
726
			$query_args['amp;c']
727
		) );
728
	}
729
730
	function jetpack_track_last_sync_callback( $params ) {
731
		/**
732
		 * Filter to turn off jitm caching
733
		 *
734
		 * @since 5.4.0
735
		 *
736
		 * @param bool false Whether to cache just in time messages
737
		 */
738
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
739
			return $params;
740
		}
741
742
		if ( is_array( $params ) && isset( $params[0] ) ) {
743
			$option = $params[0];
744
			if ( 'active_plugins' === $option ) {
745
				// use the cache if we can, but not terribly important if it gets evicted
746
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
747
			}
748
		}
749
750
		return $params;
751
	}
752
753
	function jetpack_connection_banner_callback() {
754
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
755
756
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
757
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
758
			wp_send_json_success();
759
		}
760
761
		wp_die();
762
	}
763
764
	function jetpack_admin_ajax_tracks_callback() {
765
		// Check for nonce
766
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
767
			wp_die( 'Permissions check failed.' );
768
		}
769
770
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
771
			wp_die( 'No valid event name or type.' );
772
		}
773
774
		$tracks_data = array();
775
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
776
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
777
				$tracks_data = $_REQUEST['tracksEventProp'];
778
			} else {
779
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
780
			}
781
		}
782
783
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
784
		wp_send_json_success();
785
		wp_die();
786
	}
787
788
	/**
789
	 * The callback for the JITM ajax requests.
790
	 */
791
	function jetpack_jitm_ajax_callback() {
792
		// Check for nonce
793
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
794
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
795
		}
796
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
797
			$module_slug = $_REQUEST['jitmModule'];
798
			Jetpack::log( 'activate', $module_slug );
799
			Jetpack::activate_module( $module_slug, false, false );
800
			Jetpack::state( 'message', 'no_message' );
801
802
			//A Jetpack module is being activated through a JITM, track it
803
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
804
			$this->do_stats( 'server_side' );
805
806
			wp_send_json_success();
807
		}
808
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
809
			// get the hide_jitm options array
810
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
811
			$module_slug = $_REQUEST['jitmModule'];
812
813
			if( ! $jetpack_hide_jitm ) {
814
				$jetpack_hide_jitm = array(
815
					$module_slug => 'hide'
816
				);
817
			} else {
818
				$jetpack_hide_jitm[$module_slug] = 'hide';
819
			}
820
821
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
822
823
			//jitm is being dismissed forever, track it
824
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
825
			$this->do_stats( 'server_side' );
826
827
			wp_send_json_success();
828
		}
829 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
830
			$module_slug = $_REQUEST['jitmModule'];
831
832
			// User went to WordPress.com, track this
833
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
834
			$this->do_stats( 'server_side' );
835
836
			wp_send_json_success();
837
		}
838 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
839
			$track = $_REQUEST['jitmModule'];
840
841
			// User is viewing JITM, track it.
842
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
843
			$this->do_stats( 'server_side' );
844
845
			wp_send_json_success();
846
		}
847
	}
848
849
	/**
850
	 * If there are any stats that need to be pushed, but haven't been, push them now.
851
	 */
852
	function push_stats() {
853
		if ( ! empty( $this->stats ) ) {
854
			$this->do_stats( 'server_side' );
855
		}
856
	}
857
858
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
859
		switch( $cap ) {
860
			case 'jetpack_connect' :
861
			case 'jetpack_reconnect' :
0 ignored issues
show
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
862
				if ( Jetpack::is_development_mode() ) {
863
					$caps = array( 'do_not_allow' );
864
					break;
865
				}
866
				/**
867
				 * Pass through. If it's not development mode, these should match disconnect.
868
				 * Let users disconnect if it's development mode, just in case things glitch.
869
				 */
870
			case 'jetpack_disconnect' :
871
				/**
872
				 * In multisite, can individual site admins manage their own connection?
873
				 *
874
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
875
				 */
876
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
877
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
878
						/**
879
						 * We need to update the option name -- it's terribly unclear which
880
						 * direction the override goes.
881
						 *
882
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
0 ignored issues
show
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...
883
						 */
884
						$caps = array( 'do_not_allow' );
885
						break;
886
					}
887
				}
888
889
				$caps = array( 'manage_options' );
890
				break;
891
			case 'jetpack_manage_modules' :
892
			case 'jetpack_activate_modules' :
893
			case 'jetpack_deactivate_modules' :
894
				$caps = array( 'manage_options' );
895
				break;
896
			case 'jetpack_configure_modules' :
897
				$caps = array( 'manage_options' );
898
				break;
899
			case 'jetpack_network_admin_page':
900
			case 'jetpack_network_settings_page':
901
				$caps = array( 'manage_network_plugins' );
902
				break;
903
			case 'jetpack_network_sites_page':
904
				$caps = array( 'manage_sites' );
905
				break;
906
			case 'jetpack_admin_page' :
907
				if ( Jetpack::is_development_mode() ) {
908
					$caps = array( 'manage_options' );
909
					break;
910
				} else {
911
					$caps = array( 'read' );
912
				}
913
				break;
914
			case 'jetpack_connect_user' :
915
				if ( Jetpack::is_development_mode() ) {
916
					$caps = array( 'do_not_allow' );
917
					break;
918
				}
919
				$caps = array( 'read' );
920
				break;
921
		}
922
		return $caps;
923
	}
924
925
	function require_jetpack_authentication() {
926
		// Don't let anyone authenticate
927
		$_COOKIE = array();
928
		remove_all_filters( 'authenticate' );
929
		remove_all_actions( 'wp_login_failed' );
930
931
		if ( Jetpack::is_active() ) {
932
			// Allow Jetpack authentication
933
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
934
		}
935
	}
936
937
	/**
938
	 * Load language files
939
	 * @action plugins_loaded
940
	 */
941
	public static function plugin_textdomain() {
942
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
943
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
944
	}
945
946
	/**
947
	 * Register assets for use in various modules and the Jetpack admin page.
948
	 *
949
	 * @uses wp_script_is, wp_register_script, plugins_url
950
	 * @action wp_loaded
951
	 * @return null
952
	 */
953
	public function register_assets() {
954
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
955
			wp_register_script(
956
				'spin',
957
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
958
				false,
959
				'1.3'
960
			);
961
		}
962
963
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
964
			wp_register_script(
965
				'jquery.spin',
966
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
967
				array( 'jquery', 'spin' ),
968
				'1.3'
969
			);
970
		}
971
972 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
973
			wp_register_script(
974
				'jetpack-gallery-settings',
975
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
976
				array( 'media-views' ),
977
				'20121225'
978
			);
979
		}
980
981
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
982
			wp_register_script(
983
				'jetpack-twitter-timeline',
984
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
985
				array( 'jquery' ),
986
				'4.0.0',
987
				true
988
			);
989
		}
990
991
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
992
			wp_register_script(
993
				'jetpack-facebook-embed',
994
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
995
				array( 'jquery' ),
996
				null,
997
				true
998
			);
999
1000
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1001
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1002
			if ( ! is_numeric( $fb_app_id ) ) {
1003
				$fb_app_id = '';
1004
			}
1005
			wp_localize_script(
1006
				'jetpack-facebook-embed',
1007
				'jpfbembed',
1008
				array(
1009
					'appid' => $fb_app_id,
1010
					'locale' => $this->get_locale(),
1011
				)
1012
			);
1013
		}
1014
1015
		/**
1016
		 * As jetpack_register_genericons is by default fired off a hook,
1017
		 * the hook may have already fired by this point.
1018
		 * So, let's just trigger it manually.
1019
		 */
1020
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1021
		jetpack_register_genericons();
1022
1023
		/**
1024
		 * Register the social logos
1025
		 */
1026
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1027
		jetpack_register_social_logos();
1028
1029 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1030
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1031
	}
1032
1033
	/**
1034
	 * Guess locale from language code.
1035
	 *
1036
	 * @param string $lang Language code.
1037
	 * @return string|bool
1038
	 */
1039 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1040
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1041
			return 'en_US';
1042
		}
1043
1044
		if ( ! class_exists( 'GP_Locales' ) ) {
1045
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1046
				return false;
1047
			}
1048
1049
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1050
		}
1051
1052
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1053
			// WP.com: get_locale() returns 'it'
1054
			$locale = GP_Locales::by_slug( $lang );
1055
		} else {
1056
			// Jetpack: get_locale() returns 'it_IT';
1057
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1058
		}
1059
1060
		if ( ! $locale ) {
1061
			return false;
1062
		}
1063
1064
		if ( empty( $locale->facebook_locale ) ) {
1065
			if ( empty( $locale->wp_locale ) ) {
1066
				return false;
1067
			} else {
1068
				// Facebook SDK is smart enough to fall back to en_US if a
1069
				// locale isn't supported. Since supported Facebook locales
1070
				// can fall out of sync, we'll attempt to use the known
1071
				// wp_locale value and rely on said fallback.
1072
				return $locale->wp_locale;
1073
			}
1074
		}
1075
1076
		return $locale->facebook_locale;
1077
	}
1078
1079
	/**
1080
	 * Get the locale.
1081
	 *
1082
	 * @return string|bool
1083
	 */
1084
	function get_locale() {
1085
		$locale = $this->guess_locale_from_lang( get_locale() );
1086
1087
		if ( ! $locale ) {
1088
			$locale = 'en_US';
1089
		}
1090
1091
		return $locale;
1092
	}
1093
1094
	/**
1095
	 * Device Pixels support
1096
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1097
	 */
1098
	function devicepx() {
1099
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1100
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1101
		}
1102
	}
1103
1104
	/**
1105
	 * Return the network_site_url so that .com knows what network this site is a part of.
1106
	 * @param  bool $option
1107
	 * @return string
1108
	 */
1109
	public function jetpack_main_network_site_option( $option ) {
1110
		return network_site_url();
1111
	}
1112
	/**
1113
	 * Network Name.
1114
	 */
1115
	static function network_name( $option = null ) {
1116
		global $current_site;
1117
		return $current_site->site_name;
1118
	}
1119
	/**
1120
	 * Does the network allow new user and site registrations.
1121
	 * @return string
1122
	 */
1123
	static function network_allow_new_registrations( $option = null ) {
1124
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1125
	}
1126
	/**
1127
	 * Does the network allow admins to add new users.
1128
	 * @return boolian
1129
	 */
1130
	static function network_add_new_users( $option = null ) {
1131
		return (bool) get_site_option( 'add_new_users' );
1132
	}
1133
	/**
1134
	 * File upload psace left per site in MB.
1135
	 *  -1 means NO LIMIT.
1136
	 * @return number
1137
	 */
1138
	static function network_site_upload_space( $option = null ) {
1139
		// value in MB
1140
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1141
	}
1142
1143
	/**
1144
	 * Network allowed file types.
1145
	 * @return string
1146
	 */
1147
	static function network_upload_file_types( $option = null ) {
1148
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1149
	}
1150
1151
	/**
1152
	 * Maximum file upload size set by the network.
1153
	 * @return number
1154
	 */
1155
	static function network_max_upload_file_size( $option = null ) {
1156
		// value in KB
1157
		return get_site_option( 'fileupload_maxk', 300 );
1158
	}
1159
1160
	/**
1161
	 * Lets us know if a site allows admins to manage the network.
1162
	 * @return array
1163
	 */
1164
	static function network_enable_administration_menus( $option = null ) {
1165
		return get_site_option( 'menu_items' );
1166
	}
1167
1168
	/**
1169
	 * If a user has been promoted to or demoted from admin, we need to clear the
1170
	 * jetpack_other_linked_admins transient.
1171
	 *
1172
	 * @since 4.3.2
1173
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1174
	 *
1175
	 * @param int    $user_id   The user ID whose role changed.
1176
	 * @param string $role      The new role.
1177
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
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...
1178
	 */
1179
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1180
		if ( 'administrator' == $role
1181
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1182
			|| is_null( $old_roles )
1183
		) {
1184
			delete_transient( 'jetpack_other_linked_admins' );
1185
		}
1186
	}
1187
1188
	/**
1189
	 * Checks to see if there are any other users available to become primary
1190
	 * Users must both:
1191
	 * - Be linked to wpcom
1192
	 * - Be an admin
1193
	 *
1194
	 * @return mixed False if no other users are linked, Int if there are.
1195
	 */
1196
	static function get_other_linked_admins() {
1197
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1198
1199
		if ( false === $other_linked_users ) {
1200
			$admins = get_users( array( 'role' => 'administrator' ) );
1201
			if ( count( $admins ) > 1 ) {
1202
				$available = array();
1203
				foreach ( $admins as $admin ) {
1204
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1205
						$available[] = $admin->ID;
1206
					}
1207
				}
1208
1209
				$count_connected_admins = count( $available );
1210
				if ( count( $available ) > 1 ) {
1211
					$other_linked_users = $count_connected_admins;
1212
				} else {
1213
					$other_linked_users = 0;
1214
				}
1215
			} else {
1216
				$other_linked_users = 0;
1217
			}
1218
1219
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1220
		}
1221
1222
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1223
	}
1224
1225
	/**
1226
	 * Return whether we are dealing with a multi network setup or not.
1227
	 * The reason we are type casting this is because we want to avoid the situation where
1228
	 * the result is false since when is_main_network_option return false it cases
1229
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1230
	 * database which could be set to anything as opposed to what this function returns.
1231
	 * @param  bool  $option
1232
	 *
1233
	 * @return boolean
1234
	 */
1235
	public function is_main_network_option( $option ) {
1236
		// return '1' or ''
1237
		return (string) (bool) Jetpack::is_multi_network();
1238
	}
1239
1240
	/**
1241
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1242
	 *
1243
	 * @param  string  $option
1244
	 * @return boolean
1245
	 */
1246
	public function is_multisite( $option ) {
1247
		return (string) (bool) is_multisite();
1248
	}
1249
1250
	/**
1251
	 * Implemented since there is no core is multi network function
1252
	 * Right now there is no way to tell if we which network is the dominant network on the system
1253
	 *
1254
	 * @since  3.3
1255
	 * @return boolean
1256
	 */
1257
	public static function is_multi_network() {
1258
		global  $wpdb;
1259
1260
		// if we don't have a multi site setup no need to do any more
1261
		if ( ! is_multisite() ) {
1262
			return false;
1263
		}
1264
1265
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1266
		if ( $num_sites > 1 ) {
1267
			return true;
1268
		} else {
1269
			return false;
1270
		}
1271
	}
1272
1273
	/**
1274
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1275
	 * @return null
1276
	 */
1277
	function update_jetpack_main_network_site_option() {
1278
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1279
	}
1280
	/**
1281
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1282
	 *
1283
	 */
1284
	function update_jetpack_network_settings() {
1285
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1286
		// Only sync this info for the main network site.
1287
	}
1288
1289
	/**
1290
	 * Get back if the current site is single user site.
1291
	 *
1292
	 * @return bool
1293
	 */
1294
	public static function is_single_user_site() {
1295
		global $wpdb;
1296
1297 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1298
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1299
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1300
		}
1301
		return 1 === (int) $some_users;
1302
	}
1303
1304
	/**
1305
	 * Returns true if the site has file write access false otherwise.
1306
	 * @return string ( '1' | '0' )
1307
	 **/
1308
	public static function file_system_write_access() {
1309
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1310
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1311
		}
1312
1313
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1314
1315
		$filesystem_method = get_filesystem_method();
1316
		if ( $filesystem_method === 'direct' ) {
1317
			return 1;
1318
		}
1319
1320
		ob_start();
1321
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1322
		ob_end_clean();
1323
		if ( $filesystem_credentials_are_stored ) {
1324
			return 1;
1325
		}
1326
		return 0;
1327
	}
1328
1329
	/**
1330
	 * Finds out if a site is using a version control system.
1331
	 * @return string ( '1' | '0' )
1332
	 **/
1333
	public static function is_version_controlled() {
1334
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1335
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1336
	}
1337
1338
	/**
1339
	 * Determines whether the current theme supports featured images or not.
1340
	 * @return string ( '1' | '0' )
1341
	 */
1342
	public static function featured_images_enabled() {
1343
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1344
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1345
	}
1346
1347
	/**
1348
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1349
	 *
1350
	 * @deprecated 4.7 use get_avatar_url instead.
1351
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1352
	 * @param int $size Size of the avatar image
1353
	 * @param string $default URL to a default image to use if no avatar is available
1354
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1355
	 *
1356
	 * @return array
1357
	 */
1358
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1359
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1360
		return get_avatar_url( $id_or_email, array(
1361
			'size' => $size,
1362
			'default' => $default,
1363
			'force_default' => $force_display,
1364
		) );
1365
	}
1366
1367
	/**
1368
	 * jetpack_updates is saved in the following schema:
1369
	 *
1370
	 * array (
1371
	 *      'plugins'                       => (int) Number of plugin updates available.
1372
	 *      'themes'                        => (int) Number of theme updates available.
1373
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1374
	 *      'translations'                  => (int) Number of translation updates available.
1375
	 *      'total'                         => (int) Total of all available updates.
1376
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1377
	 * )
1378
	 * @return array
1379
	 */
1380
	public static function get_updates() {
1381
		$update_data = wp_get_update_data();
1382
1383
		// Stores the individual update counts as well as the total count.
1384
		if ( isset( $update_data['counts'] ) ) {
1385
			$updates = $update_data['counts'];
1386
		}
1387
1388
		// If we need to update WordPress core, let's find the latest version number.
1389 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1390
			$cur = get_preferred_from_update_core();
1391
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1392
				$updates['wp_update_version'] = $cur->current;
1393
			}
1394
		}
1395
		return isset( $updates ) ? $updates : array();
1396
	}
1397
1398
	public static function get_update_details() {
1399
		$update_details = array(
1400
			'update_core' => get_site_transient( 'update_core' ),
1401
			'update_plugins' => get_site_transient( 'update_plugins' ),
1402
			'update_themes' => get_site_transient( 'update_themes' ),
1403
		);
1404
		return $update_details;
1405
	}
1406
1407
	public static function refresh_update_data() {
1408
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1409
1410
	}
1411
1412
	public static function refresh_theme_data() {
1413
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1414
	}
1415
1416
	/**
1417
	 * Is Jetpack active?
1418
	 */
1419
	public static function is_active() {
1420
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1421
	}
1422
1423
	/**
1424
	 * Make an API call to WordPress.com for plan status
1425
	 *
1426
	 * @uses Jetpack_Options::get_option()
1427
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1428
	 * @uses update_option()
1429
	 *
1430
	 * @access public
1431
	 * @static
1432
	 *
1433
	 * @return bool True if plan is updated, false if no update
1434
	 */
1435
	public static function refresh_active_plan_from_wpcom() {
1436
		// Make the API request
1437
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1438
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1439
1440
		// Bail if there was an error or malformed response
1441
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1442
			return false;
1443
		}
1444
1445
		// Decode the results
1446
		$results = json_decode( $response['body'], true );
1447
1448
		// Bail if there were no results or plan details returned
1449
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1450
			return false;
1451
		}
1452
1453
		// Store the option and return true if updated
1454
		return update_option( 'jetpack_active_plan', $results['plan'] );
1455
	}
1456
1457
	/**
1458
	 * Get the plan that this Jetpack site is currently using
1459
	 *
1460
	 * @uses get_option()
1461
	 *
1462
	 * @access public
1463
	 * @static
1464
	 *
1465
	 * @return array Active Jetpack plan details
1466
	 */
1467
	public static function get_active_plan() {
1468
		global $active_plan_cache;
1469
1470
		// this can be expensive to compute so we cache for the duration of a request
1471
		if ( is_array( $active_plan_cache ) && ! empty( $active_plan_cache ) ) {
1472
			return $active_plan_cache;
1473
		}
1474
1475
		$plan = get_option( 'jetpack_active_plan', array() );
1476
1477
		// Set the default options
1478
		$plan = wp_parse_args( $plan, array(
1479
			'product_slug' => 'jetpack_free',
1480
			'class'        => 'free',
1481
			'features'     => array(
1482
				'active' => array()
1483
			),
1484
		) );
1485
1486
		$supports = array();
1487
1488
		// Define what paid modules are supported by personal plans
1489
		$personal_plans = array(
1490
			'jetpack_personal',
1491
			'jetpack_personal_monthly',
1492
			'personal-bundle',
1493
		);
1494
1495
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1496
			// special support value, not a module but a separate plugin
1497
			$supports[] = 'akismet';
1498
			$plan['class'] = 'personal';
1499
		}
1500
1501
		// Define what paid modules are supported by premium plans
1502
		$premium_plans = array(
1503
			'jetpack_premium',
1504
			'jetpack_premium_monthly',
1505
			'value_bundle',
1506
		);
1507
1508 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1509
			$supports[] = 'akismet';
1510
			$supports[] = 'simple-payments';
1511
			$supports[] = 'vaultpress';
1512
			$plan['class'] = 'premium';
1513
		}
1514
1515
		// Define what paid modules are supported by professional plans
1516
		$business_plans = array(
1517
			'jetpack_business',
1518
			'jetpack_business_monthly',
1519
			'business-bundle',
1520
			'vip',
1521
		);
1522
1523 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1524
			$supports[] = 'akismet';
1525
			$supports[] = 'simple-payments';
1526
			$supports[] = 'vaultpress';
1527
			$plan['class'] = 'business';
1528
		}
1529
1530
		// get available features
1531
		foreach ( self::get_available_modules() as $module_slug ) {
1532
			$module = self::get_module( $module_slug );
1533
			if ( ! isset( $module ) || ! is_array( $module ) ) {
1534
				continue;
1535
			}
1536
			if ( in_array( 'free', $module['plan_classes'] ) || in_array( $plan['class'], $module['plan_classes'] ) ) {
1537
				$supports[] = $module_slug;
1538
			}
1539
		}
1540
1541
		$plan['supports'] = $supports;
1542
1543
		$active_plan_cache = $plan;
1544
1545
		return $plan;
1546
	}
1547
1548
	/**
1549
	 * Determine whether the active plan supports a particular feature
1550
	 *
1551
	 * @uses Jetpack::get_active_plan()
1552
	 *
1553
	 * @access public
1554
	 * @static
1555
	 *
1556
	 * @return bool True if plan supports feature, false if not
1557
	 */
1558
	public static function active_plan_supports( $feature ) {
1559
		$plan = Jetpack::get_active_plan();
1560
1561
		// Manually mapping WordPress.com features to Jetpack module slugs
1562
		foreach ( $plan['features']['active'] as $wpcom_feature ) {
1563
			switch ( $wpcom_feature ) {
1564
				case 'wordads-jetpack';
0 ignored issues
show
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1565
1566
				// WordAds are supported for this site
1567
				if ( 'wordads' === $feature ) {
1568
					return true;
1569
				}
1570
				break;
1571
			}
1572
		}
1573
1574
		if (
1575
			in_array( $feature, $plan['supports'] )
1576
			|| in_array( $feature, $plan['features']['active'] )
1577
		) {
1578
			return true;
1579
		}
1580
1581
		return false;
1582
	}
1583
1584
	/**
1585
	 * Is Jetpack in development (offline) mode?
1586
	 */
1587
	public static function is_development_mode() {
1588
		$development_mode = false;
1589
1590
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1591
			$development_mode = JETPACK_DEV_DEBUG;
1592
		} elseif ( $site_url = site_url() ) {
1593
			$development_mode = false === strpos( $site_url, '.' );
1594
		}
1595
1596
		/**
1597
		 * Filters Jetpack's development mode.
1598
		 *
1599
		 * @see https://jetpack.com/support/development-mode/
1600
		 *
1601
		 * @since 2.2.1
1602
		 *
1603
		 * @param bool $development_mode Is Jetpack's development mode active.
1604
		 */
1605
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1606
		return $development_mode;
1607
	}
1608
1609
	/**
1610
	 * Whether the site is currently onboarding or not.
1611
	 * A site is considered as being onboarded if it currently has an onboarding token.
1612
	 *
1613
	 * @since 5.8
1614
	 *
1615
	 * @access public
1616
	 * @static
1617
	 *
1618
	 * @return bool True if the site is currently onboarding, false otherwise
1619
	 */
1620
	public static function is_onboarding() {
1621
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1622
	}
1623
1624
	/**
1625
	* Get Jetpack development mode notice text and notice class.
1626
	*
1627
	* Mirrors the checks made in Jetpack::is_development_mode
1628
	*
1629
	*/
1630
	public static function show_development_mode_notice() {
1631
		if ( Jetpack::is_development_mode() ) {
1632
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1633
				$notice = sprintf(
1634
					/* translators: %s is a URL */
1635
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1636
					'https://jetpack.com/support/development-mode/'
1637
				);
1638
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1639
				$notice = sprintf(
1640
					/* translators: %s is a URL */
1641
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1642
					'https://jetpack.com/support/development-mode/'
1643
				);
1644
			} else {
1645
				$notice = sprintf(
1646
					/* translators: %s is a URL */
1647
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1648
					'https://jetpack.com/support/development-mode/'
1649
				);
1650
			}
1651
1652
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1653
		}
1654
1655
		// Throw up a notice if using a development version and as for feedback.
1656
		if ( Jetpack::is_development_version() ) {
1657
			/* translators: %s is a URL */
1658
			$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/' );
1659
1660
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1661
		}
1662
		// Throw up a notice if using staging mode
1663
		if ( Jetpack::is_staging_site() ) {
1664
			/* translators: %s is a URL */
1665
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1666
1667
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1668
		}
1669
	}
1670
1671
	/**
1672
	 * Whether Jetpack's version maps to a public release, or a development version.
1673
	 */
1674
	public static function is_development_version() {
1675
		/**
1676
		 * Allows filtering whether this is a development version of Jetpack.
1677
		 *
1678
		 * This filter is especially useful for tests.
1679
		 *
1680
		 * @since 4.3.0
1681
		 *
1682
		 * @param bool $development_version Is this a develoment version of Jetpack?
1683
		 */
1684
		return (bool) apply_filters(
1685
			'jetpack_development_version',
1686
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1687
		);
1688
	}
1689
1690
	/**
1691
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1692
	 */
1693
	public static function is_user_connected( $user_id = false ) {
1694
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1695
		if ( ! $user_id ) {
1696
			return false;
1697
		}
1698
1699
		return (bool) Jetpack_Data::get_access_token( $user_id );
1700
	}
1701
1702
	/**
1703
	 * Get the wpcom user data of the current|specified connected user.
1704
	 */
1705
	public static function get_connected_user_data( $user_id = null ) {
1706
		if ( ! $user_id ) {
1707
			$user_id = get_current_user_id();
1708
		}
1709
1710
		$transient_key = "jetpack_connected_user_data_$user_id";
1711
1712
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1713
			return $cached_user_data;
1714
		}
1715
1716
		Jetpack::load_xml_rpc_client();
1717
		$xml = new Jetpack_IXR_Client( array(
1718
			'user_id' => $user_id,
1719
		) );
1720
		$xml->query( 'wpcom.getUser' );
1721
		if ( ! $xml->isError() ) {
1722
			$user_data = $xml->getResponse();
1723
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1724
			return $user_data;
1725
		}
1726
1727
		return false;
1728
	}
1729
1730
	/**
1731
	 * Get the wpcom email of the current|specified connected user.
1732
	 */
1733 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1734
		if ( ! $user_id ) {
1735
			$user_id = get_current_user_id();
1736
		}
1737
		Jetpack::load_xml_rpc_client();
1738
		$xml = new Jetpack_IXR_Client( array(
1739
			'user_id' => $user_id,
1740
		) );
1741
		$xml->query( 'wpcom.getUserEmail' );
1742
		if ( ! $xml->isError() ) {
1743
			return $xml->getResponse();
1744
		}
1745
		return false;
1746
	}
1747
1748
	/**
1749
	 * Get the wpcom email of the master user.
1750
	 */
1751
	public static function get_master_user_email() {
1752
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1753
		if ( $master_user_id ) {
1754
			return self::get_connected_user_email( $master_user_id );
1755
		}
1756
		return '';
1757
	}
1758
1759
	function current_user_is_connection_owner() {
1760
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1761
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1762
	}
1763
1764
	/**
1765
	 * Gets current user IP address.
1766
	 *
1767
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1768
	 *
1769
	 * @return string                  Current user IP address.
1770
	 */
1771
	public static function current_user_ip( $check_all_headers = false ) {
1772
		if ( $check_all_headers ) {
1773
			foreach ( array(
1774
				'HTTP_CF_CONNECTING_IP',
1775
				'HTTP_CLIENT_IP',
1776
				'HTTP_X_FORWARDED_FOR',
1777
				'HTTP_X_FORWARDED',
1778
				'HTTP_X_CLUSTER_CLIENT_IP',
1779
				'HTTP_FORWARDED_FOR',
1780
				'HTTP_FORWARDED',
1781
				'HTTP_VIA',
1782
			) as $key ) {
1783
				if ( ! empty( $_SERVER[ $key ] ) ) {
1784
					return $_SERVER[ $key ];
1785
				}
1786
			}
1787
		}
1788
1789
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1790
	}
1791
1792
	/**
1793
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1794
	 */
1795
	function extra_oembed_providers() {
1796
		// Cloudup: https://dev.cloudup.com/#oembed
1797
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1798
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1799
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1800
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1801
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1802
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1803
	}
1804
1805
	/**
1806
	 * Synchronize connected user role changes
1807
	 */
1808
	function user_role_change( $user_id ) {
1809
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1810
		Jetpack_Sync_Users::user_role_change( $user_id );
1811
	}
1812
1813
	/**
1814
	 * Loads the currently active modules.
1815
	 */
1816
	public static function load_modules() {
1817
		if (
1818
			! self::is_active()
1819
			&& ! self::is_development_mode()
1820
			&& ! self::is_onboarding()
1821
			&& (
1822
				! is_multisite()
1823
				|| ! get_site_option( 'jetpack_protect_active' )
1824
			)
1825
		) {
1826
			return;
1827
		}
1828
1829
		$version = Jetpack_Options::get_option( 'version' );
1830 View Code Duplication
		if ( ! $version ) {
1831
			$version = $old_version = JETPACK__VERSION . ':' . time();
1832
			/** This action is documented in class.jetpack.php */
1833
			do_action( 'updating_jetpack_version', $version, false );
1834
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1835
		}
1836
		list( $version ) = explode( ':', $version );
1837
1838
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1839
1840
		$modules_data = array();
1841
1842
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1843
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1844
			$updated_modules = array();
1845
			foreach ( $modules as $module ) {
1846
				$modules_data[ $module ] = Jetpack::get_module( $module );
1847
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1848
					continue;
1849
				}
1850
1851
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1852
					continue;
1853
				}
1854
1855
				$updated_modules[] = $module;
1856
			}
1857
1858
			$modules = array_diff( $modules, $updated_modules );
1859
		}
1860
1861
		$is_development_mode = Jetpack::is_development_mode();
1862
1863
		foreach ( $modules as $index => $module ) {
1864
			// If we're in dev mode, disable modules requiring a connection
1865
			if ( $is_development_mode ) {
1866
				// Prime the pump if we need to
1867
				if ( empty( $modules_data[ $module ] ) ) {
1868
					$modules_data[ $module ] = Jetpack::get_module( $module );
1869
				}
1870
				// If the module requires a connection, but we're in local mode, don't include it.
1871
				if ( $modules_data[ $module ]['requires_connection'] ) {
1872
					continue;
1873
				}
1874
			}
1875
1876
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1877
				continue;
1878
			}
1879
1880
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1881
				unset( $modules[ $index ] );
1882
				self::update_active_modules( array_values( $modules ) );
1883
				continue;
1884
			}
1885
1886
			/**
1887
			 * Fires when a specific module is loaded.
1888
			 * The dynamic part of the hook, $module, is the module slug.
1889
			 *
1890
			 * @since 1.1.0
1891
			 */
1892
			do_action( 'jetpack_module_loaded_' . $module );
1893
		}
1894
1895
		/**
1896
		 * Fires when all the modules are loaded.
1897
		 *
1898
		 * @since 1.1.0
1899
		 */
1900
		do_action( 'jetpack_modules_loaded' );
1901
1902
		// 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.
1903
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1904
	}
1905
1906
	/**
1907
	 * Check if Jetpack's REST API compat file should be included
1908
	 * @action plugins_loaded
1909
	 * @return null
1910
	 */
1911
	public function check_rest_api_compat() {
1912
		/**
1913
		 * Filters the list of REST API compat files to be included.
1914
		 *
1915
		 * @since 2.2.5
1916
		 *
1917
		 * @param array $args Array of REST API compat files to include.
1918
		 */
1919
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1920
1921
		if ( function_exists( 'bbpress' ) )
1922
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1923
1924
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1925
			require_once $_jetpack_rest_api_compat_include;
1926
	}
1927
1928
	/**
1929
	 * Gets all plugins currently active in values, regardless of whether they're
1930
	 * traditionally activated or network activated.
1931
	 *
1932
	 * @todo Store the result in core's object cache maybe?
0 ignored issues
show
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...
1933
	 */
1934
	public static function get_active_plugins() {
1935
		$active_plugins = (array) get_option( 'active_plugins', array() );
1936
1937
		if ( is_multisite() ) {
1938
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1939
			// whereas active_plugins stores them in the values.
1940
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1941
			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...
1942
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1943
			}
1944
		}
1945
1946
		sort( $active_plugins );
1947
1948
		return array_unique( $active_plugins );
1949
	}
1950
1951
	/**
1952
	 * Gets and parses additional plugin data to send with the heartbeat data
1953
	 *
1954
	 * @since 3.8.1
1955
	 *
1956
	 * @return array Array of plugin data
1957
	 */
1958
	public static function get_parsed_plugin_data() {
1959
		if ( ! function_exists( 'get_plugins' ) ) {
1960
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1961
		}
1962
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1963
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1964
		$active_plugins = Jetpack::get_active_plugins();
1965
1966
		$plugins = array();
1967
		foreach ( $all_plugins as $path => $plugin_data ) {
1968
			$plugins[ $path ] = array(
1969
					'is_active' => in_array( $path, $active_plugins ),
1970
					'file'      => $path,
1971
					'name'      => $plugin_data['Name'],
1972
					'version'   => $plugin_data['Version'],
1973
					'author'    => $plugin_data['Author'],
1974
			);
1975
		}
1976
1977
		return $plugins;
1978
	}
1979
1980
	/**
1981
	 * Gets and parses theme data to send with the heartbeat data
1982
	 *
1983
	 * @since 3.8.1
1984
	 *
1985
	 * @return array Array of theme data
1986
	 */
1987
	public static function get_parsed_theme_data() {
1988
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1989
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1990
1991
		$themes = array();
1992
		foreach ( $all_themes as $slug => $theme_data ) {
1993
			$theme_headers = array();
1994
			foreach ( $header_keys as $header_key ) {
1995
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1996
			}
1997
1998
			$themes[ $slug ] = array(
1999
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2000
					'slug' => $slug,
2001
					'theme_root' => $theme_data->get_theme_root_uri(),
2002
					'parent' => $theme_data->parent(),
2003
					'headers' => $theme_headers
2004
			);
2005
		}
2006
2007
		return $themes;
2008
	}
2009
2010
	/**
2011
	 * Checks whether a specific plugin is active.
2012
	 *
2013
	 * We don't want to store these in a static variable, in case
2014
	 * there are switch_to_blog() calls involved.
2015
	 */
2016
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2017
		return in_array( $plugin, self::get_active_plugins() );
2018
	}
2019
2020
	/**
2021
	 * Check if Jetpack's Open Graph tags should be used.
2022
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2023
	 *
2024
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2025
	 * @action plugins_loaded
2026
	 * @return null
2027
	 */
2028
	public function check_open_graph() {
2029
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2030
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2031
		}
2032
2033
		$active_plugins = self::get_active_plugins();
2034
2035
		if ( ! empty( $active_plugins ) ) {
2036
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2037
				if ( in_array( $plugin, $active_plugins ) ) {
2038
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2039
					break;
2040
				}
2041
			}
2042
		}
2043
2044
		/**
2045
		 * Allow the addition of Open Graph Meta Tags to all pages.
2046
		 *
2047
		 * @since 2.0.3
2048
		 *
2049
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2050
		 */
2051
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2052
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2053
		}
2054
	}
2055
2056
	/**
2057
	 * Check if Jetpack's Twitter tags should be used.
2058
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2059
	 *
2060
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2061
	 * @action plugins_loaded
2062
	 * @return null
2063
	 */
2064
	public function check_twitter_tags() {
2065
2066
		$active_plugins = self::get_active_plugins();
2067
2068
		if ( ! empty( $active_plugins ) ) {
2069
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2070
				if ( in_array( $plugin, $active_plugins ) ) {
2071
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2072
					break;
2073
				}
2074
			}
2075
		}
2076
2077
		/**
2078
		 * Allow Twitter Card Meta tags to be disabled.
2079
		 *
2080
		 * @since 2.6.0
2081
		 *
2082
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2083
		 */
2084
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2085
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2086
		}
2087
	}
2088
2089
	/**
2090
	 * Allows plugins to submit security reports.
2091
 	 *
2092
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2093
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2094
	 * @param array   $args         See definitions above
2095
	 */
2096
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2097
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2098
	}
2099
2100
/* Jetpack Options API */
2101
2102
	public static function get_option_names( $type = 'compact' ) {
2103
		return Jetpack_Options::get_option_names( $type );
2104
	}
2105
2106
	/**
2107
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2108
 	 *
2109
	 * @param string $name    Option name
2110
	 * @param mixed  $default (optional)
2111
	 */
2112
	public static function get_option( $name, $default = false ) {
2113
		return Jetpack_Options::get_option( $name, $default );
2114
	}
2115
2116
	/**
2117
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2118
 	 *
2119
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2120
	 * @param string $name  Option name
2121
	 * @param mixed  $value Option value
2122
	 */
2123
	public static function update_option( $name, $value ) {
2124
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2125
		return Jetpack_Options::update_option( $name, $value );
2126
	}
2127
2128
	/**
2129
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2130
 	 *
2131
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2132
	 * @param array $array array( option name => option value, ... )
2133
	 */
2134
	public static function update_options( $array ) {
2135
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2136
		return Jetpack_Options::update_options( $array );
2137
	}
2138
2139
	/**
2140
	 * Deletes the given option.  May be passed multiple option names as an array.
2141
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2142
	 *
2143
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2144
	 * @param string|array $names
2145
	 */
2146
	public static function delete_option( $names ) {
2147
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2148
		return Jetpack_Options::delete_option( $names );
2149
	}
2150
2151
	/**
2152
	 * Enters a user token into the user_tokens option
2153
	 *
2154
	 * @param int $user_id
2155
	 * @param string $token
2156
	 * return bool
2157
	 */
2158
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2159
		// not designed for concurrent updates
2160
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2161
		if ( ! is_array( $user_tokens ) )
2162
			$user_tokens = array();
2163
		$user_tokens[$user_id] = $token;
2164
		if ( $is_master_user ) {
2165
			$master_user = $user_id;
2166
			$options     = compact( 'user_tokens', 'master_user' );
2167
		} else {
2168
			$options = compact( 'user_tokens' );
2169
		}
2170
		return Jetpack_Options::update_options( $options );
2171
	}
2172
2173
	/**
2174
	 * Returns an array of all PHP files in the specified absolute path.
2175
	 * Equivalent to glob( "$absolute_path/*.php" ).
2176
	 *
2177
	 * @param string $absolute_path The absolute path of the directory to search.
2178
	 * @return array Array of absolute paths to the PHP files.
2179
	 */
2180
	public static function glob_php( $absolute_path ) {
2181
		if ( function_exists( 'glob' ) ) {
2182
			return glob( "$absolute_path/*.php" );
2183
		}
2184
2185
		$absolute_path = untrailingslashit( $absolute_path );
2186
		$files = array();
2187
		if ( ! $dir = @opendir( $absolute_path ) ) {
2188
			return $files;
2189
		}
2190
2191
		while ( false !== $file = readdir( $dir ) ) {
2192
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2193
				continue;
2194
			}
2195
2196
			$file = "$absolute_path/$file";
2197
2198
			if ( ! is_file( $file ) ) {
2199
				continue;
2200
			}
2201
2202
			$files[] = $file;
2203
		}
2204
2205
		closedir( $dir );
2206
2207
		return $files;
2208
	}
2209
2210
	public static function activate_new_modules( $redirect = false ) {
2211
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2212
			return;
2213
		}
2214
2215
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2216 View Code Duplication
		if ( ! $jetpack_old_version ) {
2217
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2218
			/** This action is documented in class.jetpack.php */
2219
			do_action( 'updating_jetpack_version', $version, false );
2220
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2221
		}
2222
2223
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2224
2225
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2226
			return;
2227
		}
2228
2229
		$active_modules     = Jetpack::get_active_modules();
2230
		$reactivate_modules = array();
2231
		foreach ( $active_modules as $active_module ) {
2232
			$module = Jetpack::get_module( $active_module );
2233
			if ( ! isset( $module['changed'] ) ) {
2234
				continue;
2235
			}
2236
2237
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2238
				continue;
2239
			}
2240
2241
			$reactivate_modules[] = $active_module;
2242
			Jetpack::deactivate_module( $active_module );
2243
		}
2244
2245
		$new_version = JETPACK__VERSION . ':' . time();
2246
		/** This action is documented in class.jetpack.php */
2247
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2248
		Jetpack_Options::update_options(
2249
			array(
2250
				'version'     => $new_version,
2251
				'old_version' => $jetpack_old_version,
2252
			)
2253
		);
2254
2255
		Jetpack::state( 'message', 'modules_activated' );
2256
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
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...
2257
2258
		if ( $redirect ) {
2259
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2260
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2261
				$page = $_GET['page'];
2262
			}
2263
2264
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2265
			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...
2266
		}
2267
	}
2268
2269
	/**
2270
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2271
	 * Make sure to tuck away module "library" files in a sub-directory.
2272
	 */
2273
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2274
		static $modules = null;
2275
2276
		if ( ! isset( $modules ) ) {
2277
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2278
			// Use the cache if we're on the front-end and it's available...
2279
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2280
				$modules = $available_modules_option[ JETPACK__VERSION ];
2281
			} else {
2282
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2283
2284
				$modules = array();
2285
2286
				foreach ( $files as $file ) {
2287
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2288
						continue;
2289
					}
2290
2291
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2292
				}
2293
2294
				Jetpack_Options::update_option( 'available_modules', array(
2295
					JETPACK__VERSION => $modules,
2296
				) );
2297
			}
2298
		}
2299
2300
		/**
2301
		 * Filters the array of modules available to be activated.
2302
		 *
2303
		 * @since 2.4.0
2304
		 *
2305
		 * @param array $modules Array of available modules.
2306
		 * @param string $min_version Minimum version number required to use modules.
2307
		 * @param string $max_version Maximum version number required to use modules.
2308
		 */
2309
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2310
2311
		if ( ! $min_version && ! $max_version ) {
2312
			return array_keys( $mods );
2313
		}
2314
2315
		$r = array();
2316
		foreach ( $mods as $slug => $introduced ) {
2317
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2318
				continue;
2319
			}
2320
2321
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2322
				continue;
2323
			}
2324
2325
			$r[] = $slug;
2326
		}
2327
2328
		return $r;
2329
	}
2330
2331
	/**
2332
	 * Default modules loaded on activation.
2333
	 */
2334
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2335
		$return = array();
2336
2337
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2338
			$module_data = Jetpack::get_module( $module );
2339
2340
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2341
				case 'yes' :
2342
					$return[] = $module;
2343
					break;
2344
				case 'public' :
2345
					if ( Jetpack_Options::get_option( 'public' ) ) {
2346
						$return[] = $module;
2347
					}
2348
					break;
2349
				case 'no' :
2350
				default :
0 ignored issues
show
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...
2351
					break;
2352
			}
2353
		}
2354
		/**
2355
		 * Filters the array of default modules.
2356
		 *
2357
		 * @since 2.5.0
2358
		 *
2359
		 * @param array $return Array of default modules.
2360
		 * @param string $min_version Minimum version number required to use modules.
2361
		 * @param string $max_version Maximum version number required to use modules.
2362
		 */
2363
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2364
	}
2365
2366
	/**
2367
	 * Checks activated modules during auto-activation to determine
2368
	 * if any of those modules are being deprecated.  If so, close
2369
	 * them out, and add any replacement modules.
2370
	 *
2371
	 * Runs at priority 99 by default.
2372
	 *
2373
	 * This is run late, so that it can still activate a module if
2374
	 * the new module is a replacement for another that the user
2375
	 * currently has active, even if something at the normal priority
2376
	 * would kibosh everything.
2377
	 *
2378
	 * @since 2.6
2379
	 * @uses jetpack_get_default_modules filter
2380
	 * @param array $modules
2381
	 * @return array
2382
	 */
2383
	function handle_deprecated_modules( $modules ) {
2384
		$deprecated_modules = array(
2385
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2386
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2387
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2388
		);
2389
2390
		// Don't activate SSO if they never completed activating WPCC.
2391
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2392
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2393
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2394
				$deprecated_modules['wpcc'] = null;
2395
			}
2396
		}
2397
2398
		foreach ( $deprecated_modules as $module => $replacement ) {
2399
			if ( Jetpack::is_module_active( $module ) ) {
2400
				self::deactivate_module( $module );
2401
				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...
2402
					$modules[] = $replacement;
2403
				}
2404
			}
2405
		}
2406
2407
		return array_unique( $modules );
2408
	}
2409
2410
	/**
2411
	 * Checks activated plugins during auto-activation to determine
2412
	 * if any of those plugins are in the list with a corresponding module
2413
	 * that is not compatible with the plugin. The module will not be allowed
2414
	 * to auto-activate.
2415
	 *
2416
	 * @since 2.6
2417
	 * @uses jetpack_get_default_modules filter
2418
	 * @param array $modules
2419
	 * @return array
2420
	 */
2421
	function filter_default_modules( $modules ) {
2422
2423
		$active_plugins = self::get_active_plugins();
2424
2425
		if ( ! empty( $active_plugins ) ) {
2426
2427
			// For each module we'd like to auto-activate...
2428
			foreach ( $modules as $key => $module ) {
2429
				// If there are potential conflicts for it...
2430
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2431
					// For each potential conflict...
2432
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2433
						// If that conflicting plugin is active...
2434
						if ( in_array( $plugin, $active_plugins ) ) {
2435
							// Remove that item from being auto-activated.
2436
							unset( $modules[ $key ] );
2437
						}
2438
					}
2439
				}
2440
			}
2441
		}
2442
2443
		return $modules;
2444
	}
2445
2446
	/**
2447
	 * Extract a module's slug from its full path.
2448
	 */
2449
	public static function get_module_slug( $file ) {
2450
		return str_replace( '.php', '', basename( $file ) );
2451
	}
2452
2453
	/**
2454
	 * Generate a module's path from its slug.
2455
	 */
2456
	public static function get_module_path( $slug ) {
2457
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2458
	}
2459
2460
	/**
2461
	 * Load module data from module file. Headers differ from WordPress
2462
	 * plugin headers to avoid them being identified as standalone
2463
	 * plugins on the WordPress plugins page.
2464
	 */
2465
	public static function get_module( $module ) {
2466
		$headers = array(
2467
			'name'                      => 'Module Name',
2468
			'description'               => 'Module Description',
2469
			'jumpstart_desc'            => 'Jumpstart Description',
2470
			'sort'                      => 'Sort Order',
2471
			'recommendation_order'      => 'Recommendation Order',
2472
			'introduced'                => 'First Introduced',
2473
			'changed'                   => 'Major Changes In',
2474
			'deactivate'                => 'Deactivate',
2475
			'free'                      => 'Free',
2476
			'requires_connection'       => 'Requires Connection',
2477
			'auto_activate'             => 'Auto Activate',
2478
			'module_tags'               => 'Module Tags',
2479
			'feature'                   => 'Feature',
2480
			'additional_search_queries' => 'Additional Search Queries',
2481
			'plan_classes'              => 'Plans',
2482
		);
2483
2484
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2485
2486
		$mod = Jetpack::get_file_data( $file, $headers );
2487
		if ( empty( $mod['name'] ) ) {
2488
			return false;
2489
		}
2490
2491
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2492
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2493
		$mod['deactivate']              = empty( $mod['deactivate'] );
2494
		$mod['free']                    = empty( $mod['free'] );
2495
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2496
2497
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2498
			$mod['auto_activate'] = 'No';
2499
		} else {
2500
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2501
		}
2502
2503
		if ( $mod['module_tags'] ) {
2504
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2505
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2506
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2507
		} else {
2508
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2509
		}
2510
2511 View Code Duplication
		if ( $mod['plan_classes'] ) {
2512
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2513
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2514
		} else {
2515
			$mod['plan_classes'] = array( 'free' );
2516
		}
2517
2518 View Code Duplication
		if ( $mod['feature'] ) {
2519
			$mod['feature'] = explode( ',', $mod['feature'] );
2520
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2521
		} else {
2522
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2523
		}
2524
2525
		/**
2526
		 * Filters the feature array on a module.
2527
		 *
2528
		 * This filter allows you to control where each module is filtered: Recommended,
2529
		 * Jumpstart, and the default "Other" listing.
2530
		 *
2531
		 * @since 3.5.0
2532
		 *
2533
		 * @param array   $mod['feature'] The areas to feature this module:
2534
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2535
		 *     'Recommended' shows on the main Jetpack admin screen.
2536
		 *     'Other' should be the default if no other value is in the array.
2537
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2538
		 * @param array   $mod All the currently assembled module data.
2539
		 */
2540
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2541
2542
		/**
2543
		 * Filter the returned data about a module.
2544
		 *
2545
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2546
		 * so please be careful.
2547
		 *
2548
		 * @since 3.6.0
2549
		 *
2550
		 * @param array   $mod    The details of the requested module.
2551
		 * @param string  $module The slug of the module, e.g. sharedaddy
2552
		 * @param string  $file   The path to the module source file.
2553
		 */
2554
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2555
	}
2556
2557
	/**
2558
	 * Like core's get_file_data implementation, but caches the result.
2559
	 */
2560
	public static function get_file_data( $file, $headers ) {
2561
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2562
		$file_name = basename( $file );
2563
2564
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2565
2566
		$file_data_option = get_transient( $cache_key );
2567
2568
		if ( false === $file_data_option ) {
2569
			$file_data_option = array();
2570
		}
2571
2572
		$key           = md5( $file_name . serialize( $headers ) );
2573
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2574
2575
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2576
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2577
			return $file_data_option[ $key ];
2578
		}
2579
2580
		$data = get_file_data( $file, $headers );
2581
2582
		$file_data_option[ $key ] = $data;
2583
2584
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2585
2586
		return $data;
2587
	}
2588
2589
2590
	/**
2591
	 * Return translated module tag.
2592
	 *
2593
	 * @param string $tag Tag as it appears in each module heading.
2594
	 *
2595
	 * @return mixed
2596
	 */
2597
	public static function translate_module_tag( $tag ) {
2598
		return jetpack_get_module_i18n_tag( $tag );
2599
	}
2600
2601
	/**
2602
	 * Get i18n strings as a JSON-encoded string
2603
	 *
2604
	 * @return string The locale as JSON
2605
	 */
2606
	public static function get_i18n_data_json() {
2607
		$i18n_json = JETPACK__PLUGIN_DIR . 'languages/json/jetpack-' . jetpack_get_user_locale() . '.json';
2608
2609
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2610
			$locale_data = @file_get_contents( $i18n_json );
2611
			if ( $locale_data ) {
2612
				return $locale_data;
2613
			}
2614
		}
2615
2616
		// Return valid empty Jed locale
2617
		return json_encode( array(
2618
			'' => array(
2619
				'domain' => 'jetpack',
2620
				'lang'   => is_admin() ? get_user_locale() : get_locale(),
2621
			),
2622
		) );
2623
	}
2624
2625
	/**
2626
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2627
	 *
2628
	 * @since 3.9.2
2629
	 *
2630
	 * @param array $modules
2631
	 *
2632
	 * @return string|void
2633
	 */
2634
	public static function get_translated_modules( $modules ) {
2635
		foreach ( $modules as $index => $module ) {
2636
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2637
			if ( isset( $module['name'] ) ) {
2638
				$modules[ $index ]['name'] = $i18n_module['name'];
2639
			}
2640
			if ( isset( $module['description'] ) ) {
2641
				$modules[ $index ]['description'] = $i18n_module['description'];
2642
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2643
			}
2644
		}
2645
		return $modules;
2646
	}
2647
2648
	/**
2649
	 * Get a list of activated modules as an array of module slugs.
2650
	 */
2651
	public static function get_active_modules() {
2652
		$active = Jetpack_Options::get_option( 'active_modules' );
2653
2654
		if ( ! is_array( $active ) ) {
2655
			$active = array();
2656
		}
2657
2658
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2659
			$active[] = 'vaultpress';
2660
		} else {
2661
			$active = array_diff( $active, array( 'vaultpress' ) );
2662
		}
2663
2664
		//If protect is active on the main site of a multisite, it should be active on all sites.
2665
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2666
			$active[] = 'protect';
2667
		}
2668
2669
		/**
2670
		 * Allow filtering of the active modules.
2671
		 *
2672
		 * Gives theme and plugin developers the power to alter the modules that
2673
		 * are activated on the fly.
2674
		 *
2675
		 * @since 5.8.0
2676
		 *
2677
		 * @param array $active Array of active module slugs.
2678
		 */
2679
		$active = apply_filters( 'jetpack_active_modules', $active );
2680
2681
		return array_unique( $active );
2682
	}
2683
2684
	/**
2685
	 * Check whether or not a Jetpack module is active.
2686
	 *
2687
	 * @param string $module The slug of a Jetpack module.
2688
	 * @return bool
2689
	 *
2690
	 * @static
2691
	 */
2692
	public static function is_module_active( $module ) {
2693
		return in_array( $module, self::get_active_modules() );
2694
	}
2695
2696
	public static function is_module( $module ) {
2697
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2698
	}
2699
2700
	/**
2701
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2702
	 *
2703
	 * @param bool $catch True to start catching, False to stop.
2704
	 *
2705
	 * @static
2706
	 */
2707
	public static function catch_errors( $catch ) {
2708
		static $display_errors, $error_reporting;
2709
2710
		if ( $catch ) {
2711
			$display_errors  = @ini_set( 'display_errors', 1 );
2712
			$error_reporting = @error_reporting( E_ALL );
2713
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2714
		} else {
2715
			@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...
2716
			@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...
2717
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2718
		}
2719
	}
2720
2721
	/**
2722
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2723
	 */
2724
	public static function catch_errors_on_shutdown() {
2725
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2726
	}
2727
2728
	/**
2729
	 * Rewrite any string to make paths easier to read.
2730
	 *
2731
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2732
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2733
	 *
2734
	 * @param $string
2735
	 * @return mixed
2736
	 */
2737
	public static function alias_directories( $string ) {
2738
		// ABSPATH has a trailing slash.
2739
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2740
		// WP_CONTENT_DIR does not have a trailing slash.
2741
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2742
2743
		return $string;
2744
	}
2745
2746
	public static function activate_default_modules(
2747
		$min_version = false,
2748
		$max_version = false,
2749
		$other_modules = array(),
2750
		$redirect = true,
2751
		$send_state_messages = true
2752
	) {
2753
		$jetpack = Jetpack::init();
2754
2755
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2756
		$modules = array_merge( $other_modules, $modules );
2757
2758
		// Look for standalone plugins and disable if active.
2759
2760
		$to_deactivate = array();
2761
		foreach ( $modules as $module ) {
2762
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2763
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2764
			}
2765
		}
2766
2767
		$deactivated = array();
2768
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2769
			list( $probable_file, $probable_title ) = $deactivate_me;
2770
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2771
				$deactivated[] = $module;
2772
			}
2773
		}
2774
2775
		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...
2776
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2777
2778
			$url = add_query_arg(
2779
				array(
2780
					'action'   => 'activate_default_modules',
2781
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2782
				),
2783
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2784
			);
2785
			wp_safe_redirect( $url );
2786
			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...
2787
		}
2788
2789
		/**
2790
		 * Fires before default modules are activated.
2791
		 *
2792
		 * @since 1.9.0
2793
		 *
2794
		 * @param string $min_version Minimum version number required to use modules.
2795
		 * @param string $max_version Maximum version number required to use modules.
2796
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2797
		 */
2798
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2799
2800
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2801
		Jetpack::restate();
2802
		Jetpack::catch_errors( true );
2803
2804
		$active = Jetpack::get_active_modules();
2805
2806
		foreach ( $modules as $module ) {
2807
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2808
				$active[] = $module;
2809
				self::update_active_modules( $active );
2810
				continue;
2811
			}
2812
2813
			if ( $send_state_messages && in_array( $module, $active ) ) {
2814
				$module_info = Jetpack::get_module( $module );
2815 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2816
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2817
					if ( $active_state = Jetpack::state( $state ) ) {
2818
						$active_state = explode( ',', $active_state );
2819
					} else {
2820
						$active_state = array();
2821
					}
2822
					$active_state[] = $module;
2823
					Jetpack::state( $state, implode( ',', $active_state ) );
2824
				}
2825
				continue;
2826
			}
2827
2828
			$file = Jetpack::get_module_path( $module );
2829
			if ( ! file_exists( $file ) ) {
2830
				continue;
2831
			}
2832
2833
			// we'll override this later if the plugin can be included without fatal error
2834
			if ( $redirect ) {
2835
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2836
			}
2837
2838
			if ( $send_state_messages ) {
2839
				Jetpack::state( 'error', 'module_activation_failed' );
2840
				Jetpack::state( 'module', $module );
2841
			}
2842
2843
			ob_start();
2844
			require_once $file;
2845
2846
			$active[] = $module;
2847
2848 View Code Duplication
			if ( $send_state_messages ) {
2849
2850
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
0 ignored issues
show
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...
2851
				if ( $active_state = Jetpack::state( $state ) ) {
2852
					$active_state = explode( ',', $active_state );
2853
				} else {
2854
					$active_state = array();
2855
				}
2856
				$active_state[] = $module;
2857
				Jetpack::state( $state, implode( ',', $active_state ) );
2858
			}
2859
2860
			Jetpack::update_active_modules( $active );
2861
2862
			ob_end_clean();
2863
		}
2864
2865
		if ( $send_state_messages ) {
2866
			Jetpack::state( 'error', false );
0 ignored issues
show
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...
2867
			Jetpack::state( 'module', false );
0 ignored issues
show
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...
2868
		}
2869
2870
		Jetpack::catch_errors( false );
2871
		/**
2872
		 * Fires when default modules are activated.
2873
		 *
2874
		 * @since 1.9.0
2875
		 *
2876
		 * @param string $min_version Minimum version number required to use modules.
2877
		 * @param string $max_version Maximum version number required to use modules.
2878
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2879
		 */
2880
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2881
	}
2882
2883
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2884
		/**
2885
		 * Fires before a module is activated.
2886
		 *
2887
		 * @since 2.6.0
2888
		 *
2889
		 * @param string $module Module slug.
2890
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2891
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2892
		 */
2893
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2894
2895
		$jetpack = Jetpack::init();
2896
2897
		if ( ! strlen( $module ) )
2898
			return false;
2899
2900
		if ( ! Jetpack::is_module( $module ) )
2901
			return false;
2902
2903
		// If it's already active, then don't do it again
2904
		$active = Jetpack::get_active_modules();
2905
		foreach ( $active as $act ) {
2906
			if ( $act == $module )
2907
				return true;
2908
		}
2909
2910
		$module_data = Jetpack::get_module( $module );
2911
2912
		if ( ! Jetpack::is_active() ) {
2913
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2914
				return false;
2915
2916
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2917
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2918
				return false;
2919
		}
2920
2921
		// Check and see if the old plugin is active
2922
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2923
			// Deactivate the old plugin
2924
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2925
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2926
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2927
				Jetpack::state( 'deactivated_plugins', $module );
2928
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2929
				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...
2930
			}
2931
		}
2932
2933
		// Protect won't work with mis-configured IPs
2934
		if ( 'protect' === $module ) {
2935
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2936
			if ( ! jetpack_protect_get_ip() ) {
2937
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2938
				return false;
2939
			}
2940
		}
2941
2942
		if ( ! Jetpack::active_plan_supports( $module ) ) {
2943
			return false;
2944
		}
2945
2946
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2947
		Jetpack::state( 'module', $module );
2948
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2949
2950
		Jetpack::catch_errors( true );
2951
		ob_start();
2952
		require Jetpack::get_module_path( $module );
2953
		/** This action is documented in class.jetpack.php */
2954
		do_action( 'jetpack_activate_module', $module );
2955
		$active[] = $module;
2956
		Jetpack::update_active_modules( $active );
2957
2958
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
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...
2959
		ob_end_clean();
2960
		Jetpack::catch_errors( false );
2961
2962
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2963 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2964
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2965
2966
			//Jump start is being dismissed send data to MC Stats
2967
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2968
2969
			$jetpack->do_stats( 'server_side' );
2970
		}
2971
2972
		if ( $redirect ) {
2973
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2974
		}
2975
		if ( $exit ) {
2976
			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...
2977
		}
2978
		return true;
2979
	}
2980
2981
	function activate_module_actions( $module ) {
2982
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2983
	}
2984
2985
	public static function deactivate_module( $module ) {
2986
		/**
2987
		 * Fires when a module is deactivated.
2988
		 *
2989
		 * @since 1.9.0
2990
		 *
2991
		 * @param string $module Module slug.
2992
		 */
2993
		do_action( 'jetpack_pre_deactivate_module', $module );
2994
2995
		$jetpack = Jetpack::init();
2996
2997
		$active = Jetpack::get_active_modules();
2998
		$new    = array_filter( array_diff( $active, (array) $module ) );
2999
3000
		// A flag for Jump Start so it's not shown again.
3001 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3002
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3003
3004
			//Jump start is being dismissed send data to MC Stats
3005
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
3006
3007
			$jetpack->do_stats( 'server_side' );
3008
		}
3009
3010
		return self::update_active_modules( $new );
3011
	}
3012
3013
	public static function enable_module_configurable( $module ) {
3014
		$module = Jetpack::get_module_slug( $module );
3015
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3016
	}
3017
3018
	public static function module_configuration_url( $module ) {
3019
		$module = Jetpack::get_module_slug( $module );
3020
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
3021
	}
3022
3023
	public static function module_configuration_load( $module, $method ) {
3024
		$module = Jetpack::get_module_slug( $module );
3025
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
3026
	}
3027
3028
	public static function module_configuration_head( $module, $method ) {
3029
		$module = Jetpack::get_module_slug( $module );
3030
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
3031
	}
3032
3033
	public static function module_configuration_screen( $module, $method ) {
3034
		$module = Jetpack::get_module_slug( $module );
3035
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
3036
	}
3037
3038
	public static function module_configuration_activation_screen( $module, $method ) {
3039
		$module = Jetpack::get_module_slug( $module );
3040
		add_action( 'display_activate_module_setting_' . $module, $method );
3041
	}
3042
3043
/* Installation */
3044
3045
	public static function bail_on_activation( $message, $deactivate = true ) {
3046
?>
3047
<!doctype html>
3048
<html>
3049
<head>
3050
<meta charset="<?php bloginfo( 'charset' ); ?>">
3051
<style>
3052
* {
3053
	text-align: center;
3054
	margin: 0;
3055
	padding: 0;
3056
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3057
}
3058
p {
3059
	margin-top: 1em;
3060
	font-size: 18px;
3061
}
3062
</style>
3063
<body>
3064
<p><?php echo esc_html( $message ); ?></p>
3065
</body>
3066
</html>
3067
<?php
3068
		if ( $deactivate ) {
3069
			$plugins = get_option( 'active_plugins' );
3070
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3071
			$update  = false;
3072
			foreach ( $plugins as $i => $plugin ) {
3073
				if ( $plugin === $jetpack ) {
3074
					$plugins[$i] = false;
3075
					$update = true;
3076
				}
3077
			}
3078
3079
			if ( $update ) {
3080
				update_option( 'active_plugins', array_filter( $plugins ) );
3081
			}
3082
		}
3083
		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...
3084
	}
3085
3086
	/**
3087
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3088
	 * @static
3089
	 */
3090
	public static function plugin_activation( $network_wide ) {
3091
		Jetpack_Options::update_option( 'activated', 1 );
3092
3093
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3094
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3095
		}
3096
3097
		if ( $network_wide )
3098
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
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...
3099
3100
		// For firing one-off events (notices) immediately after activation
3101
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3102
3103
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3104
3105
		Jetpack::plugin_initialize();
3106
	}
3107
3108
	public static function get_activation_source( $referer_url ) {
3109
3110
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3111
			return array( 'wp-cli', null );
3112
		}
3113
3114
		$referer = parse_url( $referer_url );
3115
3116
		$source_type = 'unknown';
3117
		$source_query = null;
3118
3119
		if ( ! is_array( $referer ) ) {
3120
			return array( $source_type, $source_query );
3121
		}
3122
3123
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3124
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3125
3126
		if ( isset( $referer['query'] ) ) {
3127
			parse_str( $referer['query'], $query_parts );
3128
		} else {
3129
			$query_parts = array();
3130
		}
3131
3132
		if ( $plugins_path === $referer['path'] ) {
3133
			$source_type = 'list';
3134
		} elseif ( $plugins_install_path === $referer['path'] ) {
3135
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3136
			switch( $tab ) {
3137
				case 'popular':
3138
					$source_type = 'popular';
3139
					break;
3140
				case 'recommended':
3141
					$source_type = 'recommended';
3142
					break;
3143
				case 'favorites':
3144
					$source_type = 'favorites';
3145
					break;
3146
				case 'search':
3147
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3148
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3149
					break;
3150
				default:
3151
					$source_type = 'featured';
3152
			}
3153
		}
3154
3155
		return array( $source_type, $source_query );
3156
	}
3157
3158
	/**
3159
	 * Runs before bumping version numbers up to a new version
3160
	 * @param  string $version    Version:timestamp
3161
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3162
	 * @return null              [description]
3163
	 */
3164
	public static function do_version_bump( $version, $old_version ) {
3165
3166
		if ( ! $old_version ) { // For new sites
3167
			// Setting up jetpack manage
3168
			Jetpack::activate_manage();
3169
		}
3170
	}
3171
3172
	/**
3173
	 * Sets the internal version number and activation state.
3174
	 * @static
3175
	 */
3176
	public static function plugin_initialize() {
3177
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3178
			Jetpack_Options::update_option( 'activated', 2 );
3179
		}
3180
3181 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3182
			$version = $old_version = JETPACK__VERSION . ':' . time();
3183
			/** This action is documented in class.jetpack.php */
3184
			do_action( 'updating_jetpack_version', $version, false );
3185
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3186
		}
3187
3188
		Jetpack::load_modules();
3189
3190
		Jetpack_Options::delete_option( 'do_activate' );
3191
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3192
	}
3193
3194
	/**
3195
	 * Removes all connection options
3196
	 * @static
3197
	 */
3198
	public static function plugin_deactivation( ) {
3199
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3200
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3201
			Jetpack_Network::init()->deactivate();
3202
		} else {
3203
			Jetpack::disconnect( false );
3204
			//Jetpack_Heartbeat::init()->deactivate();
3205
		}
3206
	}
3207
3208
	/**
3209
	 * Disconnects from the Jetpack servers.
3210
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3211
	 * @static
3212
	 */
3213
	public static function disconnect( $update_activated_state = true ) {
3214
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3215
		Jetpack::clean_nonces( true );
3216
3217
		// If the site is in an IDC because sync is not allowed,
3218
		// let's make sure to not disconnect the production site.
3219
		if ( ! self::validate_sync_error_idc_option() ) {
3220
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3221
			Jetpack::load_xml_rpc_client();
3222
			$xml = new Jetpack_IXR_Client();
3223
			$xml->query( 'jetpack.deregister' );
3224
		}
3225
3226
		Jetpack_Options::delete_option(
3227
			array(
3228
				'blog_token',
3229
				'user_token',
3230
				'user_tokens',
3231
				'master_user',
3232
				'time_diff',
3233
				'fallback_no_verify_ssl_certs',
3234
			)
3235
		);
3236
3237
		Jetpack_IDC::clear_all_idc_options();
3238
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3239
3240
		if ( $update_activated_state ) {
3241
			Jetpack_Options::update_option( 'activated', 4 );
3242
		}
3243
3244
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3245
			// Check then record unique disconnection if site has never been disconnected previously
3246
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3247
				$jetpack_unique_connection['disconnected'] = 1;
3248
			} else {
3249
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3250
					//track unique disconnect
3251
					$jetpack = Jetpack::init();
3252
3253
					$jetpack->stat( 'connections', 'unique-disconnect' );
3254
					$jetpack->do_stats( 'server_side' );
3255
				}
3256
				// increment number of times disconnected
3257
				$jetpack_unique_connection['disconnected'] += 1;
3258
			}
3259
3260
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3261
		}
3262
3263
		// Delete cached connected user data
3264
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3265
		delete_transient( $transient_key );
3266
3267
		// Delete all the sync related data. Since it could be taking up space.
3268
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3269
		Jetpack_Sync_Sender::get_instance()->uninstall();
3270
3271
		// Disable the Heartbeat cron
3272
		Jetpack_Heartbeat::init()->deactivate();
3273
	}
3274
3275
	/**
3276
	 * Unlinks the current user from the linked WordPress.com user
3277
	 */
3278
	public static function unlink_user( $user_id = null ) {
3279
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3280
			return false;
3281
3282
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3283
3284
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3285
			return false;
3286
3287
		if ( ! isset( $tokens[ $user_id ] ) )
3288
			return false;
3289
3290
		Jetpack::load_xml_rpc_client();
3291
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3292
		$xml->query( 'jetpack.unlink_user', $user_id );
3293
3294
		unset( $tokens[ $user_id ] );
3295
3296
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3297
3298
		/**
3299
		 * Fires after the current user has been unlinked from WordPress.com.
3300
		 *
3301
		 * @since 4.1.0
3302
		 *
3303
		 * @param int $user_id The current user's ID.
3304
		 */
3305
		do_action( 'jetpack_unlinked_user', $user_id );
3306
3307
		return true;
3308
	}
3309
3310
	/**
3311
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3312
	 */
3313
	public static function try_registration() {
3314
		// The user has agreed to the TOS at some point by now.
3315
		Jetpack_Options::update_option( 'tos_agreed', true );
3316
3317
		// Let's get some testing in beta versions and such.
3318
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3319
			// Before attempting to connect, let's make sure that the domains are viable.
3320
			$domains_to_check = array_unique( array(
3321
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3322
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3323
			) );
3324
			foreach ( $domains_to_check as $domain ) {
3325
				$result = Jetpack_Data::is_usable_domain( $domain );
3326
				if ( is_wp_error( $result ) ) {
3327
					return $result;
3328
				}
3329
			}
3330
		}
3331
3332
		$result = Jetpack::register();
3333
3334
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3335
		if ( ! $result || is_wp_error( $result ) ) {
3336
			return $result;
3337
		} else {
3338
			return true;
3339
		}
3340
	}
3341
3342
	/**
3343
	 * Tracking an internal event log. Try not to put too much chaff in here.
3344
	 *
3345
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3346
	 */
3347
	public static function log( $code, $data = null ) {
3348
		// only grab the latest 200 entries
3349
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3350
3351
		// Append our event to the log
3352
		$log_entry = array(
3353
			'time'    => time(),
3354
			'user_id' => get_current_user_id(),
3355
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3356
			'code'    => $code,
3357
		);
3358
		// Don't bother storing it unless we've got some.
3359
		if ( ! is_null( $data ) ) {
3360
			$log_entry['data'] = $data;
3361
		}
3362
		$log[] = $log_entry;
3363
3364
		// Try add_option first, to make sure it's not autoloaded.
3365
		// @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...
3366
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3367
			Jetpack_Options::update_option( 'log', $log );
3368
		}
3369
3370
		/**
3371
		 * Fires when Jetpack logs an internal event.
3372
		 *
3373
		 * @since 3.0.0
3374
		 *
3375
		 * @param array $log_entry {
3376
		 *	Array of details about the log entry.
3377
		 *
3378
		 *	@param string time Time of the event.
3379
		 *	@param int user_id ID of the user who trigerred the event.
3380
		 *	@param int blog_id Jetpack Blog ID.
3381
		 *	@param string code Unique name for the event.
3382
		 *	@param string data Data about the event.
3383
		 * }
3384
		 */
3385
		do_action( 'jetpack_log_entry', $log_entry );
3386
	}
3387
3388
	/**
3389
	 * Get the internal event log.
3390
	 *
3391
	 * @param $event (string) - only return the specific log events
3392
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3393
	 *
3394
	 * @return array of log events || WP_Error for invalid params
3395
	 */
3396
	public static function get_log( $event = false, $num = false ) {
3397
		if ( $event && ! is_string( $event ) ) {
3398
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3399
		}
3400
3401
		if ( $num && ! is_numeric( $num ) ) {
3402
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3403
		}
3404
3405
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3406
3407
		// If nothing set - act as it did before, otherwise let's start customizing the output
3408
		if ( ! $num && ! $event ) {
3409
			return $entire_log;
3410
		} else {
3411
			$entire_log = array_reverse( $entire_log );
3412
		}
3413
3414
		$custom_log_output = array();
3415
3416
		if ( $event ) {
3417
			foreach ( $entire_log as $log_event ) {
3418
				if ( $event == $log_event[ 'code' ] ) {
3419
					$custom_log_output[] = $log_event;
3420
				}
3421
			}
3422
		} else {
3423
			$custom_log_output = $entire_log;
3424
		}
3425
3426
		if ( $num ) {
3427
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3428
		}
3429
3430
		return $custom_log_output;
3431
	}
3432
3433
	/**
3434
	 * Log modification of important settings.
3435
	 */
3436
	public static function log_settings_change( $option, $old_value, $value ) {
3437
		switch( $option ) {
3438
			case 'jetpack_sync_non_public_post_stati':
3439
				self::log( $option, $value );
3440
				break;
3441
		}
3442
	}
3443
3444
	/**
3445
	 * Return stat data for WPCOM sync
3446
	 */
3447
	public static function get_stat_data( $encode = true, $extended = true ) {
3448
		$data = Jetpack_Heartbeat::generate_stats_array();
3449
3450
		if ( $extended ) {
3451
			$additional_data = self::get_additional_stat_data();
3452
			$data = array_merge( $data, $additional_data );
3453
		}
3454
3455
		if ( $encode ) {
3456
			return json_encode( $data );
3457
		}
3458
3459
		return $data;
3460
	}
3461
3462
	/**
3463
	 * Get additional stat data to sync to WPCOM
3464
	 */
3465
	public static function get_additional_stat_data( $prefix = '' ) {
3466
		$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...
3467
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3468
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3469
		$return["{$prefix}site-count"]     = 0;
3470
3471
		if ( function_exists( 'get_blog_count' ) ) {
3472
			$return["{$prefix}site-count"] = get_blog_count();
3473
		}
3474
		return $return;
3475
	}
3476
3477
	private static function get_site_user_count() {
3478
		global $wpdb;
3479
3480
		if ( function_exists( 'wp_is_large_network' ) ) {
3481
			if ( wp_is_large_network( 'users' ) ) {
3482
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3483
			}
3484
		}
3485 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3486
			// It wasn't there, so regenerate the data and save the transient
3487
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3488
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3489
		}
3490
		return $user_count;
3491
	}
3492
3493
	/* Admin Pages */
3494
3495
	function admin_init() {
3496
		// If the plugin is not connected, display a connect message.
3497
		if (
3498
			// the plugin was auto-activated and needs its candy
3499
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3500
		||
3501
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3502
			! Jetpack_Options::get_option( 'activated' )
3503
		) {
3504
			Jetpack::plugin_initialize();
3505
		}
3506
3507
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3508
			Jetpack_Connection_Banner::init();
3509
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3510
			// Upgrade: 1.1 -> 1.1.1
3511
			// Check and see if host can verify the Jetpack servers' SSL certificate
3512
			$args = array();
3513
			Jetpack_Client::_wp_remote_request(
3514
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3515
				$args,
3516
				true
3517
			);
3518
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3519
			// Show the notice on the Dashboard only for now
3520
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3521
		}
3522
3523
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3524
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3525
		}
3526
3527
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3528
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3529
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3530
3531
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3532
			// Artificially throw errors in certain whitelisted cases during plugin activation
3533
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3534
		}
3535
3536
		// Jetpack Manage Activation Screen from .com
3537
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3538
3539
		// Add custom column in wp-admin/users.php to show whether user is linked.
3540
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3541
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3542
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3543
	}
3544
3545
	function admin_body_class( $admin_body_class = '' ) {
3546
		$classes = explode( ' ', trim( $admin_body_class ) );
3547
3548
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3549
3550
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3551
		return " $admin_body_class ";
3552
	}
3553
3554
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3555
		return $admin_body_class . ' jetpack-pagestyles ';
3556
	}
3557
3558
	/**
3559
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3560
	 *
3561
	 * @return null
3562
	 */
3563
	function prepare_manage_jetpack_notice() {
3564
3565
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3566
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3567
	}
3568
3569
	function manage_activate_screen() {
3570
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3571
	}
3572
	/**
3573
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3574
	 * This function artificially throws errors for such cases (whitelisted).
3575
	 *
3576
	 * @param string $plugin The activated plugin.
3577
	 */
3578
	function throw_error_on_activate_plugin( $plugin ) {
3579
		$active_modules = Jetpack::get_active_modules();
3580
3581
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3582
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3583
			$throw = false;
3584
3585
			// Try and make sure it really was the stats plugin
3586
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3587
				if ( 'stats.php' == basename( $plugin ) ) {
3588
					$throw = true;
3589
				}
3590
			} else {
3591
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3592
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3593
					$throw = true;
3594
				}
3595
			}
3596
3597
			if ( $throw ) {
3598
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3599
			}
3600
		}
3601
	}
3602
3603
	function intercept_plugin_error_scrape_init() {
3604
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3605
	}
3606
3607
	function intercept_plugin_error_scrape( $action, $result ) {
3608
		if ( ! $result ) {
3609
			return;
3610
		}
3611
3612
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3613
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3614
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3615
			}
3616
		}
3617
	}
3618
3619
	function add_remote_request_handlers() {
3620
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3621
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3622
	}
3623
3624
	function remote_request_handlers() {
3625
		$action = current_filter();
0 ignored issues
show
$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...
3626
3627
		switch ( current_filter() ) {
3628
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3629
			$response = $this->upload_handler();
3630
			break;
3631
3632
		case 'wp_ajax_nopriv_jetpack_update_file' :
3633
			$response = $this->upload_handler( true );
3634
			break;
3635
		default :
0 ignored issues
show
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...
3636
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3637
			break;
3638
		}
3639
3640
		if ( ! $response ) {
3641
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3642
		}
3643
3644
		if ( is_wp_error( $response ) ) {
3645
			$status_code       = $response->get_error_data();
3646
			$error             = $response->get_error_code();
3647
			$error_description = $response->get_error_message();
3648
3649
			if ( ! is_int( $status_code ) ) {
3650
				$status_code = 400;
3651
			}
3652
3653
			status_header( $status_code );
3654
			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...
3655
		}
3656
3657
		status_header( 200 );
3658
		if ( true === $response ) {
3659
			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...
3660
		}
3661
3662
		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...
3663
	}
3664
3665
	/**
3666
	 * Uploads a file gotten from the global $_FILES.
3667
	 * If `$update_media_item` is true and `post_id` is defined
3668
	 * the attachment file of the media item (gotten through of the post_id)
3669
	 * will be updated instead of add a new one.
3670
	 *
3671
	 * @param  boolean $update_media_item - update media attachment
3672
	 * @return array - An array describing the uploadind files process
3673
	 */
3674
	function upload_handler( $update_media_item = false ) {
3675
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3676
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3677
		}
3678
3679
		$user = wp_authenticate( '', '' );
3680
		if ( ! $user || is_wp_error( $user ) ) {
3681
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3682
		}
3683
3684
		wp_set_current_user( $user->ID );
3685
3686
		if ( ! current_user_can( 'upload_files' ) ) {
3687
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3688
		}
3689
3690
		if ( empty( $_FILES ) ) {
3691
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3692
		}
3693
3694
		foreach ( array_keys( $_FILES ) as $files_key ) {
3695
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3696
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3697
			}
3698
		}
3699
3700
		$media_keys = array_keys( $_FILES['media'] );
3701
3702
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3703
		if ( ! $token || is_wp_error( $token ) ) {
3704
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3705
		}
3706
3707
		$uploaded_files = array();
3708
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3709
		unset( $GLOBALS['post'] );
3710
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3711
			$file = array();
3712
			foreach ( $media_keys as $media_key ) {
3713
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3714
			}
3715
3716
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3717
3718
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3719
			if ( $hmac_provided !== $hmac_file ) {
3720
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3721
				continue;
3722
			}
3723
3724
			$_FILES['.jetpack.upload.'] = $file;
3725
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3726
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3727
				$post_id = 0;
3728
			}
3729
3730
			if ( $update_media_item ) {
3731
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3732
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3733
				}
3734
3735
				$media_array = $_FILES['media'];
3736
3737
				$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...
3738
				$file_array['type'] = $media_array['type'][0];
3739
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3740
				$file_array['error'] = $media_array['error'][0];
3741
				$file_array['size'] = $media_array['size'][0];
3742
3743
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3744
3745
				if ( is_wp_error( $edited_media_item ) ) {
3746
					return $edited_media_item;
3747
				}
3748
3749
				$response = (object) array(
3750
					'id'   => (string) $post_id,
3751
					'file' => (string) $edited_media_item->post_title,
3752
					'url'  => (string) wp_get_attachment_url( $post_id ),
3753
					'type' => (string) $edited_media_item->post_mime_type,
3754
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3755
				);
3756
3757
				return (array) array( $response );
3758
			}
3759
3760
			$attachment_id = media_handle_upload(
3761
				'.jetpack.upload.',
3762
				$post_id,
3763
				array(),
3764
				array(
3765
					'action' => 'jetpack_upload_file',
3766
				)
3767
			);
3768
3769
			if ( ! $attachment_id ) {
3770
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3771
			} elseif ( is_wp_error( $attachment_id ) ) {
3772
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3773
			} else {
3774
				$attachment = get_post( $attachment_id );
3775
				$uploaded_files[$index] = (object) array(
3776
					'id'   => (string) $attachment_id,
3777
					'file' => $attachment->post_title,
3778
					'url'  => wp_get_attachment_url( $attachment_id ),
3779
					'type' => $attachment->post_mime_type,
3780
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3781
				);
3782
				// Zip files uploads are not supported unless they are done for installation purposed
3783
				// lets delete them in case something goes wrong in this whole process
3784
				if ( 'application/zip' === $attachment->post_mime_type ) {
3785
					// Schedule a cleanup for 2 hours from now in case of failed install.
3786
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3787
				}
3788
			}
3789
		}
3790
		if ( ! is_null( $global_post ) ) {
3791
			$GLOBALS['post'] = $global_post;
3792
		}
3793
3794
		return $uploaded_files;
3795
	}
3796
3797
	/**
3798
	 * Add help to the Jetpack page
3799
	 *
3800
	 * @since Jetpack (1.2.3)
3801
	 * @return false if not the Jetpack page
3802
	 */
3803
	function admin_help() {
3804
		$current_screen = get_current_screen();
3805
3806
		// Overview
3807
		$current_screen->add_help_tab(
3808
			array(
3809
				'id'		=> 'home',
3810
				'title'		=> __( 'Home', 'jetpack' ),
3811
				'content'	=>
3812
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3813
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3814
					'<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>',
3815
			)
3816
		);
3817
3818
		// Screen Content
3819
		if ( current_user_can( 'manage_options' ) ) {
3820
			$current_screen->add_help_tab(
3821
				array(
3822
					'id'		=> 'settings',
3823
					'title'		=> __( 'Settings', 'jetpack' ),
3824
					'content'	=>
3825
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3826
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3827
						'<ol>' .
3828
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3829
							'<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>' .
3830
						'</ol>' .
3831
						'<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>'
3832
				)
3833
			);
3834
		}
3835
3836
		// Help Sidebar
3837
		$current_screen->set_help_sidebar(
3838
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3839
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3840
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3841
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3842
		);
3843
	}
3844
3845
	function admin_menu_css() {
3846
		wp_enqueue_style( 'jetpack-icons' );
3847
	}
3848
3849
	function admin_menu_order() {
3850
		return true;
3851
	}
3852
3853
	function enqueue_gutenberg_locale() {
3854
		wp_add_inline_script(
3855
			'wp-i18n',
3856
			'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
3857
		);
3858
	}
3859
3860 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3861
		$jp_menu_order = array();
3862
3863
		foreach ( $menu_order as $index => $item ) {
3864
			if ( $item != 'jetpack' ) {
3865
				$jp_menu_order[] = $item;
3866
			}
3867
3868
			if ( $index == 0 ) {
3869
				$jp_menu_order[] = 'jetpack';
3870
			}
3871
		}
3872
3873
		return $jp_menu_order;
3874
	}
3875
3876
	function admin_head() {
3877 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3878
			/** This action is documented in class.jetpack-admin-page.php */
3879
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3880
	}
3881
3882
	function admin_banner_styles() {
3883
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3884
3885
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3886
			wp_register_style(
3887
				'jetpack-dops-style',
3888
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3889
				array(),
3890
				JETPACK__VERSION
3891
			);
3892
		}
3893
3894
		wp_enqueue_style(
3895
			'jetpack',
3896
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3897
			array( 'jetpack-dops-style' ),
3898
			 JETPACK__VERSION . '-20121016'
3899
		);
3900
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3901
		wp_style_add_data( 'jetpack', 'suffix', $min );
3902
	}
3903
3904
	function plugin_action_links( $actions ) {
3905
3906
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3907
3908
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3909
			return array_merge(
3910
				$jetpack_home,
3911
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3912
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3913
				$actions
3914
				);
3915
			}
3916
3917
		return array_merge( $jetpack_home, $actions );
3918
	}
3919
3920
	/**
3921
	 * This is the first banner
3922
	 * It should be visible only to user that can update the option
3923
	 * Are not connected
3924
	 *
3925
	 * @return null
3926
	 */
3927
	function admin_jetpack_manage_notice() {
3928
		$screen = get_current_screen();
3929
3930
		// Don't show the connect notice on the jetpack settings page.
3931
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3932
			return;
3933
		}
3934
3935
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3936
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3937
		/**
3938
		 * I think it would be great to have different wordsing depending on where you are
3939
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3940
		 * etc..
3941
		 */
3942
3943
		?>
3944
		<div id="message" class="updated jp-banner">
3945
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3946
				<div class="jp-banner__description-container">
3947
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3948
					<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>
3949
					<p class="jp-banner__button-container">
3950
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3951
						<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>
3952
					</p>
3953
				</div>
3954
		</div>
3955
		<?php
3956
	}
3957
3958
	/**
3959
	 * Returns the url that the user clicks to remove the notice for the big banner
3960
	 * @return string
3961
	 */
3962
	function opt_out_jetpack_manage_url() {
3963
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3964
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3965
	}
3966
	/**
3967
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3968
	 * @return string
3969
	 */
3970
	function opt_in_jetpack_manage_url() {
3971
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3972
	}
3973
3974
	function opt_in_jetpack_manage_notice() {
3975
		?>
3976
		<div class="wrap">
3977
			<div id="message" class="jetpack-message is-opt-in">
3978
				<?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' ); ?>
3979
			</div>
3980
		</div>
3981
		<?php
3982
3983
	}
3984
	/**
3985
	 * Determines whether to show the notice of not true = display notice
3986
	 * @return bool
3987
	 */
3988
	function can_display_jetpack_manage_notice() {
3989
		// never display the notice to users that can't do anything about it anyways
3990
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3991
			return false;
3992
3993
		// don't display if we are in development more
3994
		if( Jetpack::is_development_mode() ) {
3995
			return false;
3996
		}
3997
		// don't display if the site is private
3998
		if(  ! Jetpack_Options::get_option( 'public' ) )
3999
			return false;
4000
4001
		/**
4002
		 * Should the Jetpack Remote Site Management notice be displayed.
4003
		 *
4004
		 * @since 3.3.0
4005
		 *
4006
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
4007
		 */
4008
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
4009
	}
4010
4011
	/*
4012
	 * Registration flow:
4013
	 * 1 - ::admin_page_load() action=register
4014
	 * 2 - ::try_registration()
4015
	 * 3 - ::register()
4016
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4017
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4018
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4019
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4020
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4021
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4022
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4023
	 *       jetpack_id, jetpack_secret, jetpack_public
4024
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4025
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4026
	 * 5 - user logs in with WP.com account
4027
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4028
	 *		- Jetpack_Client_Server::authorize()
4029
	 *		- Jetpack_Client_Server::get_token()
4030
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4031
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4032
	 *			- which responds with access_token, token_type, scope
4033
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
4034
	 *		- Jetpack::activate_default_modules()
4035
	 *     		- Deactivates deprecated plugins
4036
	 *     		- Activates all default modules
4037
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4038
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4039
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4040
	 *     Done!
4041
	 */
4042
4043
	/**
4044
	 * Handles the page load events for the Jetpack admin page
4045
	 */
4046
	function admin_page_load() {
4047
		$error = false;
4048
4049
		// Make sure we have the right body class to hook stylings for subpages off of.
4050
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4051
4052
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4053
			// Should only be used in intermediate redirects to preserve state across redirects
4054
			Jetpack::restate();
4055
		}
4056
4057
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4058
			// User clicked in the iframe to link their accounts
4059
			if ( ! Jetpack::is_user_connected() ) {
4060
				$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4061
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4062
4063
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4064
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4065
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4066
4067
				if ( isset( $_GET['notes_iframe'] ) )
4068
					$connect_url .= '&notes_iframe';
4069
				wp_redirect( $connect_url );
4070
				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...
4071
			} else {
4072
				if ( ! isset( $_GET['calypso_env'] ) ) {
4073
					Jetpack::state( 'message', 'already_authorized' );
4074
					wp_safe_redirect( Jetpack::admin_url() );
4075
					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...
4076
				} else {
4077
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
4078
					$connect_url .= '&already_authorized=true';
4079
					wp_redirect( $connect_url );
4080
					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...
4081
				}
4082
			}
4083
		}
4084
4085
4086
		if ( isset( $_GET['action'] ) ) {
4087
			switch ( $_GET['action'] ) {
4088
			case 'authorize':
4089
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4090
					Jetpack::state( 'message', 'already_authorized' );
4091
					wp_safe_redirect( Jetpack::admin_url() );
4092
					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...
4093
				}
4094
				Jetpack::log( 'authorize' );
4095
				$client_server = new Jetpack_Client_Server;
4096
				$client_server->client_authorize();
4097
				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...
4098
			case 'register' :
4099
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4100
					$error = 'cheatin';
4101
					break;
4102
				}
4103
				check_admin_referer( 'jetpack-register' );
4104
				Jetpack::log( 'register' );
4105
				Jetpack::maybe_set_version_option();
4106
				$registered = Jetpack::try_registration();
4107
				if ( is_wp_error( $registered ) ) {
4108
					$error = $registered->get_error_code();
4109
					Jetpack::state( 'error', $error );
4110
					Jetpack::state( 'error', $registered->get_error_message() );
4111
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4112
						'error_code' => $error,
4113
						'error_message' => $registered->get_error_message()
4114
					) );
4115
					break;
4116
				}
4117
4118
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4119
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4120
4121
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4122
					'from' => $from
4123
				) );
4124
4125
				$url = $this->build_connect_url( true, $redirect, $from );
4126
4127
				if ( ! empty( $_GET['onboarding'] ) ) {
4128
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4129
				}
4130
4131
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4132
					$url = add_query_arg( 'auth_approved', 'true', $url );
4133
				}
4134
4135
				wp_redirect( $url );
4136
				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...
4137
			case 'activate' :
4138
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4139
					$error = 'cheatin';
4140
					break;
4141
				}
4142
4143
				$module = stripslashes( $_GET['module'] );
4144
				check_admin_referer( "jetpack_activate-$module" );
4145
				Jetpack::log( 'activate', $module );
4146
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4147
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4148
				}
4149
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4150
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4151
				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...
4152
			case 'activate_default_modules' :
4153
				check_admin_referer( 'activate_default_modules' );
4154
				Jetpack::log( 'activate_default_modules' );
4155
				Jetpack::restate();
4156
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4157
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4158
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4159
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4160
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4161
				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...
4162
			case 'disconnect' :
4163
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4164
					$error = 'cheatin';
4165
					break;
4166
				}
4167
4168
				check_admin_referer( 'jetpack-disconnect' );
4169
				Jetpack::log( 'disconnect' );
4170
				Jetpack::disconnect();
4171
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4172
				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...
4173
			case 'reconnect' :
4174
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4175
					$error = 'cheatin';
4176
					break;
4177
				}
4178
4179
				check_admin_referer( 'jetpack-reconnect' );
4180
				Jetpack::log( 'reconnect' );
4181
				$this->disconnect();
4182
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4183
				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...
4184 View Code Duplication
			case 'deactivate' :
4185
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4186
					$error = 'cheatin';
4187
					break;
4188
				}
4189
4190
				$modules = stripslashes( $_GET['module'] );
4191
				check_admin_referer( "jetpack_deactivate-$modules" );
4192
				foreach ( explode( ',', $modules ) as $module ) {
4193
					Jetpack::log( 'deactivate', $module );
4194
					Jetpack::deactivate_module( $module );
4195
					Jetpack::state( 'message', 'module_deactivated' );
4196
				}
4197
				Jetpack::state( 'module', $modules );
4198
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4199
				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...
4200
			case 'unlink' :
4201
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4202
				check_admin_referer( 'jetpack-unlink' );
4203
				Jetpack::log( 'unlink' );
4204
				$this->unlink_user();
4205
				Jetpack::state( 'message', 'unlinked' );
4206
				if ( 'sub-unlink' == $redirect ) {
4207
					wp_safe_redirect( admin_url() );
4208
				} else {
4209
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4210
				}
4211
				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...
4212
			case 'onboard' :
4213
				if ( ! current_user_can( 'manage_options' ) ) {
4214
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4215
				} else {
4216
					Jetpack::create_onboarding_token();
4217
					$url = $this->build_connect_url( true );
4218
4219
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4220
						$url = add_query_arg( 'onboarding', $token, $url );
4221
					}
4222
4223
					$calypso_env = ! empty( $_GET[ 'calypso_env' ] ) ? $_GET[ 'calypso_env' ] : false;
4224
					if ( $calypso_env ) {
4225
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4226
					}
4227
4228
					wp_redirect( $url );
4229
					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...
4230
				}
4231
				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...
4232
			default:
4233
				/**
4234
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4235
				 *
4236
				 * @since 2.6.0
4237
				 *
4238
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4239
				 */
4240
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4241
			}
4242
		}
4243
4244
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4245
			self::activate_new_modules( true );
4246
		}
4247
4248
		$message_code = Jetpack::state( 'message' );
4249
		if ( Jetpack::state( 'optin-manage' ) ) {
4250
			$activated_manage = $message_code;
4251
			$message_code = 'jetpack-manage';
4252
		}
4253
4254
		switch ( $message_code ) {
4255
		case 'jetpack-manage':
4256
			$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>';
4257
			if ( $activated_manage ) {
0 ignored issues
show
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...
4258
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4259
			}
4260
			break;
4261
4262
		}
4263
4264
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4265
4266
		if ( ! empty( $deactivated_plugins ) ) {
4267
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4268
			$deactivated_titles  = array();
4269
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4270
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4271
					continue;
4272
				}
4273
4274
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4275
			}
4276
4277
			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...
4278
				if ( $this->message ) {
4279
					$this->message .= "<br /><br />\n";
4280
				}
4281
4282
				$this->message .= wp_sprintf(
4283
					_n(
4284
						'Jetpack contains the most recent version of the old %l plugin.',
4285
						'Jetpack contains the most recent versions of the old %l plugins.',
4286
						count( $deactivated_titles ),
4287
						'jetpack'
4288
					),
4289
					$deactivated_titles
4290
				);
4291
4292
				$this->message .= "<br />\n";
4293
4294
				$this->message .= _n(
4295
					'The old version has been deactivated and can be removed from your site.',
4296
					'The old versions have been deactivated and can be removed from your site.',
4297
					count( $deactivated_titles ),
4298
					'jetpack'
4299
				);
4300
			}
4301
		}
4302
4303
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4304
4305
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4306
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4307
		}
4308
4309 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4310
			/**
4311
			 * Fires when a module configuration page is loaded.
4312
			 * The dynamic part of the hook is the configure parameter from the URL.
4313
			 *
4314
			 * @since 1.1.0
4315
			 */
4316
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4317
		}
4318
4319
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4320
	}
4321
4322
	function admin_notices() {
4323
4324
		if ( $this->error ) {
4325
?>
4326
<div id="message" class="jetpack-message jetpack-err">
4327
	<div class="squeezer">
4328
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4329
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4330
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4331
<?php	endif; ?>
4332
	</div>
4333
</div>
4334
<?php
4335
		}
4336
4337
		if ( $this->message ) {
4338
?>
4339
<div id="message" class="jetpack-message">
4340
	<div class="squeezer">
4341
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4342
	</div>
4343
</div>
4344
<?php
4345
		}
4346
4347
		if ( $this->privacy_checks ) :
4348
			$module_names = $module_slugs = array();
4349
4350
			$privacy_checks = explode( ',', $this->privacy_checks );
4351
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4352
			foreach ( $privacy_checks as $module_slug ) {
4353
				$module = Jetpack::get_module( $module_slug );
4354
				if ( ! $module ) {
4355
					continue;
4356
				}
4357
4358
				$module_slugs[] = $module_slug;
4359
				$module_names[] = "<strong>{$module['name']}</strong>";
4360
			}
4361
4362
			$module_slugs = join( ',', $module_slugs );
4363
?>
4364
<div id="message" class="jetpack-message jetpack-err">
4365
	<div class="squeezer">
4366
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4367
		<p><?php
4368
			echo wp_kses(
4369
				wptexturize(
4370
					wp_sprintf(
4371
						_nx(
4372
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4373
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4374
							count( $privacy_checks ),
4375
							'%l = list of Jetpack module/feature names',
4376
							'jetpack'
4377
						),
4378
						$module_names
4379
					)
4380
				),
4381
				array( 'strong' => true )
4382
			);
4383
4384
			echo "\n<br />\n";
4385
4386
			echo wp_kses(
4387
				sprintf(
4388
					_nx(
4389
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4390
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4391
						count( $privacy_checks ),
4392
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4393
						'jetpack'
4394
					),
4395
					wp_nonce_url(
4396
						Jetpack::admin_url(
4397
							array(
4398
								'page'   => 'jetpack',
4399
								'action' => 'deactivate',
4400
								'module' => urlencode( $module_slugs ),
4401
							)
4402
						),
4403
						"jetpack_deactivate-$module_slugs"
4404
					),
4405
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4406
				),
4407
				array( 'a' => array( 'href' => true, 'title' => true ) )
4408
			);
4409
		?></p>
4410
	</div>
4411
</div>
4412
<?php endif;
4413
	// only display the notice if the other stuff is not there
4414
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4415
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4416
			$this->opt_in_jetpack_manage_notice();
4417
		}
4418
	}
4419
4420
	/**
4421
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4422
	 */
4423
	function stat( $group, $detail ) {
4424
		if ( ! isset( $this->stats[ $group ] ) )
4425
			$this->stats[ $group ] = array();
4426
		$this->stats[ $group ][] = $detail;
4427
	}
4428
4429
	/**
4430
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4431
	 */
4432
	function do_stats( $method = '' ) {
4433
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4434
			foreach ( $this->stats as $group => $stats ) {
4435
				if ( is_array( $stats ) && count( $stats ) ) {
4436
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4437
					if ( 'server_side' === $method ) {
4438
						self::do_server_side_stat( $args );
4439
					} else {
4440
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4441
					}
4442
				}
4443
				unset( $this->stats[ $group ] );
4444
			}
4445
		}
4446
	}
4447
4448
	/**
4449
	 * Runs stats code for a one-off, server-side.
4450
	 *
4451
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4452
	 *
4453
	 * @return bool If it worked.
4454
	 */
4455
	static function do_server_side_stat( $args ) {
4456
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4457
		if ( is_wp_error( $response ) )
4458
			return false;
4459
4460
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4461
			return false;
4462
4463
		return true;
4464
	}
4465
4466
	/**
4467
	 * Builds the stats url.
4468
	 *
4469
	 * @param $args array|string The arguments to append to the URL.
4470
	 *
4471
	 * @return string The URL to be pinged.
4472
	 */
4473
	static function build_stats_url( $args ) {
4474
		$defaults = array(
4475
			'v'    => 'wpcom2',
4476
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4477
		);
4478
		$args     = wp_parse_args( $args, $defaults );
4479
		/**
4480
		 * Filter the URL used as the Stats tracking pixel.
4481
		 *
4482
		 * @since 2.3.2
4483
		 *
4484
		 * @param string $url Base URL used as the Stats tracking pixel.
4485
		 */
4486
		$base_url = apply_filters(
4487
			'jetpack_stats_base_url',
4488
			'https://pixel.wp.com/g.gif'
4489
		);
4490
		$url      = add_query_arg( $args, $base_url );
4491
		return $url;
4492
	}
4493
4494
	static function translate_current_user_to_role() {
4495
		foreach ( self::$capability_translations as $role => $cap ) {
4496
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4497
				return $role;
4498
			}
4499
		}
4500
4501
		return false;
4502
	}
4503
4504
	static function translate_user_to_role( $user ) {
4505
		foreach ( self::$capability_translations as $role => $cap ) {
4506
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4507
				return $role;
4508
			}
4509
		}
4510
4511
		return false;
4512
    }
4513
4514
	static function translate_role_to_cap( $role ) {
4515
		if ( ! isset( self::$capability_translations[$role] ) ) {
4516
			return false;
4517
		}
4518
4519
		return self::$capability_translations[$role];
4520
	}
4521
4522
	static function sign_role( $role, $user_id = null ) {
4523
		if ( empty( $user_id ) ) {
4524
			$user_id = (int) get_current_user_id();
4525
		}
4526
4527
		if ( ! $user_id  ) {
4528
			return false;
4529
		}
4530
4531
		$token = Jetpack_Data::get_access_token();
4532
		if ( ! $token || is_wp_error( $token ) ) {
4533
			return false;
4534
		}
4535
4536
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4537
	}
4538
4539
4540
	/**
4541
	 * Builds a URL to the Jetpack connection auth page
4542
	 *
4543
	 * @since 3.9.5
4544
	 *
4545
	 * @param bool $raw If true, URL will not be escaped.
4546
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4547
	 *                              If string, will be a custom redirect.
4548
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4549
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4550
	 *
4551
	 * @return string Connect URL
4552
	 */
4553
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4554
		$site_id = Jetpack_Options::get_option( 'id' );
4555
		$token = Jetpack_Options::get_option( 'blog_token' );
4556
4557
		if ( $register || ! $token || ! $site_id ) {
4558
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4559
4560
			if ( ! empty( $redirect ) ) {
4561
				$url = add_query_arg(
4562
					'redirect',
4563
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4564
					$url
4565
				);
4566
			}
4567
4568
			if( is_network_admin() ) {
4569
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4570
			}
4571
		} else {
4572
4573
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4574
			// because otherwise this logic can get us in to a loop.
4575
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4576
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4577
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4578
4579
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4580
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4581
					'1.1'
4582
				);
4583
4584
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4585
					// Generating a register URL instead to refresh the existing token
4586
					return $this->build_connect_url( $raw, $redirect, $from, true );
4587
				}
4588
			}
4589
4590
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4591
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4592
			}
4593
4594
			$role = self::translate_current_user_to_role();
4595
			$signed_role = self::sign_role( $role );
4596
4597
			$user = wp_get_current_user();
4598
4599
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4600
			$redirect = $redirect
4601
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4602
				: $jetpack_admin_page;
4603
4604
			if( isset( $_REQUEST['is_multisite'] ) ) {
4605
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4606
			}
4607
4608
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4609
4610
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4611
				? get_site_icon_url()
4612
				: false;
4613
4614
			/**
4615
			 * Filter the type of authorization.
4616
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4617
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4618
			 *
4619
			 * @since 4.3.3
4620
			 *
4621
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4622
			 */
4623
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4624
4625
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4626
4627
			$args = urlencode_deep(
4628
				array(
4629
					'response_type' => 'code',
4630
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4631
					'redirect_uri'  => add_query_arg(
4632
						array(
4633
							'action'   => 'authorize',
4634
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4635
							'redirect' => urlencode( $redirect ),
4636
						),
4637
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4638
					),
4639
					'state'         => $user->ID,
4640
					'scope'         => $signed_role,
4641
					'user_email'    => $user->user_email,
4642
					'user_login'    => $user->user_login,
4643
					'is_active'     => Jetpack::is_active(),
4644
					'jp_version'    => JETPACK__VERSION,
4645
					'auth_type'     => $auth_type,
4646
					'secret'        => $secrets['secret_1'],
4647
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4648
					'blogname'      => get_option( 'blogname' ),
4649
					'site_url'      => site_url(),
4650
					'home_url'      => home_url(),
4651
					'site_icon'     => $site_icon,
4652
					'site_lang'     => get_locale(),
4653
					'_ui'           => $tracks_identity['_ui'],
4654
					'_ut'           => $tracks_identity['_ut']
4655
				)
4656
			);
4657
4658
			self::apply_activation_source_to_args( $args );
4659
4660
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4661
		}
4662
4663
		if ( $from ) {
4664
			$url = add_query_arg( 'from', $from, $url );
4665
		}
4666
4667
4668
		if ( isset( $_GET['calypso_env'] ) ) {
4669
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4670
		}
4671
4672
		return $raw ? $url : esc_url( $url );
4673
	}
4674
4675
	public static function apply_activation_source_to_args( &$args ) {
4676
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4677
4678
		if ( $activation_source_name ) {
4679
			$args['_as'] = urlencode( $activation_source_name );
4680
		}
4681
4682
		if ( $activation_source_keyword ) {
4683
			$args['_ak'] = urlencode( $activation_source_keyword );
4684
		}
4685
	}
4686
4687
	function build_reconnect_url( $raw = false ) {
4688
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4689
		return $raw ? $url : esc_url( $url );
4690
	}
4691
4692
	public static function admin_url( $args = null ) {
4693
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4694
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4695
		return $url;
4696
	}
4697
4698
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4699
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4700
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4701
	}
4702
4703
	function dismiss_jetpack_notice() {
4704
4705
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4706
			return;
4707
		}
4708
4709
		switch( $_GET['jetpack-notice'] ) {
4710
			case 'dismiss':
4711
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4712
4713
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4714
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4715
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4716
				}
4717
				break;
4718 View Code Duplication
			case 'jetpack-manage-opt-out':
0 ignored issues
show
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...
4719
4720
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4721
					// Don't show the banner again
4722
4723
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4724
					// redirect back to the page that had the notice
4725
					if ( wp_get_referer() ) {
4726
						wp_safe_redirect( wp_get_referer() );
4727
					} else {
4728
						// Take me to Jetpack
4729
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4730
					}
4731
				}
4732
				break;
4733 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
0 ignored issues
show
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...
4734
4735
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4736
					// Don't show the banner again
4737
4738
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4739
					// redirect back to the page that had the notice
4740
					if ( wp_get_referer() ) {
4741
						wp_safe_redirect( wp_get_referer() );
4742
					} else {
4743
						// Take me to Jetpack
4744
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4745
					}
4746
				}
4747
				break;
4748
			case 'jetpack-manage-opt-in':
4749
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4750
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4751
4752
					$redirection_url = Jetpack::admin_url();
4753
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4754
4755
					// Don't redirect form the Jetpack Setting Page
4756
					$referer_parsed = parse_url ( wp_get_referer() );
4757
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4758
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4759
						// Take the user to Jetpack home except when on the setting page
4760
						$redirection_url = wp_get_referer();
4761
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4762
					}
4763
					// Also update the JSON API FULL MANAGEMENT Option
4764
					Jetpack::activate_module( 'manage', false, false );
4765
4766
					// Special Message when option in.
4767
					Jetpack::state( 'optin-manage', 'true' );
4768
					// Activate the Module if not activated already
4769
4770
					// Redirect properly
4771
					wp_safe_redirect( $redirection_url );
4772
4773
				}
4774
				break;
4775
		}
4776
	}
4777
4778
	public static function admin_screen_configure_module( $module_id ) {
4779
4780
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4781
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4782
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4783
				/**
4784
				 * Fires to diplay a custom module activation screen.
4785
				 *
4786
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4787
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4788
				 *
4789
				 * @module manage
4790
				 *
4791
				 * @since 3.8.0
4792
				 *
4793
				 * @param int $module_id Module ID.
4794
				 */
4795
				do_action( 'display_activate_module_setting_' . $module_id );
4796
			} else {
4797
				self::display_activate_module_link( $module_id );
4798
			}
4799
4800
			return false;
4801
		} ?>
4802
4803
		<div id="jp-settings-screen" style="position: relative">
4804
			<h3>
4805
			<?php
4806
				$module = Jetpack::get_module( $module_id );
4807
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4808
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4809
			?>
4810
			</h3>
4811
			<?php
4812
				/**
4813
				 * Fires within the displayed message when a feature configuation is updated.
4814
				 *
4815
				 * @since 3.4.0
4816
				 *
4817
				 * @param int $module_id Module ID.
4818
				 */
4819
				do_action( 'jetpack_notices_update_settings', $module_id );
4820
				/**
4821
				 * Fires when a feature configuation screen is loaded.
4822
				 * The dynamic part of the hook, $module_id, is the module ID.
4823
				 *
4824
				 * @since 1.1.0
4825
				 */
4826
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4827
			?>
4828
		</div><?php
4829
	}
4830
4831
	/**
4832
	 * Display link to activate the module to see the settings screen.
4833
	 * @param  string $module_id
4834
	 * @return null
4835
	 */
4836
	public static function display_activate_module_link( $module_id ) {
4837
4838
		$info =  Jetpack::get_module( $module_id );
4839
		$extra = '';
4840
		$activate_url = wp_nonce_url(
4841
				Jetpack::admin_url(
4842
					array(
4843
						'page'   => 'jetpack',
4844
						'action' => 'activate',
4845
						'module' => $module_id,
4846
					)
4847
				),
4848
				"jetpack_activate-$module_id"
4849
			);
4850
4851
		?>
4852
4853
		<div class="wrap configure-module">
4854
			<div id="jp-settings-screen">
4855
				<?php
4856
				if ( $module_id == 'json-api' ) {
4857
4858
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4859
4860
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4861
4862
					$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' );
4863
4864
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4865
				} ?>
4866
4867
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4868
				<div class="narrow">
4869
					<p><?php echo  $info['description']; ?></p>
4870
					<?php if( $extra ) { ?>
4871
					<p><?php echo esc_html( $extra ); ?></p>
4872
					<?php } ?>
4873
					<p>
4874
						<?php
4875
						if( wp_get_referer() ) {
4876
							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() );
4877
						} else {
4878
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4879
						} ?>
4880
					</p>
4881
				</div>
4882
4883
			</div>
4884
		</div>
4885
4886
		<?php
4887
	}
4888
4889
	public static function sort_modules( $a, $b ) {
4890
		if ( $a['sort'] == $b['sort'] )
4891
			return 0;
4892
4893
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4894
	}
4895
4896
	function ajax_recheck_ssl() {
4897
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4898
		$result = Jetpack::permit_ssl( true );
4899
		wp_send_json( array(
4900
			'enabled' => $result,
4901
			'message' => get_transient( 'jetpack_https_test_message' )
4902
		) );
4903
	}
4904
4905
/* Client API */
4906
4907
	/**
4908
	 * Returns the requested Jetpack API URL
4909
	 *
4910
	 * @return string
4911
	 */
4912
	public static function api_url( $relative_url ) {
4913
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4914
	}
4915
4916
	/**
4917
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4918
	 */
4919
	public static function fix_url_for_bad_hosts( $url ) {
4920
		if ( 0 !== strpos( $url, 'https://' ) ) {
4921
			return $url;
4922
		}
4923
4924
		switch ( JETPACK_CLIENT__HTTPS ) {
4925
			case 'ALWAYS' :
4926
				return $url;
4927
			case 'NEVER' :
4928
				return set_url_scheme( $url, 'http' );
4929
			// default : case 'AUTO' :
4930
		}
4931
4932
		// we now return the unmodified SSL URL by default, as a security precaution
4933
		return $url;
4934
	}
4935
4936
	/**
4937
	 * Create a random secret for validating onboarding payload
4938
	 *
4939
	 * @return string Secret token
4940
	 */
4941
	public static function create_onboarding_token() {
4942
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4943
			$token = wp_generate_password( 32, false );
4944
			Jetpack_Options::update_option( 'onboarding', $token );
4945
		}
4946
4947
		return $token;
4948
	}
4949
4950
	/**
4951
	 * Remove the onboarding token
4952
	 *
4953
	 * @return bool True on success, false on failure
4954
	 */
4955
	public static function invalidate_onboarding_token() {
4956
		return Jetpack_Options::delete_option( 'onboarding' );
4957
	}
4958
4959
	/**
4960
	 * Validate an onboarding token for a specific action
4961
	 *
4962
	 * @return boolean True if token/action pair is accepted, false if not
4963
	 */
4964
	public static function validate_onboarding_token_action( $token, $action ) {
4965
		// Compare tokens, bail if tokens do not match
4966
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
4967
			return false;
4968
		}
4969
4970
		// List of valid actions we can take
4971
		$valid_actions = array(
4972
			'/jetpack/v4/settings',
4973
		);
4974
4975
		// Whitelist the action
4976
		if ( ! in_array( $action, $valid_actions ) ) {
4977
			return false;
4978
		}
4979
4980
		return true;
4981
	}
4982
4983
	/**
4984
	 * Checks to see if the URL is using SSL to connect with Jetpack
4985
	 *
4986
	 * @since 2.3.3
4987
	 * @return boolean
4988
	 */
4989
	public static function permit_ssl( $force_recheck = false ) {
4990
		// Do some fancy tests to see if ssl is being supported
4991
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4992
			$message = '';
4993
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4994
				$ssl = 0;
4995
			} else {
4996
				switch ( JETPACK_CLIENT__HTTPS ) {
4997
					case 'NEVER':
4998
						$ssl = 0;
4999
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5000
						break;
5001
					case 'ALWAYS':
5002
					case 'AUTO':
5003
					default:
5004
						$ssl = 1;
5005
						break;
5006
				}
5007
5008
				// If it's not 'NEVER', test to see
5009
				if ( $ssl ) {
5010
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5011
						$ssl = 0;
5012
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5013
					} else {
5014
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5015
						if ( is_wp_error( $response ) ) {
5016
							$ssl = 0;
5017
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5018
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5019
							$ssl = 0;
5020
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5021
						}
5022
					}
5023
				}
5024
			}
5025
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5026
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5027
		}
5028
5029
		return (bool) $ssl;
5030
	}
5031
5032
	/*
5033
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5034
	 */
5035
	public function alert_auto_ssl_fail() {
5036
		if ( ! current_user_can( 'manage_options' ) )
5037
			return;
5038
5039
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5040
		?>
5041
5042
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5043
			<div class="jp-banner__content">
5044
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5045
				<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>
5046
				<p>
5047
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5048
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5049
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5050
				</p>
5051
				<p>
5052
					<?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' ),
5053
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
5054
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
5055
				</p>
5056
			</div>
5057
		</div>
5058
		<style>
5059
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5060
		</style>
5061
		<script type="text/javascript">
5062
			jQuery( document ).ready( function( $ ) {
5063
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5064
					var $this = $( this );
5065
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5066
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5067
					e.preventDefault();
5068
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5069
					$.post( ajaxurl, data )
5070
					  .done( function( response ) {
5071
					  	if ( response.enabled ) {
5072
					  		$( '#jetpack-ssl-warning' ).hide();
5073
					  	} else {
5074
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5075
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5076
					  	}
5077
					  }.bind( $this ) );
5078
				} );
5079
			} );
5080
		</script>
5081
5082
		<?php
5083
	}
5084
5085
	/**
5086
	 * Returns the Jetpack XML-RPC API
5087
	 *
5088
	 * @return string
5089
	 */
5090
	public static function xmlrpc_api_url() {
5091
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
5092
		return untrailingslashit( $base ) . '/xmlrpc.php';
5093
	}
5094
5095
	/**
5096
	 * Creates two secret tokens and the end of life timestamp for them.
5097
	 *
5098
	 * Note these tokens are unique per call, NOT static per site for connecting.
5099
	 *
5100
	 * @since 2.6
5101
	 * @return array
5102
	 */
5103
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5104
		if ( ! $user_id ) {
5105
			$user_id = get_current_user_id();
5106
		}
5107
5108
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
5109
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5110
5111
		if (
5112
			isset( $secrets[ $secret_name ] ) &&
5113
			$secrets[ $secret_name ]['exp'] > time()
5114
		) {
5115
			return $secrets[ $secret_name ];
5116
		}
5117
5118
		$secret_value = array(
5119
			'secret_1'  => wp_generate_password( 32, false ),
5120
			'secret_2'  => wp_generate_password( 32, false ),
5121
			'exp'       => time() + $exp,
5122
		);
5123
5124
		$secrets[ $secret_name ] = $secret_value;
5125
5126
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5127
		return $secrets[ $secret_name ];
5128
	}
5129
5130
	public static function get_secrets( $action, $user_id ) {
5131
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5132
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5133
5134
		if ( ! isset( $secrets[ $secret_name ] ) ) {
5135
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5136
		}
5137
5138
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
5139
			self::delete_secrets( $action, $user_id );
5140
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5141
		}
5142
5143
		return $secrets[ $secret_name ];
5144
	}
5145
5146
	public static function delete_secrets( $action, $user_id ) {
5147
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5148
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5149
		if ( isset( $secrets[ $secret_name ] ) ) {
5150
			unset( $secrets[ $secret_name ] );
5151
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5152
		}
5153
	}
5154
5155
	/**
5156
	 * Builds the timeout limit for queries talking with the wpcom servers.
5157
	 *
5158
	 * Based on local php max_execution_time in php.ini
5159
	 *
5160
	 * @since 2.6
5161
	 * @return int
5162
	 * @deprecated
5163
	 **/
5164
	public function get_remote_query_timeout_limit() {
5165
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5166
		return Jetpack::get_max_execution_time();
5167
	}
5168
5169
	/**
5170
	 * Builds the timeout limit for queries talking with the wpcom servers.
5171
	 *
5172
	 * Based on local php max_execution_time in php.ini
5173
	 *
5174
	 * @since 5.4
5175
	 * @return int
5176
	 **/
5177
	public static function get_max_execution_time() {
5178
		$timeout = (int) ini_get( 'max_execution_time' );
5179
5180
		// Ensure exec time set in php.ini
5181
		if ( ! $timeout ) {
5182
			$timeout = 30;
5183
		}
5184
		return $timeout;
5185
	}
5186
5187
	/**
5188
	 * Sets a minimum request timeout, and returns the current timeout
5189
	 *
5190
	 * @since 5.4
5191
	 **/
5192
	public static function set_min_time_limit( $min_timeout ) {
5193
		$timeout = self::get_max_execution_time();
5194
		if ( $timeout < $min_timeout ) {
5195
			$timeout = $min_timeout;
5196
			set_time_limit( $timeout );
5197
		}
5198
		return $timeout;
5199
	}
5200
5201
5202
	/**
5203
	 * Takes the response from the Jetpack register new site endpoint and
5204
	 * verifies it worked properly.
5205
	 *
5206
	 * @since 2.6
5207
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5208
	 **/
5209
	public function validate_remote_register_response( $response ) {
5210
	  if ( is_wp_error( $response ) ) {
5211
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5212
		}
5213
5214
		$code   = wp_remote_retrieve_response_code( $response );
5215
		$entity = wp_remote_retrieve_body( $response );
5216
		if ( $entity )
5217
			$registration_response = json_decode( $entity );
5218
		else
5219
			$registration_response = false;
5220
5221
		$code_type = intval( $code / 100 );
5222
		if ( 5 == $code_type ) {
5223
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5224
		} elseif ( 408 == $code ) {
5225
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5226
		} elseif ( ! empty( $registration_response->error ) ) {
5227
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5228
				$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' );
5229
			} else {
5230
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5231
			}
5232
5233
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5234
		} elseif ( 200 != $code ) {
5235
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5236
		}
5237
5238
		// Jetpack ID error block
5239
		if ( empty( $registration_response->jetpack_id ) ) {
5240
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5241
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5242
			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 );
5243
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5244
			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 );
5245
		}
5246
5247
	    return $registration_response;
5248
	}
5249
	/**
5250
	 * @return bool|WP_Error
5251
	 */
5252
	public static function register() {
5253
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5254
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5255
		$secrets = Jetpack::generate_secrets( 'register' );
5256
5257 View Code Duplication
		if (
5258
			empty( $secrets['secret_1'] ) ||
5259
			empty( $secrets['secret_2'] ) ||
5260
			empty( $secrets['exp'] )
5261
		) {
5262
			return new Jetpack_Error( 'missing_secrets' );
5263
		}
5264
5265
		// better to try (and fail) to set a higher timeout than this system
5266
		// supports than to have register fail for more users than it should
5267
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5268
5269
		$gmt_offset = get_option( 'gmt_offset' );
5270
		if ( ! $gmt_offset ) {
5271
			$gmt_offset = 0;
5272
		}
5273
5274
		$stats_options = get_option( 'stats_options' );
5275
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5276
5277
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5278
5279
		$args = array(
5280
			'method'  => 'POST',
5281
			'body'    => array(
5282
				'siteurl'         => site_url(),
5283
				'home'            => home_url(),
5284
				'gmt_offset'      => $gmt_offset,
5285
				'timezone_string' => (string) get_option( 'timezone_string' ),
5286
				'site_name'       => (string) get_option( 'blogname' ),
5287
				'secret_1'        => $secrets['secret_1'],
5288
				'secret_2'        => $secrets['secret_2'],
5289
				'site_lang'       => get_locale(),
5290
				'timeout'         => $timeout,
5291
				'stats_id'        => $stats_id,
5292
				'state'           => get_current_user_id(),
5293
				'_ui'             => $tracks_identity['_ui'],
5294
				'_ut'             => $tracks_identity['_ut'],
5295
				'jetpack_version' => JETPACK__VERSION
5296
			),
5297
			'headers' => array(
5298
				'Accept' => 'application/json',
5299
			),
5300
			'timeout' => $timeout,
5301
		);
5302
5303
		self::apply_activation_source_to_args( $args['body'] );
5304
5305
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5306
5307
		// Make sure the response is valid and does not contain any Jetpack errors
5308
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5309
		if ( is_wp_error( $registration_details ) ) {
5310
			return $registration_details;
5311
		} elseif ( ! $registration_details ) {
5312
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5313
		}
5314
5315 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5316
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5317
		}
5318
5319
		if ( isset( $registration_details->jetpack_public ) ) {
5320
			$jetpack_public = (int) $registration_details->jetpack_public;
5321
		} else {
5322
			$jetpack_public = false;
5323
		}
5324
5325
		Jetpack_Options::update_options(
5326
			array(
5327
				'id'         => (int)    $registration_details->jetpack_id,
5328
				'blog_token' => (string) $registration_details->jetpack_secret,
5329
				'public'     => $jetpack_public,
5330
			)
5331
		);
5332
5333
		/**
5334
		 * Fires when a site is registered on WordPress.com.
5335
		 *
5336
		 * @since 3.7.0
5337
		 *
5338
		 * @param int $json->jetpack_id Jetpack Blog ID.
5339
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5340
		 * @param int|bool $jetpack_public Is the site public.
5341
		 */
5342
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5343
5344
		// Initialize Jump Start for the first and only time.
5345
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5346
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5347
5348
			$jetpack = Jetpack::init();
5349
5350
			$jetpack->stat( 'jumpstart', 'unique-views' );
5351
			$jetpack->do_stats( 'server_side' );
5352
		};
5353
5354
		return true;
5355
	}
5356
5357
	/**
5358
	 * If the db version is showing something other that what we've got now, bump it to current.
5359
	 *
5360
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
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...
5361
	 */
5362
	public static function maybe_set_version_option() {
5363
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5364
		if ( JETPACK__VERSION != $version ) {
5365
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5366
5367
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5368
				/** This action is documented in class.jetpack.php */
5369
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5370
			}
5371
5372
			return true;
5373
		}
5374
		return false;
5375
	}
5376
5377
/* Client Server API */
5378
5379
	/**
5380
	 * Loads the Jetpack XML-RPC client
5381
	 */
5382
	public static function load_xml_rpc_client() {
5383
		require_once ABSPATH . WPINC . '/class-IXR.php';
5384
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5385
	}
5386
5387
	/**
5388
	 * Resets the saved authentication state in between testing requests.
5389
	 */
5390
	public function reset_saved_auth_state() {
5391
		$this->xmlrpc_verification = null;
5392
		$this->rest_authentication_status = null;
5393
	}
5394
5395
	function verify_xml_rpc_signature() {
5396
		if ( $this->xmlrpc_verification ) {
5397
			return $this->xmlrpc_verification;
5398
		}
5399
5400
		// It's not for us
5401
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5402
			return false;
5403
		}
5404
5405
		@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...
5406
		if (
5407
			empty( $token_key )
5408
		||
5409
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5410
		) {
5411
			return false;
5412
		}
5413
5414
		if ( '0' === $user_id ) {
5415
			$token_type = 'blog';
5416
			$user_id = 0;
5417
		} else {
5418
			$token_type = 'user';
5419
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5420
				return false;
5421
			}
5422
			$user_id = (int) $user_id;
5423
5424
			$user = new WP_User( $user_id );
5425
			if ( ! $user || ! $user->exists() ) {
5426
				return false;
5427
			}
5428
		}
5429
5430
		$token = Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
$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...
5431
		if ( ! $token ) {
5432
			return false;
5433
		}
5434
5435
		$token_check = "$token_key.";
5436
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
5437
			return false;
5438
		}
5439
5440
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5441
5442
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5443
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5444
			$post_data   = $_POST;
5445
			$file_hashes = array();
5446
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5447
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5448
					continue;
5449
				}
5450
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5451
				$file_hashes[$post_data_key] = $post_data_value;
5452
			}
5453
5454
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5455
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5456
				$post_data[$post_data_key] = $post_data_value;
5457
			}
5458
5459
			ksort( $post_data );
5460
5461
			$body = http_build_query( stripslashes_deep( $post_data ) );
5462
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5463
			$body = file_get_contents( 'php://input' );
5464
		} else {
5465
			$body = null;
5466
		}
5467
5468
		$signature = $jetpack_signature->sign_current_request(
5469
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5470
		);
5471
5472
		if ( ! $signature ) {
5473
			return false;
5474
		} else if ( is_wp_error( $signature ) ) {
5475
			return $signature;
5476
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
5477
			return false;
5478
		}
5479
5480
		$timestamp = (int) $_GET['timestamp'];
5481
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5482
5483
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5484
			return false;
5485
		}
5486
5487
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5488
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5489
			if ( ! empty( $_GET['onboarding'] ) ) {
5490
				$jpo = $_GET;
5491
			} else {
5492
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5493
			}
5494
5495
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5496
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5497
5498
			if (
5499
				isset( $jpo_user ) && isset( $jpo_token ) &&
5500
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5501
				isset( $_GET['rest_route'] ) &&
5502
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5503
			) {
5504
				$jpUser = get_user_by( 'email', $jpo_user );
5505
				if ( is_a( $jpUser, 'WP_User' ) ) {
5506
					wp_set_current_user( $jpUser->ID );
5507
					$user_can = is_multisite()
5508
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5509
						: current_user_can( 'manage_options' );
5510
					if ( $user_can ) {
5511
						$token_type = 'user';
5512
						$token->external_user_id = $jpUser->ID;
5513
					}
5514
				}
5515
			}
5516
		}
5517
5518
		$this->xmlrpc_verification = array(
5519
			'type'    => $token_type,
5520
			'user_id' => $token->external_user_id,
5521
		);
5522
5523
		return $this->xmlrpc_verification;
5524
	}
5525
5526
	/**
5527
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5528
	 */
5529
	function authenticate_jetpack( $user, $username, $password ) {
5530
		if ( is_a( $user, 'WP_User' ) ) {
5531
			return $user;
5532
		}
5533
5534
		$token_details = $this->verify_xml_rpc_signature();
5535
5536
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5537
			return $user;
5538
		}
5539
5540
		if ( 'user' !== $token_details['type'] ) {
5541
			return $user;
5542
		}
5543
5544
		if ( ! $token_details['user_id'] ) {
5545
			return $user;
5546
		}
5547
5548
		nocache_headers();
5549
5550
		return new WP_User( $token_details['user_id'] );
5551
	}
5552
5553
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5554
	// Uses the existing XMLRPC request signing implementation.
5555
	function wp_rest_authenticate( $user ) {
5556
		if ( ! empty( $user ) ) {
5557
			// Another authentication method is in effect.
5558
			return $user;
5559
		}
5560
5561
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5562
			// Nothing to do for this authentication method.
5563
			return null;
5564
		}
5565
5566
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5567
			// Nothing to do for this authentication method.
5568
			return null;
5569
		}
5570
5571
		// Ensure that we always have the request body available.  At this
5572
		// point, the WP REST API code to determine the request body has not
5573
		// run yet.  That code may try to read from 'php://input' later, but
5574
		// this can only be done once per request in PHP versions prior to 5.6.
5575
		// So we will go ahead and perform this read now if needed, and save
5576
		// the request body where both the Jetpack signature verification code
5577
		// and the WP REST API code can see it.
5578
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5579
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5580
		}
5581
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5582
5583
		// Only support specific request parameters that have been tested and
5584
		// are known to work with signature verification.  A different method
5585
		// can be passed to the WP REST API via the '?_method=' parameter if
5586
		// needed.
5587
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5588
			$this->rest_authentication_status = new WP_Error(
5589
				'rest_invalid_request',
5590
				__( 'This request method is not supported.', 'jetpack' ),
5591
				array( 'status' => 400 )
5592
			);
5593
			return null;
5594
		}
5595
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5596
			$this->rest_authentication_status = new WP_Error(
5597
				'rest_invalid_request',
5598
				__( 'This request method does not support body parameters.', 'jetpack' ),
5599
				array( 'status' => 400 )
5600
			);
5601
			return null;
5602
		}
5603
5604
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
5605
			$content_type = $_SERVER['CONTENT_TYPE'];
5606
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
5607
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
5608
		}
5609
5610
		if (
5611
			isset( $content_type ) &&
5612
			$content_type !== 'application/x-www-form-urlencoded' &&
5613
			$content_type !== 'application/json'
5614
		) {
5615
			$this->rest_authentication_status = new WP_Error(
5616
				'rest_invalid_request',
5617
				__( 'This Content-Type is not supported.', 'jetpack' ),
5618
				array( 'status' => 400 )
5619
			);
5620
			return null;
5621
		}
5622
5623
		$verified = $this->verify_xml_rpc_signature();
5624
5625
		if ( is_wp_error( $verified ) ) {
5626
			$this->rest_authentication_status = $verified;
5627
			return null;
5628
		}
5629
5630
		if (
5631
			$verified &&
5632
			isset( $verified['type'] ) &&
5633
			'user' === $verified['type'] &&
5634
			! empty( $verified['user_id'] )
5635
		) {
5636
			// Authentication successful.
5637
			$this->rest_authentication_status = true;
5638
			return $verified['user_id'];
5639
		}
5640
5641
		// Something else went wrong.  Probably a signature error.
5642
		$this->rest_authentication_status = new WP_Error(
5643
			'rest_invalid_signature',
5644
			__( 'The request is not signed correctly.', 'jetpack' ),
5645
			array( 'status' => 400 )
5646
		);
5647
		return null;
5648
	}
5649
5650
	/**
5651
	 * Report authentication status to the WP REST API.
5652
	 *
5653
	 * @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
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...
5654
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5655
	 */
5656
	public function wp_rest_authentication_errors( $value ) {
5657
		if ( $value !== null ) {
5658
			return $value;
5659
		}
5660
		return $this->rest_authentication_status;
5661
	}
5662
5663
	function add_nonce( $timestamp, $nonce ) {
5664
		global $wpdb;
5665
		static $nonces_used_this_request = array();
5666
5667
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5668
			return $nonces_used_this_request["$timestamp:$nonce"];
5669
		}
5670
5671
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5672
		$timestamp = (int) $timestamp;
5673
		$nonce     = esc_sql( $nonce );
5674
5675
		// Raw query so we can avoid races: add_option will also update
5676
		$show_errors = $wpdb->show_errors( false );
5677
5678
		$old_nonce = $wpdb->get_row(
5679
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5680
		);
5681
5682
		if ( is_null( $old_nonce ) ) {
5683
			$return = $wpdb->query(
5684
				$wpdb->prepare(
5685
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5686
					"jetpack_nonce_{$timestamp}_{$nonce}",
5687
					time(),
5688
					'no'
5689
				)
5690
			);
5691
		} else {
5692
			$return = false;
5693
		}
5694
5695
		$wpdb->show_errors( $show_errors );
5696
5697
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5698
5699
		return $return;
5700
	}
5701
5702
	/**
5703
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5704
	 * Capture it here so we can verify the signature later.
5705
	 */
5706
	function xmlrpc_methods( $methods ) {
5707
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5708
		return $methods;
5709
	}
5710
5711
	function public_xmlrpc_methods( $methods ) {
5712
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5713
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5714
		}
5715
		return $methods;
5716
	}
5717
5718
	function jetpack_getOptions( $args ) {
5719
		global $wp_xmlrpc_server;
5720
5721
		$wp_xmlrpc_server->escape( $args );
5722
5723
		$username	= $args[1];
5724
		$password	= $args[2];
5725
5726
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5727
			return $wp_xmlrpc_server->error;
5728
		}
5729
5730
		$options = array();
5731
		$user_data = $this->get_connected_user_data();
5732
		if ( is_array( $user_data ) ) {
5733
			$options['jetpack_user_id'] = array(
5734
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5735
				'readonly'      => true,
5736
				'value'         => $user_data['ID'],
5737
			);
5738
			$options['jetpack_user_login'] = array(
5739
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5740
				'readonly'      => true,
5741
				'value'         => $user_data['login'],
5742
			);
5743
			$options['jetpack_user_email'] = array(
5744
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5745
				'readonly'      => true,
5746
				'value'         => $user_data['email'],
5747
			);
5748
			$options['jetpack_user_site_count'] = array(
5749
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5750
				'readonly'      => true,
5751
				'value'         => $user_data['site_count'],
5752
			);
5753
		}
5754
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5755
		$args = stripslashes_deep( $args );
5756
		return $wp_xmlrpc_server->wp_getOptions( $args );
5757
	}
5758
5759
	function xmlrpc_options( $options ) {
5760
		$jetpack_client_id = false;
5761
		if ( self::is_active() ) {
5762
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5763
		}
5764
		$options['jetpack_version'] = array(
5765
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5766
				'readonly'      => true,
5767
				'value'         => JETPACK__VERSION,
5768
		);
5769
5770
		$options['jetpack_client_id'] = array(
5771
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5772
				'readonly'      => true,
5773
				'value'         => $jetpack_client_id,
5774
		);
5775
		return $options;
5776
	}
5777
5778
	public static function clean_nonces( $all = false ) {
5779
		global $wpdb;
5780
5781
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5782
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5783
5784
		if ( true !== $all ) {
5785
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5786
			$sql_args[] = time() - 3600;
5787
		}
5788
5789
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5790
5791
		$sql = $wpdb->prepare( $sql, $sql_args );
5792
5793
		for ( $i = 0; $i < 1000; $i++ ) {
5794
			if ( ! $wpdb->query( $sql ) ) {
5795
				break;
5796
			}
5797
		}
5798
	}
5799
5800
	/**
5801
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5802
	 * SET: state( $key, $value );
5803
	 * GET: $value = state( $key );
5804
	 *
5805
	 * @param string $key
0 ignored issues
show
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...
5806
	 * @param string $value
0 ignored issues
show
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...
5807
	 * @param bool $restate private
5808
	 */
5809
	public static function state( $key = null, $value = null, $restate = false ) {
5810
		static $state = array();
5811
		static $path, $domain;
5812
		if ( ! isset( $path ) ) {
5813
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5814
			$admin_url = Jetpack::admin_url();
5815
			$bits      = parse_url( $admin_url );
5816
5817
			if ( is_array( $bits ) ) {
5818
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5819
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5820
			} else {
5821
				$path = $domain = null;
5822
			}
5823
		}
5824
5825
		// Extract state from cookies and delete cookies
5826
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5827
			$yum = $_COOKIE[ 'jetpackState' ];
5828
			unset( $_COOKIE[ 'jetpackState' ] );
5829
			foreach ( $yum as $k => $v ) {
5830
				if ( strlen( $v ) )
5831
					$state[ $k ] = $v;
5832
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5833
			}
5834
		}
5835
5836
		if ( $restate ) {
5837
			foreach ( $state as $k => $v ) {
5838
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5839
			}
5840
			return;
5841
		}
5842
5843
		// Get a state variable
5844
		if ( isset( $key ) && ! isset( $value ) ) {
5845
			if ( array_key_exists( $key, $state ) )
5846
				return $state[ $key ];
5847
			return null;
5848
		}
5849
5850
		// Set a state variable
5851
		if ( isset ( $key ) && isset( $value ) ) {
5852
			if( is_array( $value ) && isset( $value[0] ) ) {
5853
				$value = $value[0];
5854
			}
5855
			$state[ $key ] = $value;
5856
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5857
		}
5858
	}
5859
5860
	public static function restate() {
5861
		Jetpack::state( null, null, true );
5862
	}
5863
5864
	public static function check_privacy( $file ) {
5865
		static $is_site_publicly_accessible = null;
5866
5867
		if ( is_null( $is_site_publicly_accessible ) ) {
5868
			$is_site_publicly_accessible = false;
5869
5870
			Jetpack::load_xml_rpc_client();
5871
			$rpc = new Jetpack_IXR_Client();
5872
5873
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5874
			if ( $success ) {
5875
				$response = $rpc->getResponse();
5876
				if ( $response ) {
5877
					$is_site_publicly_accessible = true;
5878
				}
5879
			}
5880
5881
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5882
		}
5883
5884
		if ( $is_site_publicly_accessible ) {
5885
			return;
5886
		}
5887
5888
		$module_slug = self::get_module_slug( $file );
5889
5890
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5891
		if ( ! $privacy_checks ) {
5892
			$privacy_checks = $module_slug;
5893
		} else {
5894
			$privacy_checks .= ",$module_slug";
5895
		}
5896
5897
		Jetpack::state( 'privacy_checks', $privacy_checks );
5898
	}
5899
5900
	/**
5901
	 * Helper method for multicall XMLRPC.
5902
	 */
5903
	public static function xmlrpc_async_call() {
5904
		global $blog_id;
5905
		static $clients = array();
5906
5907
		$client_blog_id = is_multisite() ? $blog_id : 0;
5908
5909
		if ( ! isset( $clients[$client_blog_id] ) ) {
5910
			Jetpack::load_xml_rpc_client();
5911
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5912
			if ( function_exists( 'ignore_user_abort' ) ) {
5913
				ignore_user_abort( true );
5914
			}
5915
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5916
		}
5917
5918
		$args = func_get_args();
5919
5920
		if ( ! empty( $args[0] ) ) {
5921
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5922
		} elseif ( is_multisite() ) {
5923
			foreach ( $clients as $client_blog_id => $client ) {
5924
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5925
					continue;
5926
				}
5927
5928
				$switch_success = switch_to_blog( $client_blog_id, true );
5929
				if ( ! $switch_success ) {
5930
					continue;
5931
				}
5932
5933
				flush();
5934
				$client->query();
5935
5936
				restore_current_blog();
5937
			}
5938
		} else {
5939
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5940
				flush();
5941
				$clients[0]->query();
5942
			}
5943
		}
5944
	}
5945
5946
	public static function staticize_subdomain( $url ) {
5947
5948
		// Extract hostname from URL
5949
		$host = parse_url( $url, PHP_URL_HOST );
5950
5951
		// Explode hostname on '.'
5952
		$exploded_host = explode( '.', $host );
5953
5954
		// Retrieve the name and TLD
5955
		if ( count( $exploded_host ) > 1 ) {
5956
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5957
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5958
			// Rebuild domain excluding subdomains
5959
			$domain = $name . '.' . $tld;
5960
		} else {
5961
			$domain = $host;
5962
		}
5963
		// Array of Automattic domains
5964
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5965
5966
		// Return $url if not an Automattic domain
5967
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5968
			return $url;
5969
		}
5970
5971
		if ( is_ssl() ) {
5972
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5973
		}
5974
5975
		srand( crc32( basename( $url ) ) );
5976
		$static_counter = rand( 0, 2 );
5977
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5978
5979
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5980
	}
5981
5982
/* JSON API Authorization */
5983
5984
	/**
5985
	 * Handles the login action for Authorizing the JSON API
5986
	 */
5987
	function login_form_json_api_authorization() {
5988
		$this->verify_json_api_authorization_request();
5989
5990
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5991
5992
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5993
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5994
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5995
	}
5996
5997
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5998
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5999
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6000
			return $url;
6001
		}
6002
6003
		$parsed_url = parse_url( $url );
6004
		$url = strtok( $url, '?' );
6005
		$url = "$url?{$_SERVER['QUERY_STRING']}";
6006
		if ( ! empty( $parsed_url['query'] ) )
6007
			$url .= "&{$parsed_url['query']}";
6008
6009
		return $url;
6010
	}
6011
6012
	// Make sure the POSTed request is handled by the same action
6013
	function preserve_action_in_login_form_for_json_api_authorization() {
6014
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6015
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6016
	}
6017
6018
	// If someone logs in to approve API access, store the Access Code in usermeta
6019
	function store_json_api_authorization_token( $user_login, $user ) {
6020
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6021
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6022
		$token = wp_generate_password( 32, false );
6023
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6024
	}
6025
6026
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
6027
	function allow_wpcom_public_api_domain( $domains ) {
6028
		$domains[] = 'public-api.wordpress.com';
6029
		return $domains;
6030
	}
6031
6032
	// Add all wordpress.com environments to the safe redirect whitelist
6033
	function allow_wpcom_environments( $domains ) {
6034
		$domains[] = 'wordpress.com';
6035
		$domains[] = 'wpcalypso.wordpress.com';
6036
		$domains[] = 'horizon.wordpress.com';
6037
		$domains[] = 'calypso.localhost';
6038
		return $domains;
6039
	}
6040
6041
	// Add the Access Code details to the public-api.wordpress.com redirect
6042
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6043
		return add_query_arg(
6044
			urlencode_deep(
6045
				array(
6046
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6047
					'jetpack-user-id' => (int) $user->ID,
6048
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6049
				)
6050
			),
6051
			$redirect_to
6052
		);
6053
	}
6054
6055
6056
	/**
6057
	 * Verifies the request by checking the signature
6058
	 *
6059
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6060
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6061
	 *
6062
	 * @param null|array $environment
6063
	 */
6064
	function verify_json_api_authorization_request( $environment = null ) {
6065
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
6066
6067
		$environment = is_null( $environment )
6068
			? $_REQUEST
6069
			: $environment;
6070
6071
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
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...
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...
6072
		$token = Jetpack_Data::get_access_token( $envUserId );
6073
		if ( ! $token || empty( $token->secret ) ) {
6074
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
6075
		}
6076
6077
		$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' );
6078
6079
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6080
6081
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6082
			$signature = $jetpack_signature->sign_request(
6083
				$environment['token'],
6084
				$environment['timestamp'],
6085
				$environment['nonce'],
6086
				'',
6087
				'GET',
6088
				$environment['jetpack_json_api_original_query'],
6089
				null,
6090
				true
6091
			);
6092
		} else {
6093
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
6094
		}
6095
6096
		if ( ! $signature ) {
6097
			wp_die( $die_error );
6098
		} else if ( is_wp_error( $signature ) ) {
6099
			wp_die( $die_error );
6100
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
6101
			if ( is_ssl() ) {
6102
				// 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
6103
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
6104
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) { // phpcs:ignore PHPCompatibility -- skipping since `hash_equals` is part of WP core
6105
					wp_die( $die_error );
6106
				}
6107
			} else {
6108
				wp_die( $die_error );
6109
			}
6110
		}
6111
6112
		$timestamp = (int) $environment['timestamp'];
6113
		$nonce     = stripslashes( (string) $environment['nonce'] );
6114
6115
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
6116
			// De-nonce the nonce, at least for 5 minutes.
6117
			// 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)
6118
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6119
			if ( $old_nonce_time < time() - 300 ) {
6120
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
6121
			}
6122
		}
6123
6124
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6125
		$data_filters = array(
6126
			'state'        => 'opaque',
6127
			'client_id'    => 'int',
6128
			'client_title' => 'string',
6129
			'client_image' => 'url',
6130
		);
6131
6132
		foreach ( $data_filters as $key => $sanitation ) {
6133
			if ( ! isset( $data->$key ) ) {
6134
				wp_die( $die_error );
6135
			}
6136
6137
			switch ( $sanitation ) {
6138
			case 'int' :
6139
				$this->json_api_authorization_request[$key] = (int) $data->$key;
6140
				break;
6141
			case 'opaque' :
6142
				$this->json_api_authorization_request[$key] = (string) $data->$key;
6143
				break;
6144
			case 'string' :
6145
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6146
				break;
6147
			case 'url' :
6148
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6149
				break;
6150
			}
6151
		}
6152
6153
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6154
			wp_die( $die_error );
6155
		}
6156
	}
6157
6158
	function login_message_json_api_authorization( $message ) {
6159
		return '<p class="message">' . sprintf(
6160
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
6161
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6162
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6163
	}
6164
6165
	/**
6166
	 * Get $content_width, but with a <s>twist</s> filter.
6167
	 */
6168
	public static function get_content_width() {
6169
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
6170
		/**
6171
		 * Filter the Content Width value.
6172
		 *
6173
		 * @since 2.2.3
6174
		 *
6175
		 * @param string $content_width Content Width value.
6176
		 */
6177
		return apply_filters( 'jetpack_content_width', $content_width );
6178
	}
6179
6180
	/**
6181
	 * Pings the WordPress.com Mirror Site for the specified options.
6182
	 *
6183
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6184
	 *
6185
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6186
	 */
6187
	public function get_cloud_site_options( $option_names ) {
6188
		$option_names = array_filter( (array) $option_names, 'is_string' );
6189
6190
		Jetpack::load_xml_rpc_client();
6191
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6192
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6193
		if ( $xml->isError() ) {
6194
			return array(
6195
				'error_code' => $xml->getErrorCode(),
6196
				'error_msg'  => $xml->getErrorMessage(),
6197
			);
6198
		}
6199
		$cloud_site_options = $xml->getResponse();
6200
6201
		return $cloud_site_options;
6202
	}
6203
6204
	/**
6205
	 * Checks if the site is currently in an identity crisis.
6206
	 *
6207
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6208
	 */
6209
	public static function check_identity_crisis() {
6210
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6211
			return false;
6212
		}
6213
6214
		return Jetpack_Options::get_option( 'sync_error_idc' );
6215
	}
6216
6217
	/**
6218
	 * Checks whether the home and siteurl specifically are whitelisted
6219
	 * Written so that we don't have re-check $key and $value params every time
6220
	 * we want to check if this site is whitelisted, for example in footer.php
6221
	 *
6222
	 * @since  3.8.0
6223
	 * @return bool True = already whitelisted False = not whitelisted
6224
	 */
6225
	public static function is_staging_site() {
6226
		$is_staging = false;
6227
6228
		$known_staging = array(
6229
			'urls' => array(
6230
				'#\.staging\.wpengine\.com$#i', // WP Engine
6231
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6232
				),
6233
			'constants' => array(
6234
				'IS_WPE_SNAPSHOT',      // WP Engine
6235
				'KINSTA_DEV_ENV',       // Kinsta.com
6236
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6237
				'JETPACK_STAGING_MODE', // Generic
6238
				)
6239
			);
6240
		/**
6241
		 * Filters the flags of known staging sites.
6242
		 *
6243
		 * @since 3.9.0
6244
		 *
6245
		 * @param array $known_staging {
6246
		 *     An array of arrays that each are used to check if the current site is staging.
6247
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6248
		 *     @type array $constants PHP constants of known staging/developement environments.
6249
		 *  }
6250
		 */
6251
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6252
6253
		if ( isset( $known_staging['urls'] ) ) {
6254
			foreach ( $known_staging['urls'] as $url ){
6255
				if ( preg_match( $url, site_url() ) ) {
6256
					$is_staging = true;
6257
					break;
6258
				}
6259
			}
6260
		}
6261
6262
		if ( isset( $known_staging['constants'] ) ) {
6263
			foreach ( $known_staging['constants'] as $constant ) {
6264
				if ( defined( $constant ) && constant( $constant ) ) {
6265
					$is_staging = true;
6266
				}
6267
			}
6268
		}
6269
6270
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6271
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6272
			$is_staging = true;
6273
		}
6274
6275
		/**
6276
		 * Filters is_staging_site check.
6277
		 *
6278
		 * @since 3.9.0
6279
		 *
6280
		 * @param bool $is_staging If the current site is a staging site.
6281
		 */
6282
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6283
	}
6284
6285
	/**
6286
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6287
	 *
6288
	 * @since 4.4.0
6289
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6290
	 *
6291
	 * @return bool
6292
	 */
6293
	public static function validate_sync_error_idc_option() {
6294
		$is_valid = false;
6295
6296
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6297
		if ( false === $idc_allowed ) {
6298
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6299
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6300
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6301
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6302
				$transient_duration = HOUR_IN_SECONDS;
6303
			} else {
6304
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6305
				$idc_allowed = '1';
6306
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6307
			}
6308
6309
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6310
		}
6311
6312
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6313
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6314
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6315
			$local_options = self::get_sync_error_idc_option();
6316
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6317
				$is_valid = true;
6318
			}
6319
		}
6320
6321
		/**
6322
		 * Filters whether the sync_error_idc option is valid.
6323
		 *
6324
		 * @since 4.4.0
6325
		 *
6326
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6327
		 */
6328
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6329
6330
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6331
			// Since the option exists, and did not validate, delete it
6332
			Jetpack_Options::delete_option( 'sync_error_idc' );
6333
		}
6334
6335
		return $is_valid;
6336
	}
6337
6338
	/**
6339
	 * Normalizes a url by doing three things:
6340
	 *  - Strips protocol
6341
	 *  - Strips www
6342
	 *  - Adds a trailing slash
6343
	 *
6344
	 * @since 4.4.0
6345
	 * @param string $url
6346
	 * @return WP_Error|string
6347
	 */
6348
	public static function normalize_url_protocol_agnostic( $url ) {
6349
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6350
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6351
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6352
		}
6353
6354
		// Strip www and protocols
6355
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6356
		return $url;
6357
	}
6358
6359
	/**
6360
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6361
	 *
6362
	 * @since 4.4.0
6363
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6364
	 *
6365
	 * @param array $response
6366
	 * @return array Array of the local urls, wpcom urls, and error code
6367
	 */
6368
	public static function get_sync_error_idc_option( $response = array() ) {
6369
		// Since the local options will hit the database directly, store the values
6370
		// in a transient to allow for autoloading and caching on subsequent views.
6371
		$local_options = get_transient( 'jetpack_idc_local' );
6372
		if ( false === $local_options ) {
6373
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6374
			$local_options = array(
6375
				'home'    => Jetpack_Sync_Functions::home_url(),
6376
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6377
			);
6378
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6379
		}
6380
6381
		$options = array_merge( $local_options, $response );
6382
6383
		$returned_values = array();
6384
		foreach( $options as $key => $option ) {
6385
			if ( 'error_code' === $key ) {
6386
				$returned_values[ $key ] = $option;
6387
				continue;
6388
			}
6389
6390
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6391
				continue;
6392
			}
6393
6394
			$returned_values[ $key ] = $normalized_url;
6395
		}
6396
6397
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6398
6399
		return $returned_values;
6400
	}
6401
6402
	/**
6403
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6404
	 * If set to true, the site will be put into staging mode.
6405
	 *
6406
	 * @since 4.3.2
6407
	 * @return bool
6408
	 */
6409
	public static function sync_idc_optin() {
6410
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6411
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6412
		} else {
6413
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6414
		}
6415
6416
		/**
6417
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6418
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6419
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6420
		 *
6421
		 * @since 4.3.2
6422
		 *
6423
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6424
		 */
6425
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6426
	}
6427
6428
	/**
6429
	 * Maybe Use a .min.css stylesheet, maybe not.
6430
	 *
6431
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6432
	 */
6433
	public static function maybe_min_asset( $url, $path, $plugin ) {
6434
		// Short out on things trying to find actual paths.
6435
		if ( ! $path || empty( $plugin ) ) {
6436
			return $url;
6437
		}
6438
6439
		$path = ltrim( $path, '/' );
6440
6441
		// Strip out the abspath.
6442
		$base = dirname( plugin_basename( $plugin ) );
6443
6444
		// Short out on non-Jetpack assets.
6445
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6446
			return $url;
6447
		}
6448
6449
		// File name parsing.
6450
		$file              = "{$base}/{$path}";
6451
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6452
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6453
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6454
		$extension         = array_shift( $file_name_parts_r );
6455
6456
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6457
			// Already pointing at the minified version.
6458
			if ( 'min' === $file_name_parts_r[0] ) {
6459
				return $url;
6460
			}
6461
6462
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6463
			if ( file_exists( $min_full_path ) ) {
6464
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6465
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6466
				if ( 'css' === $extension ) {
6467
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6468
					self::$min_assets[ $key ] = $path;
6469
				}
6470
			}
6471
		}
6472
6473
		return $url;
6474
	}
6475
6476
	/**
6477
	 * If the asset is minified, let's flag .min as the suffix.
6478
	 *
6479
	 * Attached to `style_loader_src` filter.
6480
	 *
6481
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
There is no parameter named $tag. 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...
6482
	 * @param string $handle The registered handle of the script in question.
6483
	 * @param string $href The url of the asset in question.
0 ignored issues
show
There is no parameter named $href. 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...
6484
	 */
6485
	public static function set_suffix_on_min( $src, $handle ) {
6486
		if ( false === strpos( $src, '.min.css' ) ) {
6487
			return $src;
6488
		}
6489
6490
		if ( ! empty( self::$min_assets ) ) {
6491
			foreach ( self::$min_assets as $file => $path ) {
6492
				if ( false !== strpos( $src, $file ) ) {
6493
					wp_style_add_data( $handle, 'suffix', '.min' );
6494
					return $src;
6495
				}
6496
			}
6497
		}
6498
6499
		return $src;
6500
	}
6501
6502
	/**
6503
	 * Maybe inlines a stylesheet.
6504
	 *
6505
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6506
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6507
	 *
6508
	 * Attached to `style_loader_tag` filter.
6509
	 *
6510
	 * @param string $tag The tag that would link to the external asset.
6511
	 * @param string $handle The registered handle of the script in question.
6512
	 *
6513
	 * @return string
6514
	 */
6515
	public static function maybe_inline_style( $tag, $handle ) {
6516
		global $wp_styles;
6517
		$item = $wp_styles->registered[ $handle ];
6518
6519
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6520
			return $tag;
6521
		}
6522
6523
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6524
			$href = $matches[1];
6525
			// Strip off query string
6526
			if ( $pos = strpos( $href, '?' ) ) {
6527
				$href = substr( $href, 0, $pos );
6528
			}
6529
			// Strip off fragment
6530
			if ( $pos = strpos( $href, '#' ) ) {
6531
				$href = substr( $href, 0, $pos );
6532
			}
6533
		} else {
6534
			return $tag;
6535
		}
6536
6537
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6538
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6539
			return $tag;
6540
		}
6541
6542
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6543
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6544
			// And this isn't the pass that actually deals with the RTL version...
6545
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6546
				// Short out, as the RTL version will deal with it in a moment.
6547
				return $tag;
6548
			}
6549
		}
6550
6551
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6552
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6553
		if ( $css ) {
6554
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6555
			if ( empty( $item->extra['after'] ) ) {
6556
				wp_add_inline_style( $handle, $css );
6557
			} else {
6558
				array_unshift( $item->extra['after'], $css );
6559
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6560
			}
6561
		}
6562
6563
		return $tag;
6564
	}
6565
6566
	/**
6567
	 * Loads a view file from the views
6568
	 *
6569
	 * Data passed in with the $data parameter will be available in the
6570
	 * template file as $data['value']
6571
	 *
6572
	 * @param string $template - Template file to load
6573
	 * @param array $data - Any data to pass along to the template
6574
	 * @return boolean - If template file was found
6575
	 **/
6576
	public function load_view( $template, $data = array() ) {
6577
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6578
6579
		if( file_exists( $views_dir . $template ) ) {
6580
			require_once( $views_dir . $template );
6581
			return true;
6582
		}
6583
6584
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6585
		return false;
6586
	}
6587
6588
	/**
6589
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6590
	 */
6591
	public function deprecated_hooks() {
6592
		global $wp_filter;
6593
6594
		/*
6595
		 * Format:
6596
		 * deprecated_filter_name => replacement_name
6597
		 *
6598
		 * If there is no replacement, use null for replacement_name
6599
		 */
6600
		$deprecated_list = array(
6601
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6602
			'wpl_sharing_2014_1'                                     => null,
6603
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6604
			'jetpack_identity_crisis_options_to_check'               => null,
6605
			'update_option_jetpack_single_user_site'                 => null,
6606
			'audio_player_default_colors'                            => null,
6607
			'add_option_jetpack_featured_images_enabled'             => null,
6608
			'add_option_jetpack_update_details'                      => null,
6609
			'add_option_jetpack_updates'                             => null,
6610
			'add_option_jetpack_network_name'                        => null,
6611
			'add_option_jetpack_network_allow_new_registrations'     => null,
6612
			'add_option_jetpack_network_add_new_users'               => null,
6613
			'add_option_jetpack_network_site_upload_space'           => null,
6614
			'add_option_jetpack_network_upload_file_types'           => null,
6615
			'add_option_jetpack_network_enable_administration_menus' => null,
6616
			'add_option_jetpack_is_multi_site'                       => null,
6617
			'add_option_jetpack_is_main_network'                     => null,
6618
			'add_option_jetpack_main_network_site'                   => null,
6619
			'jetpack_sync_all_registered_options'                    => null,
6620
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6621
			'jetpack_is_post_mailable'                               => null,
6622
			'jetpack_seo_site_host'                                  => null,
6623
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6624
			'jetpack_holiday_snow_option_name'                       => null,
6625
			'jetpack_holiday_chance_of_snow'                         => null,
6626
			'jetpack_holiday_snow_js_url'                            => null,
6627
			'jetpack_is_holiday_snow_season'                         => null,
6628
			'jetpack_holiday_snow_option_updated'                    => null,
6629
			'jetpack_holiday_snowing'                                => null,
6630
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6631
			'jetpack_cache_plans'                                    => null,
6632
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6633
		);
6634
6635
		// This is a silly loop depth. Better way?
6636
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6637
			if ( has_action( $hook ) ) {
6638
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6639
					foreach( $values AS $hooked ) {
6640
						if ( is_callable( $hooked['function'] ) ) {
6641
							$function_name = 'an anonymous function';
6642
						} else {
6643
							$function_name = $hooked['function'];
6644
						}
6645
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6646
					}
6647
				}
6648
			}
6649
		}
6650
	}
6651
6652
	/**
6653
	 * Converts any url in a stylesheet, to the correct absolute url.
6654
	 *
6655
	 * Considerations:
6656
	 *  - Normal, relative URLs     `feh.png`
6657
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6658
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6659
	 *  - Absolute URLs             `http://domain.com/feh.png`
6660
	 *  - Domain root relative URLs `/feh.png`
6661
	 *
6662
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6663
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6664
	 *
6665
	 * @return mixed|string
6666
	 */
6667
	public static function absolutize_css_urls( $css, $css_file_url ) {
6668
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6669
		$css_dir = dirname( $css_file_url );
6670
		$p       = parse_url( $css_dir );
6671
		$domain  = sprintf(
6672
					'%1$s//%2$s%3$s%4$s',
6673
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6674
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6675
					$p['host'],
6676
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6677
				);
6678
6679
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6680
			$find = $replace = array();
6681
			foreach ( $matches as $match ) {
6682
				$url = trim( $match['path'], "'\" \t" );
6683
6684
				// If this is a data url, we don't want to mess with it.
6685
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6686
					continue;
6687
				}
6688
6689
				// If this is an absolute or protocol-agnostic url,
6690
				// we don't want to mess with it.
6691
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6692
					continue;
6693
				}
6694
6695
				switch ( substr( $url, 0, 1 ) ) {
6696
					case '/':
6697
						$absolute = $domain . $url;
6698
						break;
6699
					default:
6700
						$absolute = $css_dir . '/' . $url;
6701
				}
6702
6703
				$find[]    = $match[0];
6704
				$replace[] = sprintf( 'url("%s")', $absolute );
6705
			}
6706
			$css = str_replace( $find, $replace, $css );
6707
		}
6708
6709
		return $css;
6710
	}
6711
6712
	/**
6713
	 * This methods removes all of the registered css files on the front end
6714
	 * from Jetpack in favor of using a single file. In effect "imploding"
6715
	 * all the files into one file.
6716
	 *
6717
	 * Pros:
6718
	 * - Uses only ONE css asset connection instead of 15
6719
	 * - Saves a minimum of 56k
6720
	 * - Reduces server load
6721
	 * - Reduces time to first painted byte
6722
	 *
6723
	 * Cons:
6724
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6725
	 *		should not cause any issues with themes.
6726
	 * - Plugins/themes dequeuing styles no longer do anything. See
6727
	 *		jetpack_implode_frontend_css filter for a workaround
6728
	 *
6729
	 * For some situations developers may wish to disable css imploding and
6730
	 * instead operate in legacy mode where each file loads seperately and
6731
	 * can be edited individually or dequeued. This can be accomplished with
6732
	 * the following line:
6733
	 *
6734
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6735
	 *
6736
	 * @since 3.2
6737
	 **/
6738
	public function implode_frontend_css( $travis_test = false ) {
6739
		$do_implode = true;
6740
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6741
			$do_implode = false;
6742
		}
6743
6744
		/**
6745
		 * Allow CSS to be concatenated into a single jetpack.css file.
6746
		 *
6747
		 * @since 3.2.0
6748
		 *
6749
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6750
		 */
6751
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6752
6753
		// Do not use the imploded file when default behaviour was altered through the filter
6754
		if ( ! $do_implode ) {
6755
			return;
6756
		}
6757
6758
		// We do not want to use the imploded file in dev mode, or if not connected
6759
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6760
			if ( ! $travis_test ) {
6761
				return;
6762
			}
6763
		}
6764
6765
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6766
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6767
			return;
6768
		}
6769
6770
		/*
6771
		 * Now we assume Jetpack is connected and able to serve the single
6772
		 * file.
6773
		 *
6774
		 * In the future there will be a check here to serve the file locally
6775
		 * or potentially from the Jetpack CDN
6776
		 *
6777
		 * For now:
6778
		 * - Enqueue a single imploded css file
6779
		 * - Zero out the style_loader_tag for the bundled ones
6780
		 * - Be happy, drink scotch
6781
		 */
6782
6783
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6784
6785
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6786
6787
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6788
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6789
	}
6790
6791
	function concat_remove_style_loader_tag( $tag, $handle ) {
6792
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6793
			$tag = '';
6794
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6795
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6796
			}
6797
		}
6798
6799
		return $tag;
6800
	}
6801
6802
	/*
6803
	 * Check the heartbeat data
6804
	 *
6805
	 * Organizes the heartbeat data by severity.  For example, if the site
6806
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6807
	 *
6808
	 * Data will be added to "caution" array, if it either:
6809
	 *  - Out of date Jetpack version
6810
	 *  - Out of date WP version
6811
	 *  - Out of date PHP version
6812
	 *
6813
	 * $return array $filtered_data
6814
	 */
6815
	public static function jetpack_check_heartbeat_data() {
6816
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6817
6818
		$good    = array();
6819
		$caution = array();
6820
		$bad     = array();
6821
6822
		foreach ( $raw_data as $stat => $value ) {
6823
6824
			// Check jetpack version
6825
			if ( 'version' == $stat ) {
6826
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6827
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6828
					continue;
6829
				}
6830
			}
6831
6832
			// Check WP version
6833
			if ( 'wp-version' == $stat ) {
6834
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6835
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6836
					continue;
6837
				}
6838
			}
6839
6840
			// Check PHP version
6841
			if ( 'php-version' == $stat ) {
6842
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6843
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6844
					continue;
6845
				}
6846
			}
6847
6848
			// Check ID crisis
6849
			if ( 'identitycrisis' == $stat ) {
6850
				if ( 'yes' == $value ) {
6851
					$bad[ $stat ] = $value;
6852
					continue;
6853
				}
6854
			}
6855
6856
			// The rest are good :)
6857
			$good[ $stat ] = $value;
6858
		}
6859
6860
		$filtered_data = array(
6861
			'good'    => $good,
6862
			'caution' => $caution,
6863
			'bad'     => $bad
6864
		);
6865
6866
		return $filtered_data;
6867
	}
6868
6869
6870
	/*
6871
	 * This method is used to organize all options that can be reset
6872
	 * without disconnecting Jetpack.
6873
	 *
6874
	 * It is used in class.jetpack-cli.php to reset options
6875
	 *
6876
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6877
	 *
6878
	 * @return array of options to delete.
6879
	 */
6880
	public static function get_jetpack_options_for_reset() {
6881
		return Jetpack_Options::get_options_for_reset();
6882
	}
6883
6884
	/**
6885
	 * Check if an option of a Jetpack module has been updated.
6886
	 *
6887
	 * If any module option has been updated before Jump Start has been dismissed,
6888
	 * update the 'jumpstart' option so we can hide Jump Start.
6889
	 *
6890
	 * @param string $option_name
6891
	 *
6892
	 * @return bool
6893
	 */
6894
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6895
		// Bail if Jump Start has already been dismissed
6896
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6897
			return false;
6898
		}
6899
6900
		$jetpack = Jetpack::init();
6901
6902
		// Manual build of module options
6903
		$option_names = self::get_jetpack_options_for_reset();
6904
6905
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6906
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6907
6908
			//Jump start is being dismissed send data to MC Stats
6909
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6910
6911
			$jetpack->do_stats( 'server_side' );
6912
		}
6913
6914
	}
6915
6916
	/*
6917
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6918
	 * so we can bring them directly to their site in calypso.
6919
	 *
6920
	 * @param string | url
6921
	 * @return string | url without the guff
6922
	 */
6923
	public static function build_raw_urls( $url ) {
6924
		$strip_http = '/.*?:\/\//i';
6925
		$url = preg_replace( $strip_http, '', $url  );
6926
		$url = str_replace( '/', '::', $url );
6927
		return $url;
6928
	}
6929
6930
	/**
6931
	 * Stores and prints out domains to prefetch for page speed optimization.
6932
	 *
6933
	 * @param mixed $new_urls
6934
	 */
6935
	public static function dns_prefetch( $new_urls = null ) {
6936
		static $prefetch_urls = array();
6937
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6938
			echo "\r\n";
6939
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6940
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6941
			}
6942
		} elseif ( ! empty( $new_urls ) ) {
6943
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6944
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6945
			}
6946
			foreach ( (array) $new_urls as $this_new_url ) {
6947
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6948
			}
6949
			$prefetch_urls = array_unique( $prefetch_urls );
6950
		}
6951
	}
6952
6953
	public function wp_dashboard_setup() {
6954
		if ( self::is_active() ) {
6955
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6956
		}
6957
6958
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6959
			wp_add_dashboard_widget(
6960
				'jetpack_summary_widget',
6961
				esc_html__( 'Site Stats', 'jetpack' ),
6962
				array( __CLASS__, 'dashboard_widget' )
6963
			);
6964
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6965
6966
			// If we're inactive and not in development mode, sort our box to the top.
6967
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6968
				global $wp_meta_boxes;
6969
6970
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6971
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6972
6973
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6974
			}
6975
		}
6976
	}
6977
6978
	/**
6979
	 * @param mixed $result Value for the user's option
0 ignored issues
show
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...
6980
	 * @return mixed
6981
	 */
6982
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6983
		if ( ! is_array( $sorted ) ) {
6984
			return $sorted;
6985
		}
6986
6987
		foreach ( $sorted as $box_context => $ids ) {
6988
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6989
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6990
				continue;
6991
			}
6992
6993
			$ids_array = explode( ',', $ids );
6994
			$key = array_search( 'dashboard_stats', $ids_array );
6995
6996
			if ( false !== $key ) {
6997
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6998
				$ids_array[ $key ] = 'jetpack_summary_widget';
6999
				$sorted[ $box_context ] = implode( ',', $ids_array );
7000
				// We've found it, stop searching, and just return.
7001
				break;
7002
			}
7003
		}
7004
7005
		return $sorted;
7006
	}
7007
7008
	public static function dashboard_widget() {
7009
		/**
7010
		 * Fires when the dashboard is loaded.
7011
		 *
7012
		 * @since 3.4.0
7013
		 */
7014
		do_action( 'jetpack_dashboard_widget' );
7015
	}
7016
7017
	public static function dashboard_widget_footer() {
7018
		?>
7019
		<footer>
7020
7021
		<div class="protect">
7022
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
7023
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
7024
				<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>
7025
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
7026
				<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' ); ?>">
7027
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
7028
				</a>
7029
			<?php else : ?>
7030
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
7031
			<?php endif; ?>
7032
		</div>
7033
7034
		<div class="akismet">
7035
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7036
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
7037
				<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>
7038
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7039
				<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">
7040
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
7041
				</a>
7042
			<?php else : ?>
7043
				<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>
7044
			<?php endif; ?>
7045
		</div>
7046
7047
		</footer>
7048
		<?php
7049
	}
7050
7051
	/**
7052
	 * Return string containing the Jetpack logo.
7053
	 *
7054
	 * @since 3.9.0
7055
	 *
7056
	 * @return string
7057
	 */
7058
	public static function get_jp_emblem() {
7059
		return '<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 32 32"><path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/></svg>';
7060
	}
7061
7062
	/*
7063
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7064
	 */
7065
	function jetpack_icon_user_connected( $columns ) {
7066
		$columns['user_jetpack'] = '';
7067
		return $columns;
7068
	}
7069
7070
	/*
7071
	 * Show Jetpack icon if the user is linked.
7072
	 */
7073
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7074
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
7075
			$emblem_html = sprintf(
7076
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7077
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7078
				Jetpack::get_jp_emblem()
7079
			);
7080
			return $emblem_html;
7081
		}
7082
7083
		return $val;
7084
	}
7085
7086
	/*
7087
	 * Style the Jetpack user column
7088
	 */
7089
	function jetpack_user_col_style() {
7090
		global $current_screen;
7091
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
7092
			<style>
7093
				.fixed .column-user_jetpack {
7094
					width: 21px;
7095
				}
7096
				.jp-emblem-user-admin svg {
7097
					width: 20px;
7098
					height: 20px;
7099
				}
7100
				.jp-emblem-user-admin path {
7101
					fill: #00BE28;
7102
				}
7103
			</style>
7104
		<?php }
7105
	}
7106
7107
	/**
7108
	 * Checks if Akismet is active and working.
7109
	 *
7110
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7111
	 * that implied usage of methods present since more recent version.
7112
	 * See https://github.com/Automattic/jetpack/pull/9585
7113
	 *
7114
	 * @since  5.1.0
7115
	 *
7116
	 * @return bool True = Akismet available. False = Aksimet not available.
7117
	 */
7118
	public static function is_akismet_active() {
7119
		if ( method_exists( 'Akismet' , 'http_post' ) ) {
7120
			$akismet_key = Akismet::get_api_key();
7121
			if ( ! $akismet_key ) {
7122
				return false;
7123
			}
7124
			$cached_key_verification = get_transient( 'jetpack_akismet_key_is_valid' );
7125
7126
			// We cache the result of the Akismet key verification for ten minutes.
7127
			if ( in_array( $cached_key_verification, array( 'valid', 'invalid' ) ) ) {
7128
				$akismet_key_state = $cached_key_verification;
7129
			} else {
7130
				$akismet_key_state = Akismet::verify_key( $akismet_key );
7131
				if ( 'failed' === $akismet_key_state ) {
7132
					return false;
7133
				}
7134
				set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7135
			}
7136
7137
			return ( 'valid' === $akismet_key_state );
7138
		}
7139
		return false;
7140
	}
7141
7142
	/**
7143
	 * Checks if one or more function names is in debug_backtrace
7144
	 *
7145
	 * @param $names Mixed string name of function or array of string names of functions
7146
	 *
7147
	 * @return bool
7148
	 */
7149
	public static function is_function_in_backtrace( $names ) {
7150
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility
7151
		if ( ! is_array( $names ) ) {
7152
			$names = array( $names );
7153
		}
7154
		$names_as_keys = array_flip( $names );
7155
7156
		//Do check in constant O(1) time for PHP5.5+
7157
		if ( function_exists( 'array_column' ) ) {
7158
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility
7159
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
7160
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
7161
			return ! empty ( $intersection );
7162
		}
7163
7164
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
7165
		foreach ( $backtrace as $call ) {
7166
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
7167
				return true;
7168
			}
7169
		}
7170
		return false;
7171
	}
7172
7173
	/**
7174
	 * Given a minified path, and a non-minified path, will return
7175
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7176
	 *
7177
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7178
	 * root Jetpack directory.
7179
	 *
7180
	 * @since 5.6.0
7181
	 *
7182
	 * @param string $min_path
7183
	 * @param string $non_min_path
7184
	 * @return string The URL to the file
7185
	 */
7186
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7187
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
7188
			? $non_min_path
7189
			: $min_path;
7190
7191
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7192
	}
7193
7194
	/**
7195
	 * Checks for whether Jetpack Rewind is enabled.
7196
	 * Will return true if the state of Rewind is anything except "unavailable".
7197
	 * @return bool|int|mixed
7198
	 */
7199
	public static function is_rewind_enabled() {
7200
		if ( ! Jetpack::is_active() ) {
7201
			return false;
7202
		}
7203
7204
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7205
		if ( false === $rewind_enabled ) {
7206
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7207
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7208
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7209
				&& ! empty( $rewind_data['state'] )
7210
				&& 'active' === $rewind_data['state'] )
7211
				? 1
7212
				: 0;
7213
7214
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7215
		}
7216
		return $rewind_enabled;
7217
	}
7218
7219
	/**
7220
	 * Checks whether or not TOS has been agreed upon.
7221
	 * Will return true if a user has clicked to register, or is already connected.
7222
	 */
7223
	public static function jetpack_tos_agreed() {
7224
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7225
	}
7226
7227
	/**
7228
	 * Handles activating default modules as well general cleanup for the new connection.
7229
	 *
7230
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7231
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7232
	 * @return void
7233
	 */
7234
	public static function handle_post_authorization_actions( $activate_sso = false, $redirect_on_activation_error = false ) {
7235
		$other_modules = $activate_sso
7236
			? array( 'sso' )
7237
			: array();
7238
7239 View Code Duplication
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7240
			Jetpack::delete_active_modules();
7241
7242
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, false );
0 ignored issues
show
999 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...
7243
		} else {
7244
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, false );
7245
		}
7246
7247
		// Since this is a fresh connection, be sure to clear out IDC options
7248
		Jetpack_IDC::clear_all_idc_options();
7249
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7250
7251
		// Start nonce cleaner
7252
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7253
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7254
7255
		Jetpack::state( 'message', 'authorized' );
7256
	}
7257
}
7258