Completed
Push — update/split-class-jetpack ( 2a34fb )
by
unknown
13:38
created

Jetpack::get_active_modules()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 32
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 8
nop 0
dl 0
loc 32
rs 6.7272
c 0
b 0
f 0
1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack extends Jetpack_Functions {
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
	);
63
64
	/**
65
	 * Contains all assets that have had their URL rewritten to minified versions.
66
	 *
67
	 * @var array
68
	 */
69
	static $min_assets = array();
0 ignored issues
show
Coding Style introduced by
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...
70
71
	public $plugins_to_deactivate = array(
72
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
73
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
74
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
75
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
76
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
77
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
78
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
79
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
80
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
81
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
82
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
83
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
84
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
85
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
86
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
87
	);
88
89
	static $capability_translations = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $capability_translations.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
90
		'administrator' => 'manage_options',
91
		'editor'        => 'edit_others_posts',
92
		'author'        => 'publish_posts',
93
		'contributor'   => 'edit_posts',
94
		'subscriber'    => 'read',
95
	);
96
97
	/**
98
	 * Map of modules that have conflicts with plugins and should not be auto-activated
99
	 * if the plugins are active.  Used by filter_default_modules
100
	 *
101
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
102
	 * change `module-slug` and add this to your plugin:
103
	 *
104
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
105
	 * function my_jetpack_get_default_modules( $modules ) {
106
	 *     return array_diff( $modules, array( 'module-slug' ) );
107
	 * }
108
	 *
109
	 * @var array
110
	 */
111
	private $conflicting_plugins = array(
112
		'comments'          => array(
113
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
114
			'Disqus'                               => 'disqus-comment-system/disqus.php',
115
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
116
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
117
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
118
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
119
		),
120
		'comment-likes' => array(
121
			'Epoch'                                => 'epoch/plugincore.php',
122
		),
123
		'contact-form'      => array(
124
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
125
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
126
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
127
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
128
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
129
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
130
		),
131
		'minileven'         => array(
132
			'WPtouch'                              => 'wptouch/wptouch.php',
133
		),
134
		'latex'             => array(
135
			'LaTeX for WordPress'                  => 'latex/latex.php',
136
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
137
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
138
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
139
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
140
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
141
		),
142
		'protect'           => array(
143
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
144
			'Captcha'                              => 'captcha/captcha.php',
145
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
146
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
147
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
148
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
149
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
150
			'Security-protection'                  => 'security-protection/security-protection.php',
151
			'Login Security'                       => 'login-security/login-security.php',
152
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
153
			'Wordfence Security'                   => 'wordfence/wordfence.php',
154
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
155
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
156
		),
157
		'random-redirect'   => array(
158
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
159
		),
160
		'related-posts'     => array(
161
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
162
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
163
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
164
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
165
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
166
			'outbrain'                             => 'outbrain/outbrain.php',
167
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
168
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
169
		),
170
		'sharedaddy'        => array(
171
			'AddThis'                              => 'addthis/addthis_social_widget.php',
172
			'Add To Any'                           => 'add-to-any/add-to-any.php',
173
			'ShareThis'                            => 'share-this/sharethis.php',
174
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
175
		),
176
		'seo-tools' => array(
177
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
178
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
179
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
180
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
181
		),
182
		'verification-tools' => array(
183
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
184
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
185
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
186
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
187
		),
188
		'widget-visibility' => array(
189
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
190
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
191
		),
192
		'sitemaps' => array(
193
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
194
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
195
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
196
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
197
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
198
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
199
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
200
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
201
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
202
			'Sitemap'                              => 'sitemap/sitemap.php',
203
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
204
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
205
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
206
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
207
		),
208
		'lazy-images' => array(
209
			'Lazy Load'              => 'lazy-load/lazy-load.php',
210
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
211
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
212
		),
213
	);
214
215
	/**
216
	 * Plugins for which we turn off our Facebook OG Tags implementation.
217
	 *
218
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
219
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
220
	 *
221
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
222
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
223
	 */
224
	private $open_graph_conflicting_plugins = array(
225
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
226
		                                                         // 2 Click Social Media Buttons
227
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
228
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
229
		'autodescription/autodescription.php',                   // The SEO Framework
230
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
231
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
232
		                                                         // Open Graph Meta Tags by Heateor
233
		'facebook/facebook.php',                                 // Facebook (official plugin)
234
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
235
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
236
		                                                         // Facebook Featured Image & OG Meta Tags
237
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
238
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
239
		                                                         // Facebook Open Graph Meta Tags for WordPress
240
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
241
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
242
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
243
		                                                         // Fedmich's Facebook Open Graph Meta
244
		'network-publisher/networkpub.php',                      // Network Publisher
245
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
246
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
247
		                                                         // NextScripts SNAP
248
		'og-tags/og-tags.php',                                   // OG Tags
249
		'opengraph/opengraph.php',                               // Open Graph
250
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
251
		                                                         // Open Graph Protocol Framework
252
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
253
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
254
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
255
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
256
		'sharepress/sharepress.php',                             // SharePress
257
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
258
		'social-discussions/social-discussions.php',             // Social Discussions
259
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
260
		'socialize/socialize.php',                               // Socialize
261
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
262
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
263
		                                                         // Tweet, Like, Google +1 and Share
264
		'wordbooker/wordbooker.php',                             // Wordbooker
265
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
266
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
267
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
268
		                                                         // WP Facebook Like Send & Open Graph Meta
269
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
270
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
271
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
272
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
273
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
274
	);
275
276
	/**
277
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
278
	 */
279
	private $twitter_cards_conflicting_plugins = array(
280
	//	'twitter/twitter.php',                       // The official one handles this on its own.
281
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
282
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
283
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
284
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
285
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
286
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
287
		'twitter-cards/twitter-cards.php',           // Twitter Cards
288
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
289
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
290
	);
291
292
	/**
293
	 * Message to display in admin_notice
294
	 * @var string
295
	 */
296
	public $message = '';
297
298
	/**
299
	 * Error to display in admin_notice
300
	 * @var string
301
	 */
302
	public $error = '';
303
304
	/**
305
	 * Modules that need more privacy description.
306
	 * @var string
307
	 */
308
	public $privacy_checks = '';
309
310
	/**
311
	 * Stats to record once the page loads
312
	 *
313
	 * @var array
314
	 */
315
	public $stats = array();
316
317
	/**
318
	 * Jetpack_Sync object
319
	 */
320
	public $sync;
321
322
	/**
323
	 * Verified data for JSON authorization request
324
	 */
325
	public $json_api_authorization_request = array();
326
327
	/**
328
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
329
	 */
330
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
331
332
	/**
333
	 * Holds the singleton instance of this class
334
	 * @since 2.3.3
335
	 * @var Jetpack
336
	 */
337
	static $instance = false;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $instance.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
338
339
	/**
340
	 * Singleton
341
	 * @static
342
	 */
343
	public static function init() {
344
		if ( ! self::$instance ) {
345
			self::$instance = new Jetpack;
346
347
			self::$instance->plugin_upgrade();
348
		}
349
350
		return self::$instance;
351
	}
352
353
	/**
354
	 * Must never be called statically
355
	 */
356
	function plugin_upgrade() {
357
		if ( Jetpack::is_active() ) {
358
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
359
			if ( JETPACK__VERSION != $version ) {
360
				// Prevent multiple upgrades at once - only a single process should trigger
361
				// an upgrade to avoid stampedes
362
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
363
					return;
364
				}
365
366
				// Set a short lock to prevent multiple instances of the upgrade
367
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
368
369
				// check which active modules actually exist and remove others from active_modules list
370
				$unfiltered_modules = Jetpack::get_active_modules();
371
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
372
				if ( array_diff( $unfiltered_modules, $modules ) ) {
373
					Jetpack::update_active_modules( $modules );
374
				}
375
376
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
377
378
				// Upgrade to 4.3.0
379
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
380
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
381
				}
382
383
				// Make sure Markdown for posts gets turned back on
384
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
385
					update_option( 'wpcom_publish_posts_with_markdown', true );
386
				}
387
388
				if ( did_action( 'wp_loaded' ) ) {
389
					self::upgrade_on_load();
390
				} else {
391
					add_action(
392
						'wp_loaded',
393
						array( __CLASS__, 'upgrade_on_load' )
394
					);
395
				}
396
			}
397
		}
398
	}
399
400
	/**
401
	 * Runs upgrade routines that need to have modules loaded.
402
	 */
403
	static function upgrade_on_load() {
404
405
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
406
		// This can happen in case Jetpack has been just upgraded and is
407
		// being initialized late during the page load. In this case we wait
408
		// until the next proper admin page load with Jetpack active.
409
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
410
			delete_transient( self::$plugin_upgrade_lock_key );
411
412
			return;
413
		}
414
415
		Jetpack::maybe_set_version_option();
416
417
		if ( class_exists( 'Jetpack_Widget_Conditions' ) ) {
418
			Jetpack_Widget_Conditions::migrate_post_type_rules();
419
		}
420
421
		if (
422
			class_exists( 'Jetpack_Sitemap_Manager' )
423
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
424
		) {
425
			do_action( 'jetpack_sitemaps_purge_data' );
426
		}
427
428
		delete_transient( self::$plugin_upgrade_lock_key );
429
	}
430
431
	static function activate_manage( ) {
432
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
433
			self::activate_module( 'manage', false, false );
434
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
435
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
436
		}
437
	}
438
439
	static function update_active_modules( $modules ) {
440
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
441
442
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
443
444
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
445
			$new_active_modules = array_diff( $modules, $current_modules );
446
			foreach( $new_active_modules as $module ) {
447
				/**
448
				 * Fires when a specific module is activated.
449
				 *
450
				 * @since 1.9.0
451
				 *
452
				 * @param string $module Module slug.
453
				 * @param boolean $success whether the module was activated. @since 4.2
454
				 */
455
				do_action( 'jetpack_activate_module', $module, $success );
456
457
				/**
458
				 * Fires when a module is activated.
459
				 * The dynamic part of the filter, $module, is the module slug.
460
				 *
461
				 * @since 1.9.0
462
				 *
463
				 * @param string $module Module slug.
464
				 */
465
				do_action( "jetpack_activate_module_$module", $module );
466
			}
467
468
			$new_deactive_modules = array_diff( $current_modules, $modules );
469
			foreach( $new_deactive_modules as $module ) {
470
				/**
471
				 * Fired after a module has been deactivated.
472
				 *
473
				 * @since 4.2.0
474
				 *
475
				 * @param string $module Module slug.
476
				 * @param boolean $success whether the module was deactivated.
477
				 */
478
				do_action( 'jetpack_deactivate_module', $module, $success );
479
				/**
480
				 * Fires when a module is deactivated.
481
				 * The dynamic part of the filter, $module, is the module slug.
482
				 *
483
				 * @since 1.9.0
484
				 *
485
				 * @param string $module Module slug.
486
				 */
487
				do_action( "jetpack_deactivate_module_$module", $module );
488
			}
489
		}
490
491
		return $success;
492
	}
493
494
	static function delete_active_modules() {
495
		self::update_active_modules( array() );
496
	}
497
498
	/**
499
	 * Constructor.  Initializes WordPress hooks
500
	 */
501
	private function __construct() {
502
		/*
503
		 * Check for and alert any deprecated hooks
504
		 */
505
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
506
507
		/*
508
		 * Enable enhanced handling of previewing sites in Calypso
509
		 */
510
		if ( Jetpack::is_active() ) {
511
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
512
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
513
		}
514
515
		/*
516
		 * Load things that should only be in Network Admin.
517
		 *
518
		 * For now blow away everything else until a more full
519
		 * understanding of what is needed at the network level is
520
		 * available
521
		 */
522
		if( is_multisite() ) {
523
			Jetpack_Network::init();
524
		}
525
526
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
527
528
		// Unlink user before deleting the user from .com
529
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
530
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
531
532
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
533
			@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...
534
535
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
536
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
537
538
			$this->require_jetpack_authentication();
539
540
			if ( Jetpack::is_active() ) {
541
				// Hack to preserve $HTTP_RAW_POST_DATA
542
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
543
544
				$signed = $this->verify_xml_rpc_signature();
545 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
546
					// The actual API methods.
547
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
548
				} else {
549
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
550
					// active Jetpack connection, so that additional users can link their account.
551
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
552
				}
553 View Code Duplication
			} else {
554
				// The bootstrap API methods.
555
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
556
				$signed = $this->verify_xml_rpc_signature();
557
				if ( $signed && ! is_wp_error( $signed ) ) {
558
					// the jetpack Provision method is available for blog-token-signed requests
559
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
560
				}
561
			}
562
563
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
564
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
565
		} elseif (
566
			is_admin() &&
567
			isset( $_POST['action'] ) && (
568
				'jetpack_upload_file' == $_POST['action'] ||
569
				'jetpack_update_file' == $_POST['action']
570
			)
571
		) {
572
			$this->require_jetpack_authentication();
573
			$this->add_remote_request_handlers();
574
		} else {
575
			if ( Jetpack::is_active() ) {
576
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
577
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
578
			}
579
		}
580
581
		if ( Jetpack::is_active() ) {
582
			Jetpack_Heartbeat::init();
583
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
584
			Jetpack_Search_Performance_Logger::init();
585
		}
586
587
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
588
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
589
590
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
591
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
592
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
593
		}
594
595
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
596
597
		add_action( 'admin_init', array( $this, 'admin_init' ) );
598
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
599
600
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
601
602
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
603
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
604
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
605
606
		// returns HTTPS support status
607
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
608
609
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
610
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
611
612
		// JITM AJAX callback function
613
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
614
615
		// Universal ajax callback for all tracking events triggered via js
616
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
617
618
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
619
620
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
621
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
622
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
623
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
624
625
		// gutenberg locale
626
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_gutenberg_locale' ) );
627
628
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
629
630
		/**
631
		 * These actions run checks to load additional files.
632
		 * They check for external files or plugins, so they need to run as late as possible.
633
		 */
634
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
635
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
636
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
637
638
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
639
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
640
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
641
642
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
643
644
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
645
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
646
647
		// A filter to control all just in time messages
648
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
649
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
650
651
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
652
		// We should make sure to only do this for front end links.
653
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
654
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
655
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
656
657
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
658
			//so they point moderation links on emails to Calypso
659
			jetpack_require_lib( 'functions.wp-notify' );
660
		}
661
662
		// Update the Jetpack plan from API on heartbeats
663
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
664
665
		/**
666
		 * This is the hack to concatenate all css files into one.
667
		 * For description and reasoning see the implode_frontend_css method
668
		 *
669
		 * Super late priority so we catch all the registered styles
670
		 */
671
		if( !is_admin() ) {
672
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
673
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
674
		}
675
676
		/**
677
		 * These are sync actions that we need to keep track of for jitms
678
		 */
679
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
680
681
		// Actually push the stats on shutdown.
682
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
683
			add_action( 'shutdown', array( $this, 'push_stats' ) );
684
		}
685
	}
686
687
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
688
		$post = get_post( $post_id );
689
690
		if ( empty( $post ) ) {
691
			return $default_url;
692
		}
693
694
		$post_type = $post->post_type;
695
696
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
697
		// https://en.support.wordpress.com/custom-post-types/
698
		$allowed_post_types = array(
699
			'post' => 'post',
700
			'page' => 'page',
701
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
702
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
703
		);
704
705
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
706
			return $default_url;
707
		}
708
709
		$path_prefix = $allowed_post_types[ $post_type ];
710
711
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
0 ignored issues
show
Coding Style introduced by
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...
712
713
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
714
	}
715
716
	function point_edit_comment_links_to_calypso( $url ) {
717
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
718
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
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...
719
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
720
			Jetpack::build_raw_urls( get_home_url() ),
721
			$query_args['amp;c']
722
		) );
723
	}
724
725
	function jetpack_track_last_sync_callback( $params ) {
726
		/**
727
		 * Filter to turn off jitm caching
728
		 *
729
		 * @since 5.4.0
730
		 *
731
		 * @param bool false Whether to cache just in time messages
732
		 */
733
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
734
			return $params;
735
		}
736
737
		if ( is_array( $params ) && isset( $params[0] ) ) {
738
			$option = $params[0];
739
			if ( 'active_plugins' === $option ) {
740
				// use the cache if we can, but not terribly important if it gets evicted
741
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
742
			}
743
		}
744
745
		return $params;
746
	}
747
748
	function jetpack_connection_banner_callback() {
749
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
750
751
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
752
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
753
			wp_send_json_success();
754
		}
755
756
		wp_die();
757
	}
758
759
	function jetpack_admin_ajax_tracks_callback() {
760
		// Check for nonce
761
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
762
			wp_die( 'Permissions check failed.' );
763
		}
764
765
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
766
			wp_die( 'No valid event name or type.' );
767
		}
768
769
		$tracks_data = array();
770
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
771
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
772
				$tracks_data = $_REQUEST['tracksEventProp'];
773
			} else {
774
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
775
			}
776
		}
777
778
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
779
		wp_send_json_success();
780
		wp_die();
781
	}
782
783
	/**
784
	 * The callback for the JITM ajax requests.
785
	 */
786
	function jetpack_jitm_ajax_callback() {
787
		// Check for nonce
788
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
789
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
790
		}
791
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
792
			$module_slug = $_REQUEST['jitmModule'];
793
			Jetpack::log( 'activate', $module_slug );
794
			Jetpack::activate_module( $module_slug, false, false );
795
			Jetpack::state( 'message', 'no_message' );
796
797
			//A Jetpack module is being activated through a JITM, track it
798
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
799
			$this->do_stats( 'server_side' );
800
801
			wp_send_json_success();
802
		}
803
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
804
			// get the hide_jitm options array
805
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
806
			$module_slug = $_REQUEST['jitmModule'];
807
808
			if( ! $jetpack_hide_jitm ) {
809
				$jetpack_hide_jitm = array(
810
					$module_slug => 'hide'
811
				);
812
			} else {
813
				$jetpack_hide_jitm[$module_slug] = 'hide';
814
			}
815
816
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
817
818
			//jitm is being dismissed forever, track it
819
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
820
			$this->do_stats( 'server_side' );
821
822
			wp_send_json_success();
823
		}
824 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
825
			$module_slug = $_REQUEST['jitmModule'];
826
827
			// User went to WordPress.com, track this
828
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
829
			$this->do_stats( 'server_side' );
830
831
			wp_send_json_success();
832
		}
833 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
834
			$track = $_REQUEST['jitmModule'];
835
836
			// User is viewing JITM, track it.
837
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
838
			$this->do_stats( 'server_side' );
839
840
			wp_send_json_success();
841
		}
842
	}
843
844
	/**
845
	 * If there are any stats that need to be pushed, but haven't been, push them now.
846
	 */
847
	function push_stats() {
848
		if ( ! empty( $this->stats ) ) {
849
			$this->do_stats( 'server_side' );
850
		}
851
	}
852
853
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
854
		switch( $cap ) {
855
			case 'jetpack_connect' :
856
			case 'jetpack_reconnect' :
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
857
				if ( Jetpack::is_development_mode() ) {
858
					$caps = array( 'do_not_allow' );
859
					break;
860
				}
861
				/**
862
				 * Pass through. If it's not development mode, these should match disconnect.
863
				 * Let users disconnect if it's development mode, just in case things glitch.
864
				 */
865
			case 'jetpack_disconnect' :
866
				/**
867
				 * In multisite, can individual site admins manage their own connection?
868
				 *
869
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
870
				 */
871
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
872
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
873
						/**
874
						 * We need to update the option name -- it's terribly unclear which
875
						 * direction the override goes.
876
						 *
877
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
878
						 */
879
						$caps = array( 'do_not_allow' );
880
						break;
881
					}
882
				}
883
884
				$caps = array( 'manage_options' );
885
				break;
886
			case 'jetpack_manage_modules' :
887
			case 'jetpack_activate_modules' :
888
			case 'jetpack_deactivate_modules' :
889
				$caps = array( 'manage_options' );
890
				break;
891
			case 'jetpack_configure_modules' :
892
				$caps = array( 'manage_options' );
893
				break;
894
			case 'jetpack_network_admin_page':
895
			case 'jetpack_network_settings_page':
896
				$caps = array( 'manage_network_plugins' );
897
				break;
898
			case 'jetpack_network_sites_page':
899
				$caps = array( 'manage_sites' );
900
				break;
901
			case 'jetpack_admin_page' :
902
				if ( Jetpack::is_development_mode() ) {
903
					$caps = array( 'manage_options' );
904
					break;
905
				} else {
906
					$caps = array( 'read' );
907
				}
908
				break;
909
			case 'jetpack_connect_user' :
910
				if ( Jetpack::is_development_mode() ) {
911
					$caps = array( 'do_not_allow' );
912
					break;
913
				}
914
				$caps = array( 'read' );
915
				break;
916
		}
917
		return $caps;
918
	}
919
920
	function require_jetpack_authentication() {
921
		// Don't let anyone authenticate
922
		$_COOKIE = array();
923
		remove_all_filters( 'authenticate' );
924
		remove_all_actions( 'wp_login_failed' );
925
926
		if ( Jetpack::is_active() ) {
927
			// Allow Jetpack authentication
928
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
929
		}
930
	}
931
932
	/**
933
	 * Load language files
934
	 * @action plugins_loaded
935
	 */
936
	public static function plugin_textdomain() {
937
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
938
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
939
	}
940
941
	/**
942
	 * Register assets for use in various modules and the Jetpack admin page.
943
	 *
944
	 * @uses wp_script_is, wp_register_script, plugins_url
945
	 * @action wp_loaded
946
	 * @return null
947
	 */
948
	public function register_assets() {
949
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
950
			wp_register_script(
951
				'spin',
952
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
953
				false,
954
				'1.3'
955
			);
956
		}
957
958
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
959
			wp_register_script(
960
				'jquery.spin',
961
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
962
				array( 'jquery', 'spin' ),
963
				'1.3'
964
			);
965
		}
966
967 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
968
			wp_register_script(
969
				'jetpack-gallery-settings',
970
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
971
				array( 'media-views' ),
972
				'20121225'
973
			);
974
		}
975
976
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
977
			wp_register_script(
978
				'jetpack-twitter-timeline',
979
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
980
				array( 'jquery' ),
981
				'4.0.0',
982
				true
983
			);
984
		}
985
986
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
987
			wp_register_script(
988
				'jetpack-facebook-embed',
989
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
990
				array( 'jquery' ),
991
				null,
992
				true
993
			);
994
995
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
996
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
997
			if ( ! is_numeric( $fb_app_id ) ) {
998
				$fb_app_id = '';
999
			}
1000
			wp_localize_script(
1001
				'jetpack-facebook-embed',
1002
				'jpfbembed',
1003
				array(
1004
					'appid' => $fb_app_id,
1005
					'locale' => $this->get_locale(),
1006
				)
1007
			);
1008
		}
1009
1010
		/**
1011
		 * As jetpack_register_genericons is by default fired off a hook,
1012
		 * the hook may have already fired by this point.
1013
		 * So, let's just trigger it manually.
1014
		 */
1015
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1016
		jetpack_register_genericons();
1017
1018
		/**
1019
		 * Register the social logos
1020
		 */
1021
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1022
		jetpack_register_social_logos();
1023
1024 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1025
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1026
	}
1027
1028
	/**
1029
	 * Device Pixels support
1030
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1031
	 */
1032
	function devicepx() {
1033
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1034
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1035
		}
1036
	}
1037
1038
	/**
1039
	 * If a user has been promoted to or demoted from admin, we need to clear the
1040
	 * jetpack_other_linked_admins transient.
1041
	 *
1042
	 * @since 4.3.2
1043
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1044
	 *
1045
	 * @param int    $user_id   The user ID whose role changed.
1046
	 * @param string $role      The new role.
1047
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

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

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

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

Loading history...
1048
	 */
1049
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1050
		if ( 'administrator' == $role
1051
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1052
			|| is_null( $old_roles )
1053
		) {
1054
			delete_transient( 'jetpack_other_linked_admins' );
1055
		}
1056
	}
1057
1058
	/**
1059
	 * Checks to see if there are any other users available to become primary
1060
	 * Users must both:
1061
	 * - Be linked to wpcom
1062
	 * - Be an admin
1063
	 *
1064
	 * @return mixed False if no other users are linked, Int if there are.
1065
	 */
1066
	static function get_other_linked_admins() {
1067
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1068
1069
		if ( false === $other_linked_users ) {
1070
			$admins = get_users( array( 'role' => 'administrator' ) );
1071
			if ( count( $admins ) > 1 ) {
1072
				$available = array();
1073
				foreach ( $admins as $admin ) {
1074
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1075
						$available[] = $admin->ID;
1076
					}
1077
				}
1078
1079
				$count_connected_admins = count( $available );
1080
				if ( count( $available ) > 1 ) {
1081
					$other_linked_users = $count_connected_admins;
1082
				} else {
1083
					$other_linked_users = 0;
1084
				}
1085
			} else {
1086
				$other_linked_users = 0;
1087
			}
1088
1089
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1090
		}
1091
1092
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1093
	}
1094
1095
	/**
1096
	 * Return whether we are dealing with a multi network setup or not.
1097
	 * The reason we are type casting this is because we want to avoid the situation where
1098
	 * the result is false since when is_main_network_option return false it cases
1099
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1100
	 * database which could be set to anything as opposed to what this function returns.
1101
	 * @param  bool  $option
1102
	 *
1103
	 * @return boolean
1104
	 */
1105
	public function is_main_network_option( $option ) {
1106
		// return '1' or ''
1107
		return (string) (bool) Jetpack::is_multi_network();
1108
	}
1109
1110
	/**
1111
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1112
	 * @return null
1113
	 */
1114
	function update_jetpack_main_network_site_option() {
1115
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1116
	}
1117
	/**
1118
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1119
	 *
1120
	 */
1121
	function update_jetpack_network_settings() {
1122
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1123
		// Only sync this info for the main network site.
1124
	}
1125
1126
	/**
1127
	 * jetpack_updates is saved in the following schema:
1128
	 *
1129
	 * array (
1130
	 *      'plugins'                       => (int) Number of plugin updates available.
1131
	 *      'themes'                        => (int) Number of theme updates available.
1132
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1133
	 *      'translations'                  => (int) Number of translation updates available.
1134
	 *      'total'                         => (int) Total of all available updates.
1135
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1136
	 * )
1137
	 * @return array
1138
	 */
1139
	public static function get_updates() {
1140
		$update_data = wp_get_update_data();
1141
1142
		// Stores the individual update counts as well as the total count.
1143
		if ( isset( $update_data['counts'] ) ) {
1144
			$updates = $update_data['counts'];
1145
		}
1146
1147
		// If we need to update WordPress core, let's find the latest version number.
1148 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1149
			$cur = get_preferred_from_update_core();
1150
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1151
				$updates['wp_update_version'] = $cur->current;
1152
			}
1153
		}
1154
		return isset( $updates ) ? $updates : array();
1155
	}
1156
1157
	public static function get_update_details() {
1158
		$update_details = array(
1159
			'update_core' => get_site_transient( 'update_core' ),
1160
			'update_plugins' => get_site_transient( 'update_plugins' ),
1161
			'update_themes' => get_site_transient( 'update_themes' ),
1162
		);
1163
		return $update_details;
1164
	}
1165
1166
	public static function refresh_update_data() {
1167
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1168
1169
	}
1170
1171
	public static function refresh_theme_data() {
1172
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1173
	}
1174
1175
	/**
1176
	 * Is Jetpack active?
1177
	 */
1178
	public static function is_active() {
1179
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1180
	}
1181
1182
	/**
1183
	 * Make an API call to WordPress.com for plan status
1184
	 *
1185
	 * @uses Jetpack_Options::get_option()
1186
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1187
	 * @uses update_option()
1188
	 *
1189
	 * @access public
1190
	 * @static
1191
	 *
1192
	 * @return bool True if plan is updated, false if no update
1193
	 */
1194
	public static function refresh_active_plan_from_wpcom() {
1195
		// Make the API request
1196
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1197
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1198
1199
		// Bail if there was an error or malformed response
1200
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1201
			return false;
1202
		}
1203
1204
		// Decode the results
1205
		$results = json_decode( $response['body'], true );
1206
1207
		// Bail if there were no results or plan details returned
1208
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1209
			return false;
1210
		}
1211
1212
		// Store the option and return true if updated
1213
		return update_option( 'jetpack_active_plan', $results['plan'] );
1214
	}
1215
1216
	/**
1217
	* Get Jetpack development mode notice text and notice class.
1218
	*
1219
	* Mirrors the checks made in Jetpack::is_development_mode
1220
	*
1221
	*/
1222
	public static function show_development_mode_notice() {
1223
		if ( Jetpack::is_development_mode() ) {
1224
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1225
				$notice = sprintf(
1226
					/* translators: %s is a URL */
1227
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1228
					'https://jetpack.com/support/development-mode/'
1229
				);
1230
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1231
				$notice = sprintf(
1232
					/* translators: %s is a URL */
1233
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1234
					'https://jetpack.com/support/development-mode/'
1235
				);
1236
			} else {
1237
				$notice = sprintf(
1238
					/* translators: %s is a URL */
1239
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1240
					'https://jetpack.com/support/development-mode/'
1241
				);
1242
			}
1243
1244
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1245
		}
1246
1247
		// Throw up a notice if using a development version and as for feedback.
1248
		if ( Jetpack::is_development_version() ) {
1249
			/* translators: %s is a URL */
1250
			$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/' );
1251
1252
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1253
		}
1254
		// Throw up a notice if using staging mode
1255
		if ( Jetpack::is_staging_site() ) {
1256
			/* translators: %s is a URL */
1257
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1258
1259
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1260
		}
1261
	}
1262
1263
	/**
1264
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1265
	 */
1266
	function extra_oembed_providers() {
1267
		// Cloudup: https://dev.cloudup.com/#oembed
1268
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1269
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1270
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1271
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1272
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1273
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1274
	}
1275
1276
	/**
1277
	 * Synchronize connected user role changes
1278
	 */
1279
	function user_role_change( $user_id ) {
1280
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1281
		Jetpack_Sync_Users::user_role_change( $user_id );
1282
	}
1283
1284
	/**
1285
	 * Loads the currently active modules.
1286
	 */
1287
	public static function load_modules() {
1288
		if (
1289
			! self::is_active()
1290
			&& ! self::is_development_mode()
1291
			&& ! self::is_onboarding()
1292
			&& (
1293
				! is_multisite()
1294
				|| ! get_site_option( 'jetpack_protect_active' )
1295
			)
1296
		) {
1297
			return;
1298
		}
1299
1300
		$version = Jetpack_Options::get_option( 'version' );
1301 View Code Duplication
		if ( ! $version ) {
1302
			$version = $old_version = JETPACK__VERSION . ':' . time();
1303
			/** This action is documented in class.jetpack.php */
1304
			do_action( 'updating_jetpack_version', $version, false );
1305
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1306
		}
1307
		list( $version ) = explode( ':', $version );
1308
1309
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1310
1311
		$modules_data = array();
1312
1313
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1314
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1315
			$updated_modules = array();
1316
			foreach ( $modules as $module ) {
1317
				$modules_data[ $module ] = Jetpack::get_module( $module );
1318
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1319
					continue;
1320
				}
1321
1322
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1323
					continue;
1324
				}
1325
1326
				$updated_modules[] = $module;
1327
			}
1328
1329
			$modules = array_diff( $modules, $updated_modules );
1330
		}
1331
1332
		$is_development_mode = Jetpack::is_development_mode();
1333
1334
		foreach ( $modules as $index => $module ) {
1335
			// If we're in dev mode, disable modules requiring a connection
1336
			if ( $is_development_mode ) {
1337
				// Prime the pump if we need to
1338
				if ( empty( $modules_data[ $module ] ) ) {
1339
					$modules_data[ $module ] = Jetpack::get_module( $module );
1340
				}
1341
				// If the module requires a connection, but we're in local mode, don't include it.
1342
				if ( $modules_data[ $module ]['requires_connection'] ) {
1343
					continue;
1344
				}
1345
			}
1346
1347
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1348
				continue;
1349
			}
1350
1351
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1352
				unset( $modules[ $index ] );
1353
				self::update_active_modules( array_values( $modules ) );
1354
				continue;
1355
			}
1356
1357
			/**
1358
			 * Fires when a specific module is loaded.
1359
			 * The dynamic part of the hook, $module, is the module slug.
1360
			 *
1361
			 * @since 1.1.0
1362
			 */
1363
			do_action( 'jetpack_module_loaded_' . $module );
1364
		}
1365
1366
		/**
1367
		 * Fires when all the modules are loaded.
1368
		 *
1369
		 * @since 1.1.0
1370
		 */
1371
		do_action( 'jetpack_modules_loaded' );
1372
1373
		// 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.
1374
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1375
	}
1376
1377
	/**
1378
	 * Check if Jetpack's REST API compat file should be included
1379
	 * @action plugins_loaded
1380
	 * @return null
1381
	 */
1382
	public function check_rest_api_compat() {
1383
		/**
1384
		 * Filters the list of REST API compat files to be included.
1385
		 *
1386
		 * @since 2.2.5
1387
		 *
1388
		 * @param array $args Array of REST API compat files to include.
1389
		 */
1390
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1391
1392
		if ( function_exists( 'bbpress' ) )
1393
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1394
1395
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1396
			require_once $_jetpack_rest_api_compat_include;
1397
	}
1398
1399
	/**
1400
	 * Check if Jetpack's Open Graph tags should be used.
1401
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1402
	 *
1403
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1404
	 * @action plugins_loaded
1405
	 * @return null
1406
	 */
1407
	public function check_open_graph() {
1408
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1409
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1410
		}
1411
1412
		$active_plugins = self::get_active_plugins();
1413
1414
		if ( ! empty( $active_plugins ) ) {
1415
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1416
				if ( in_array( $plugin, $active_plugins ) ) {
1417
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1418
					break;
1419
				}
1420
			}
1421
		}
1422
1423
		/**
1424
		 * Allow the addition of Open Graph Meta Tags to all pages.
1425
		 *
1426
		 * @since 2.0.3
1427
		 *
1428
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1429
		 */
1430
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1431
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1432
		}
1433
	}
1434
1435
	/**
1436
	 * Check if Jetpack's Twitter tags should be used.
1437
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1438
	 *
1439
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1440
	 * @action plugins_loaded
1441
	 * @return null
1442
	 */
1443
	public function check_twitter_tags() {
1444
1445
		$active_plugins = self::get_active_plugins();
1446
1447
		if ( ! empty( $active_plugins ) ) {
1448
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1449
				if ( in_array( $plugin, $active_plugins ) ) {
1450
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1451
					break;
1452
				}
1453
			}
1454
		}
1455
1456
		/**
1457
		 * Allow Twitter Card Meta tags to be disabled.
1458
		 *
1459
		 * @since 2.6.0
1460
		 *
1461
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1462
		 */
1463
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1464
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1465
		}
1466
	}
1467
1468
	/**
1469
	 * Allows plugins to submit security reports.
1470
 	 *
1471
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1472
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1473
	 * @param array   $args         See definitions above
1474
	 */
1475
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1476
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1477
	}
1478
1479
/* Jetpack Options API */
1480
1481
	public static function get_option_names( $type = 'compact' ) {
1482
		return Jetpack_Options::get_option_names( $type );
1483
	}
1484
1485
	/**
1486
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1487
 	 *
1488
	 * @param string $name    Option name
1489
	 * @param mixed  $default (optional)
1490
	 */
1491
	public static function get_option( $name, $default = false ) {
1492
		return Jetpack_Options::get_option( $name, $default );
1493
	}
1494
1495
	/**
1496
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1497
 	 *
1498
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1499
	 * @param string $name  Option name
1500
	 * @param mixed  $value Option value
1501
	 */
1502
	public static function update_option( $name, $value ) {
1503
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1504
		return Jetpack_Options::update_option( $name, $value );
1505
	}
1506
1507
	/**
1508
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1509
 	 *
1510
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1511
	 * @param array $array array( option name => option value, ... )
1512
	 */
1513
	public static function update_options( $array ) {
1514
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1515
		return Jetpack_Options::update_options( $array );
1516
	}
1517
1518
	/**
1519
	 * Deletes the given option.  May be passed multiple option names as an array.
1520
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1521
	 *
1522
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1523
	 * @param string|array $names
1524
	 */
1525
	public static function delete_option( $names ) {
1526
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1527
		return Jetpack_Options::delete_option( $names );
1528
	}
1529
1530
	/**
1531
	 * Enters a user token into the user_tokens option
1532
	 *
1533
	 * @param int $user_id
1534
	 * @param string $token
1535
	 * return bool
1536
	 */
1537
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1538
		// not designed for concurrent updates
1539
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1540
		if ( ! is_array( $user_tokens ) )
1541
			$user_tokens = array();
1542
		$user_tokens[$user_id] = $token;
1543
		if ( $is_master_user ) {
1544
			$master_user = $user_id;
1545
			$options     = compact( 'user_tokens', 'master_user' );
1546
		} else {
1547
			$options = compact( 'user_tokens' );
1548
		}
1549
		return Jetpack_Options::update_options( $options );
1550
	}
1551
1552
	public static function activate_new_modules( $redirect = false ) {
1553
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1554
			return;
1555
		}
1556
1557
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1558 View Code Duplication
		if ( ! $jetpack_old_version ) {
1559
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1560
			/** This action is documented in class.jetpack.php */
1561
			do_action( 'updating_jetpack_version', $version, false );
1562
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1563
		}
1564
1565
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1566
1567
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1568
			return;
1569
		}
1570
1571
		$active_modules     = Jetpack::get_active_modules();
1572
		$reactivate_modules = array();
1573
		foreach ( $active_modules as $active_module ) {
1574
			$module = Jetpack::get_module( $active_module );
1575
			if ( ! isset( $module['changed'] ) ) {
1576
				continue;
1577
			}
1578
1579
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1580
				continue;
1581
			}
1582
1583
			$reactivate_modules[] = $active_module;
1584
			Jetpack::deactivate_module( $active_module );
1585
		}
1586
1587
		$new_version = JETPACK__VERSION . ':' . time();
1588
		/** This action is documented in class.jetpack.php */
1589
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1590
		Jetpack_Options::update_options(
1591
			array(
1592
				'version'     => $new_version,
1593
				'old_version' => $jetpack_old_version,
1594
			)
1595
		);
1596
1597
		Jetpack::state( 'message', 'modules_activated' );
1598
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1599
1600
		if ( $redirect ) {
1601
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1602
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1603
				$page = $_GET['page'];
1604
			}
1605
1606
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1607
			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...
1608
		}
1609
	}
1610
1611
	/**
1612
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1613
	 * Make sure to tuck away module "library" files in a sub-directory.
1614
	 */
1615
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1616
		static $modules = null;
1617
1618
		if ( ! isset( $modules ) ) {
1619
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1620
			// Use the cache if we're on the front-end and it's available...
1621
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1622
				$modules = $available_modules_option[ JETPACK__VERSION ];
1623
			} else {
1624
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1625
1626
				$modules = array();
1627
1628
				foreach ( $files as $file ) {
1629
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1630
						continue;
1631
					}
1632
1633
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1634
				}
1635
1636
				Jetpack_Options::update_option( 'available_modules', array(
1637
					JETPACK__VERSION => $modules,
1638
				) );
1639
			}
1640
		}
1641
1642
		/**
1643
		 * Filters the array of modules available to be activated.
1644
		 *
1645
		 * @since 2.4.0
1646
		 *
1647
		 * @param array $modules Array of available modules.
1648
		 * @param string $min_version Minimum version number required to use modules.
1649
		 * @param string $max_version Maximum version number required to use modules.
1650
		 */
1651
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1652
1653
		if ( ! $min_version && ! $max_version ) {
1654
			return array_keys( $mods );
1655
		}
1656
1657
		$r = array();
1658
		foreach ( $mods as $slug => $introduced ) {
1659
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1660
				continue;
1661
			}
1662
1663
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1664
				continue;
1665
			}
1666
1667
			$r[] = $slug;
1668
		}
1669
1670
		return $r;
1671
	}
1672
1673
	/**
1674
	 * Default modules loaded on activation.
1675
	 */
1676
	public static function get_default_modules( $min_version = false, $max_version = false ) {
1677
		$return = array();
1678
1679
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1680
			$module_data = Jetpack::get_module( $module );
1681
1682
			switch ( strtolower( $module_data['auto_activate'] ) ) {
1683
				case 'yes' :
1684
					$return[] = $module;
1685
					break;
1686
				case 'public' :
1687
					if ( Jetpack_Options::get_option( 'public' ) ) {
1688
						$return[] = $module;
1689
					}
1690
					break;
1691
				case 'no' :
1692
				default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

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

Loading history...
1693
					break;
1694
			}
1695
		}
1696
		/**
1697
		 * Filters the array of default modules.
1698
		 *
1699
		 * @since 2.5.0
1700
		 *
1701
		 * @param array $return Array of default modules.
1702
		 * @param string $min_version Minimum version number required to use modules.
1703
		 * @param string $max_version Maximum version number required to use modules.
1704
		 */
1705
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1706
	}
1707
1708
	/**
1709
	 * Checks activated modules during auto-activation to determine
1710
	 * if any of those modules are being deprecated.  If so, close
1711
	 * them out, and add any replacement modules.
1712
	 *
1713
	 * Runs at priority 99 by default.
1714
	 *
1715
	 * This is run late, so that it can still activate a module if
1716
	 * the new module is a replacement for another that the user
1717
	 * currently has active, even if something at the normal priority
1718
	 * would kibosh everything.
1719
	 *
1720
	 * @since 2.6
1721
	 * @uses jetpack_get_default_modules filter
1722
	 * @param array $modules
1723
	 * @return array
1724
	 */
1725
	function handle_deprecated_modules( $modules ) {
1726
		$deprecated_modules = array(
1727
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
1728
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1729
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
1730
		);
1731
1732
		// Don't activate SSO if they never completed activating WPCC.
1733
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
1734
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1735
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1736
				$deprecated_modules['wpcc'] = null;
1737
			}
1738
		}
1739
1740
		foreach ( $deprecated_modules as $module => $replacement ) {
1741
			if ( Jetpack::is_module_active( $module ) ) {
1742
				self::deactivate_module( $module );
1743
				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...
1744
					$modules[] = $replacement;
1745
				}
1746
			}
1747
		}
1748
1749
		return array_unique( $modules );
1750
	}
1751
1752
	/**
1753
	 * Checks activated plugins during auto-activation to determine
1754
	 * if any of those plugins are in the list with a corresponding module
1755
	 * that is not compatible with the plugin. The module will not be allowed
1756
	 * to auto-activate.
1757
	 *
1758
	 * @since 2.6
1759
	 * @uses jetpack_get_default_modules filter
1760
	 * @param array $modules
1761
	 * @return array
1762
	 */
1763
	function filter_default_modules( $modules ) {
1764
1765
		$active_plugins = self::get_active_plugins();
1766
1767
		if ( ! empty( $active_plugins ) ) {
1768
1769
			// For each module we'd like to auto-activate...
1770
			foreach ( $modules as $key => $module ) {
1771
				// If there are potential conflicts for it...
1772
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1773
					// For each potential conflict...
1774
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1775
						// If that conflicting plugin is active...
1776
						if ( in_array( $plugin, $active_plugins ) ) {
1777
							// Remove that item from being auto-activated.
1778
							unset( $modules[ $key ] );
1779
						}
1780
					}
1781
				}
1782
			}
1783
		}
1784
1785
		return $modules;
1786
	}
1787
1788
	/**
1789
	 * Return translated module tag.
1790
	 *
1791
	 * @param string $tag Tag as it appears in each module heading.
1792
	 *
1793
	 * @return mixed
1794
	 */
1795
	public static function translate_module_tag( $tag ) {
1796
		return jetpack_get_module_i18n_tag( $tag );
1797
	}
1798
1799
	/**
1800
	 * Get i18n strings as a JSON-encoded string
1801
	 *
1802
	 * @return string The locale as JSON
1803
	 */
1804
	public static function get_i18n_data_json() {
1805
		$i18n_json = JETPACK__PLUGIN_DIR . 'languages/json/jetpack-' . jetpack_get_user_locale() . '.json';
1806
1807
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
1808
			$locale_data = @file_get_contents( $i18n_json );
1809
			if ( $locale_data ) {
1810
				return $locale_data;
1811
			}
1812
		}
1813
1814
		// Return valid empty Jed locale
1815
		return json_encode( array(
1816
			'' => array(
1817
				'domain' => 'jetpack',
1818
				'lang'   => is_admin() ? get_user_locale() : get_locale(),
1819
			),
1820
		) );
1821
	}
1822
1823
	/**
1824
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
1825
	 *
1826
	 * @since 3.9.2
1827
	 *
1828
	 * @param array $modules
1829
	 *
1830
	 * @return string|void
1831
	 */
1832
	public static function get_translated_modules( $modules ) {
1833
		foreach ( $modules as $index => $module ) {
1834
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
1835
			if ( isset( $module['name'] ) ) {
1836
				$modules[ $index ]['name'] = $i18n_module['name'];
1837
			}
1838
			if ( isset( $module['description'] ) ) {
1839
				$modules[ $index ]['description'] = $i18n_module['description'];
1840
				$modules[ $index ]['short_description'] = $i18n_module['description'];
1841
			}
1842
		}
1843
		return $modules;
1844
	}
1845
1846
	/**
1847
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
1848
	 *
1849
	 * @param bool $catch True to start catching, False to stop.
1850
	 *
1851
	 * @static
1852
	 */
1853
	public static function catch_errors( $catch ) {
1854
		static $display_errors, $error_reporting;
1855
1856
		if ( $catch ) {
1857
			$display_errors  = @ini_set( 'display_errors', 1 );
1858
			$error_reporting = @error_reporting( E_ALL );
1859
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
1860
		} else {
1861
			@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...
1862
			@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...
1863
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
1864
		}
1865
	}
1866
1867
	/**
1868
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
1869
	 */
1870
	public static function catch_errors_on_shutdown() {
1871
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
1872
	}
1873
1874
	/**
1875
	 * Rewrite any string to make paths easier to read.
1876
	 *
1877
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
1878
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
1879
	 *
1880
	 * @param $string
1881
	 * @return mixed
1882
	 */
1883
	public static function alias_directories( $string ) {
1884
		// ABSPATH has a trailing slash.
1885
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
1886
		// WP_CONTENT_DIR does not have a trailing slash.
1887
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
1888
1889
		return $string;
1890
	}
1891
1892
	public static function activate_default_modules(
1893
		$min_version = false,
1894
		$max_version = false,
1895
		$other_modules = array(),
1896
		$redirect = true,
1897
		$send_state_messages = true
1898
	) {
1899
		$jetpack = Jetpack::init();
1900
1901
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
1902
		$modules = array_merge( $other_modules, $modules );
1903
1904
		// Look for standalone plugins and disable if active.
1905
1906
		$to_deactivate = array();
1907
		foreach ( $modules as $module ) {
1908
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
1909
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
1910
			}
1911
		}
1912
1913
		$deactivated = array();
1914
		foreach ( $to_deactivate as $module => $deactivate_me ) {
1915
			list( $probable_file, $probable_title ) = $deactivate_me;
1916
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
1917
				$deactivated[] = $module;
1918
			}
1919
		}
1920
1921
		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...
1922
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
1923
1924
			$url = add_query_arg(
1925
				array(
1926
					'action'   => 'activate_default_modules',
1927
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
1928
				),
1929
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
1930
			);
1931
			wp_safe_redirect( $url );
1932
			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...
1933
		}
1934
1935
		/**
1936
		 * Fires before default modules are activated.
1937
		 *
1938
		 * @since 1.9.0
1939
		 *
1940
		 * @param string $min_version Minimum version number required to use modules.
1941
		 * @param string $max_version Maximum version number required to use modules.
1942
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
1943
		 */
1944
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
1945
1946
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
1947
		Jetpack::restate();
1948
		Jetpack::catch_errors( true );
1949
1950
		$active = Jetpack::get_active_modules();
1951
1952
		foreach ( $modules as $module ) {
1953
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
1954
				$active[] = $module;
1955
				self::update_active_modules( $active );
1956
				continue;
1957
			}
1958
1959
			if ( $send_state_messages && in_array( $module, $active ) ) {
1960
				$module_info = Jetpack::get_module( $module );
1961 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
1962
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
1963
					if ( $active_state = Jetpack::state( $state ) ) {
1964
						$active_state = explode( ',', $active_state );
1965
					} else {
1966
						$active_state = array();
1967
					}
1968
					$active_state[] = $module;
1969
					Jetpack::state( $state, implode( ',', $active_state ) );
1970
				}
1971
				continue;
1972
			}
1973
1974
			$file = Jetpack::get_module_path( $module );
1975
			if ( ! file_exists( $file ) ) {
1976
				continue;
1977
			}
1978
1979
			// we'll override this later if the plugin can be included without fatal error
1980
			if ( $redirect ) {
1981
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
1982
			}
1983
1984
			if ( $send_state_messages ) {
1985
				Jetpack::state( 'error', 'module_activation_failed' );
1986
				Jetpack::state( 'module', $module );
1987
			}
1988
1989
			ob_start();
1990
			require_once $file;
1991
1992
			$active[] = $module;
1993
1994 View Code Duplication
			if ( $send_state_messages ) {
1995
1996
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces

This check looks for improperly formatted assignments.

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

To illustrate:

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

will have no issues, while

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

will report issues in lines 1 and 2.

Loading history...
1997
				if ( $active_state = Jetpack::state( $state ) ) {
1998
					$active_state = explode( ',', $active_state );
1999
				} else {
2000
					$active_state = array();
2001
				}
2002
				$active_state[] = $module;
2003
				Jetpack::state( $state, implode( ',', $active_state ) );
2004
			}
2005
2006
			Jetpack::update_active_modules( $active );
2007
2008
			ob_end_clean();
2009
		}
2010
2011
		if ( $send_state_messages ) {
2012
			Jetpack::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2013
			Jetpack::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2014
		}
2015
2016
		Jetpack::catch_errors( false );
2017
		/**
2018
		 * Fires when default modules are activated.
2019
		 *
2020
		 * @since 1.9.0
2021
		 *
2022
		 * @param string $min_version Minimum version number required to use modules.
2023
		 * @param string $max_version Maximum version number required to use modules.
2024
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2025
		 */
2026
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2027
	}
2028
2029
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2030
		/**
2031
		 * Fires before a module is activated.
2032
		 *
2033
		 * @since 2.6.0
2034
		 *
2035
		 * @param string $module Module slug.
2036
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2037
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2038
		 */
2039
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2040
2041
		$jetpack = Jetpack::init();
2042
2043
		if ( ! strlen( $module ) )
2044
			return false;
2045
2046
		if ( ! Jetpack::is_module( $module ) )
2047
			return false;
2048
2049
		// If it's already active, then don't do it again
2050
		$active = Jetpack::get_active_modules();
2051
		foreach ( $active as $act ) {
2052
			if ( $act == $module )
2053
				return true;
2054
		}
2055
2056
		$module_data = Jetpack::get_module( $module );
2057
2058
		if ( ! Jetpack::is_active() ) {
2059
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2060
				return false;
2061
2062
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2063
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2064
				return false;
2065
		}
2066
2067
		// Check and see if the old plugin is active
2068
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2069
			// Deactivate the old plugin
2070
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2071
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2072
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2073
				Jetpack::state( 'deactivated_plugins', $module );
2074
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2075
				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...
2076
			}
2077
		}
2078
2079
		// Protect won't work with mis-configured IPs
2080
		if ( 'protect' === $module ) {
2081
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2082
			if ( ! jetpack_protect_get_ip() ) {
2083
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2084
				return false;
2085
			}
2086
		}
2087
2088
		if ( ! Jetpack::active_plan_supports( $module ) ) {
2089
			return false;
2090
		}
2091
2092
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2093
		Jetpack::state( 'module', $module );
2094
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2095
2096
		Jetpack::catch_errors( true );
2097
		ob_start();
2098
		require Jetpack::get_module_path( $module );
2099
		/** This action is documented in class.jetpack.php */
2100
		do_action( 'jetpack_activate_module', $module );
2101
		$active[] = $module;
2102
		Jetpack::update_active_modules( $active );
2103
2104
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2105
		ob_end_clean();
2106
		Jetpack::catch_errors( false );
2107
2108
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2109 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2110
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2111
2112
			//Jump start is being dismissed send data to MC Stats
2113
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2114
2115
			$jetpack->do_stats( 'server_side' );
2116
		}
2117
2118
		if ( $redirect ) {
2119
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2120
		}
2121
		if ( $exit ) {
2122
			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...
2123
		}
2124
		return true;
2125
	}
2126
2127
	function activate_module_actions( $module ) {
2128
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2129
	}
2130
2131
	public static function deactivate_module( $module ) {
2132
		/**
2133
		 * Fires when a module is deactivated.
2134
		 *
2135
		 * @since 1.9.0
2136
		 *
2137
		 * @param string $module Module slug.
2138
		 */
2139
		do_action( 'jetpack_pre_deactivate_module', $module );
2140
2141
		$jetpack = Jetpack::init();
2142
2143
		$active = Jetpack::get_active_modules();
2144
		$new    = array_filter( array_diff( $active, (array) $module ) );
2145
2146
		// A flag for Jump Start so it's not shown again.
2147 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2148
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2149
2150
			//Jump start is being dismissed send data to MC Stats
2151
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2152
2153
			$jetpack->do_stats( 'server_side' );
2154
		}
2155
2156
		return self::update_active_modules( $new );
2157
	}
2158
2159
	public static function enable_module_configurable( $module ) {
2160
		$module = Jetpack::get_module_slug( $module );
2161
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2162
	}
2163
2164
	public static function module_configuration_url( $module ) {
2165
		$module = Jetpack::get_module_slug( $module );
2166
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2167
	}
2168
2169
	public static function module_configuration_load( $module, $method ) {
2170
		$module = Jetpack::get_module_slug( $module );
2171
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2172
	}
2173
2174
	public static function module_configuration_head( $module, $method ) {
2175
		$module = Jetpack::get_module_slug( $module );
2176
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2177
	}
2178
2179
	public static function module_configuration_screen( $module, $method ) {
2180
		$module = Jetpack::get_module_slug( $module );
2181
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2182
	}
2183
2184
	public static function module_configuration_activation_screen( $module, $method ) {
2185
		$module = Jetpack::get_module_slug( $module );
2186
		add_action( 'display_activate_module_setting_' . $module, $method );
2187
	}
2188
2189
/* Installation */
2190
2191
	public static function bail_on_activation( $message, $deactivate = true ) {
2192
?>
2193
<!doctype html>
2194
<html>
2195
<head>
2196
<meta charset="<?php bloginfo( 'charset' ); ?>">
2197
<style>
2198
* {
2199
	text-align: center;
2200
	margin: 0;
2201
	padding: 0;
2202
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2203
}
2204
p {
2205
	margin-top: 1em;
2206
	font-size: 18px;
2207
}
2208
</style>
2209
<body>
2210
<p><?php echo esc_html( $message ); ?></p>
2211
</body>
2212
</html>
2213
<?php
2214
		if ( $deactivate ) {
2215
			$plugins = get_option( 'active_plugins' );
2216
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2217
			$update  = false;
2218
			foreach ( $plugins as $i => $plugin ) {
2219
				if ( $plugin === $jetpack ) {
2220
					$plugins[$i] = false;
2221
					$update = true;
2222
				}
2223
			}
2224
2225
			if ( $update ) {
2226
				update_option( 'active_plugins', array_filter( $plugins ) );
2227
			}
2228
		}
2229
		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...
2230
	}
2231
2232
	/**
2233
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2234
	 * @static
2235
	 */
2236
	public static function plugin_activation( $network_wide ) {
2237
		Jetpack_Options::update_option( 'activated', 1 );
2238
2239
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2240
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2241
		}
2242
2243
		if ( $network_wide )
2244
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2245
2246
		// For firing one-off events (notices) immediately after activation
2247
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2248
2249
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2250
2251
		Jetpack::plugin_initialize();
2252
	}
2253
2254
	public static function get_activation_source( $referer_url ) {
2255
2256
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
2257
			return array( 'wp-cli', null );
2258
		}
2259
2260
		$referer = parse_url( $referer_url );
2261
2262
		$source_type = 'unknown';
2263
		$source_query = null;
2264
2265
		if ( ! is_array( $referer ) ) {
2266
			return array( $source_type, $source_query );
2267
		}
2268
2269
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
2270
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
2271
2272
		if ( isset( $referer['query'] ) ) {
2273
			parse_str( $referer['query'], $query_parts );
2274
		} else {
2275
			$query_parts = array();
2276
		}
2277
2278
		if ( $plugins_path === $referer['path'] ) {
2279
			$source_type = 'list';
2280
		} elseif ( $plugins_install_path === $referer['path'] ) {
2281
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
2282
			switch( $tab ) {
2283
				case 'popular':
2284
					$source_type = 'popular';
2285
					break;
2286
				case 'recommended':
2287
					$source_type = 'recommended';
2288
					break;
2289
				case 'favorites':
2290
					$source_type = 'favorites';
2291
					break;
2292
				case 'search':
2293
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
2294
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
2295
					break;
2296
				default:
2297
					$source_type = 'featured';
2298
			}
2299
		}
2300
2301
		return array( $source_type, $source_query );
2302
	}
2303
2304
	/**
2305
	 * Runs before bumping version numbers up to a new version
2306
	 * @param  string $version    Version:timestamp
2307
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
2308
	 * @return null              [description]
2309
	 */
2310
	public static function do_version_bump( $version, $old_version ) {
2311
2312
		if ( ! $old_version ) { // For new sites
2313
			// Setting up jetpack manage
2314
			Jetpack::activate_manage();
2315
		}
2316
	}
2317
2318
	/**
2319
	 * Sets the internal version number and activation state.
2320
	 * @static
2321
	 */
2322
	public static function plugin_initialize() {
2323
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2324
			Jetpack_Options::update_option( 'activated', 2 );
2325
		}
2326
2327 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2328
			$version = $old_version = JETPACK__VERSION . ':' . time();
2329
			/** This action is documented in class.jetpack.php */
2330
			do_action( 'updating_jetpack_version', $version, false );
2331
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2332
		}
2333
2334
		Jetpack::load_modules();
2335
2336
		Jetpack_Options::delete_option( 'do_activate' );
2337
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
2338
	}
2339
2340
	/**
2341
	 * Removes all connection options
2342
	 * @static
2343
	 */
2344
	public static function plugin_deactivation( ) {
2345
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2346
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2347
			Jetpack_Network::init()->deactivate();
2348
		} else {
2349
			Jetpack::disconnect( false );
2350
			//Jetpack_Heartbeat::init()->deactivate();
2351
		}
2352
	}
2353
2354
	/**
2355
	 * Disconnects from the Jetpack servers.
2356
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2357
	 * @static
2358
	 */
2359
	public static function disconnect( $update_activated_state = true ) {
2360
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2361
		Jetpack::clean_nonces( true );
2362
2363
		// If the site is in an IDC because sync is not allowed,
2364
		// let's make sure to not disconnect the production site.
2365
		if ( ! self::validate_sync_error_idc_option() ) {
2366
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2367
			Jetpack::load_xml_rpc_client();
2368
			$xml = new Jetpack_IXR_Client();
2369
			$xml->query( 'jetpack.deregister' );
2370
		}
2371
2372
		Jetpack_Options::delete_option(
2373
			array(
2374
				'blog_token',
2375
				'user_token',
2376
				'user_tokens',
2377
				'master_user',
2378
				'time_diff',
2379
				'fallback_no_verify_ssl_certs',
2380
			)
2381
		);
2382
2383
		Jetpack_IDC::clear_all_idc_options();
2384
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
2385
2386
		if ( $update_activated_state ) {
2387
			Jetpack_Options::update_option( 'activated', 4 );
2388
		}
2389
2390
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2391
			// Check then record unique disconnection if site has never been disconnected previously
2392
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2393
				$jetpack_unique_connection['disconnected'] = 1;
2394
			} else {
2395
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2396
					//track unique disconnect
2397
					$jetpack = Jetpack::init();
2398
2399
					$jetpack->stat( 'connections', 'unique-disconnect' );
2400
					$jetpack->do_stats( 'server_side' );
2401
				}
2402
				// increment number of times disconnected
2403
				$jetpack_unique_connection['disconnected'] += 1;
2404
			}
2405
2406
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2407
		}
2408
2409
		// Delete cached connected user data
2410
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2411
		delete_transient( $transient_key );
2412
2413
		// Delete all the sync related data. Since it could be taking up space.
2414
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2415
		Jetpack_Sync_Sender::get_instance()->uninstall();
2416
2417
		// Disable the Heartbeat cron
2418
		Jetpack_Heartbeat::init()->deactivate();
2419
	}
2420
2421
	/**
2422
	 * Unlinks the current user from the linked WordPress.com user
2423
	 */
2424
	public static function unlink_user( $user_id = null ) {
2425
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2426
			return false;
2427
2428
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2429
2430
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2431
			return false;
2432
2433
		if ( ! isset( $tokens[ $user_id ] ) )
2434
			return false;
2435
2436
		Jetpack::load_xml_rpc_client();
2437
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2438
		$xml->query( 'jetpack.unlink_user', $user_id );
2439
2440
		unset( $tokens[ $user_id ] );
2441
2442
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2443
2444
		/**
2445
		 * Fires after the current user has been unlinked from WordPress.com.
2446
		 *
2447
		 * @since 4.1.0
2448
		 *
2449
		 * @param int $user_id The current user's ID.
2450
		 */
2451
		do_action( 'jetpack_unlinked_user', $user_id );
2452
2453
		return true;
2454
	}
2455
2456
	/**
2457
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2458
	 */
2459
	public static function try_registration() {
2460
		// The user has agreed to the TOS at some point by now.
2461
		Jetpack_Options::update_option( 'tos_agreed', true );
2462
2463
		// Let's get some testing in beta versions and such.
2464
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2465
			// Before attempting to connect, let's make sure that the domains are viable.
2466
			$domains_to_check = array_unique( array(
2467
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2468
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2469
			) );
2470
			foreach ( $domains_to_check as $domain ) {
2471
				$result = Jetpack_Data::is_usable_domain( $domain );
2472
				if ( is_wp_error( $result ) ) {
2473
					return $result;
2474
				}
2475
			}
2476
		}
2477
2478
		$result = Jetpack::register();
2479
2480
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2481
		if ( ! $result || is_wp_error( $result ) ) {
2482
			return $result;
2483
		} else {
2484
			return true;
2485
		}
2486
	}
2487
2488
	/**
2489
	 * Tracking an internal event log. Try not to put too much chaff in here.
2490
	 *
2491
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2492
	 */
2493
	public static function log( $code, $data = null ) {
2494
		// only grab the latest 200 entries
2495
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2496
2497
		// Append our event to the log
2498
		$log_entry = array(
2499
			'time'    => time(),
2500
			'user_id' => get_current_user_id(),
2501
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2502
			'code'    => $code,
2503
		);
2504
		// Don't bother storing it unless we've got some.
2505
		if ( ! is_null( $data ) ) {
2506
			$log_entry['data'] = $data;
2507
		}
2508
		$log[] = $log_entry;
2509
2510
		// Try add_option first, to make sure it's not autoloaded.
2511
		// @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...
2512
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2513
			Jetpack_Options::update_option( 'log', $log );
2514
		}
2515
2516
		/**
2517
		 * Fires when Jetpack logs an internal event.
2518
		 *
2519
		 * @since 3.0.0
2520
		 *
2521
		 * @param array $log_entry {
2522
		 *	Array of details about the log entry.
2523
		 *
2524
		 *	@param string time Time of the event.
2525
		 *	@param int user_id ID of the user who trigerred the event.
2526
		 *	@param int blog_id Jetpack Blog ID.
2527
		 *	@param string code Unique name for the event.
2528
		 *	@param string data Data about the event.
2529
		 * }
2530
		 */
2531
		do_action( 'jetpack_log_entry', $log_entry );
2532
	}
2533
2534
	/**
2535
	 * Get the internal event log.
2536
	 *
2537
	 * @param $event (string) - only return the specific log events
2538
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2539
	 *
2540
	 * @return array of log events || WP_Error for invalid params
2541
	 */
2542
	public static function get_log( $event = false, $num = false ) {
2543
		if ( $event && ! is_string( $event ) ) {
2544
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2545
		}
2546
2547
		if ( $num && ! is_numeric( $num ) ) {
2548
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2549
		}
2550
2551
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2552
2553
		// If nothing set - act as it did before, otherwise let's start customizing the output
2554
		if ( ! $num && ! $event ) {
2555
			return $entire_log;
2556
		} else {
2557
			$entire_log = array_reverse( $entire_log );
2558
		}
2559
2560
		$custom_log_output = array();
2561
2562
		if ( $event ) {
2563
			foreach ( $entire_log as $log_event ) {
2564
				if ( $event == $log_event[ 'code' ] ) {
2565
					$custom_log_output[] = $log_event;
2566
				}
2567
			}
2568
		} else {
2569
			$custom_log_output = $entire_log;
2570
		}
2571
2572
		if ( $num ) {
2573
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2574
		}
2575
2576
		return $custom_log_output;
2577
	}
2578
2579
	/**
2580
	 * Log modification of important settings.
2581
	 */
2582
	public static function log_settings_change( $option, $old_value, $value ) {
2583
		switch( $option ) {
2584
			case 'jetpack_sync_non_public_post_stati':
2585
				self::log( $option, $value );
2586
				break;
2587
		}
2588
	}
2589
2590
	/**
2591
	 * Return stat data for WPCOM sync
2592
	 */
2593
	public static function get_stat_data( $encode = true, $extended = true ) {
2594
		$data = Jetpack_Heartbeat::generate_stats_array();
2595
2596
		if ( $extended ) {
2597
			$additional_data = self::get_additional_stat_data();
2598
			$data = array_merge( $data, $additional_data );
2599
		}
2600
2601
		if ( $encode ) {
2602
			return json_encode( $data );
2603
		}
2604
2605
		return $data;
2606
	}
2607
2608
	/**
2609
	 * Get additional stat data to sync to WPCOM
2610
	 */
2611
	public static function get_additional_stat_data( $prefix = '' ) {
2612
		$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...
2613
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2614
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
0 ignored issues
show
Bug introduced by
The method get_site_user_count() cannot be called from this context as it is declared private in class Jetpack_Functions.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
2615
		$return["{$prefix}site-count"]     = 0;
2616
2617
		if ( function_exists( 'get_blog_count' ) ) {
2618
			$return["{$prefix}site-count"] = get_blog_count();
2619
		}
2620
		return $return;
2621
	}
2622
2623
	/* Admin Pages */
2624
2625
	function admin_init() {
2626
		// If the plugin is not connected, display a connect message.
2627
		if (
2628
			// the plugin was auto-activated and needs its candy
2629
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2630
		||
2631
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2632
			! Jetpack_Options::get_option( 'activated' )
2633
		) {
2634
			Jetpack::plugin_initialize();
2635
		}
2636
2637
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2638
			Jetpack_Connection_Banner::init();
2639
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2640
			// Upgrade: 1.1 -> 1.1.1
2641
			// Check and see if host can verify the Jetpack servers' SSL certificate
2642
			$args = array();
2643
			Jetpack_Client::_wp_remote_request(
2644
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2645
				$args,
2646
				true
2647
			);
2648
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
2649
			// Show the notice on the Dashboard only for now
2650
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2651
		}
2652
2653
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2654
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2655
		}
2656
2657
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2658
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2659
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2660
2661
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2662
			// Artificially throw errors in certain whitelisted cases during plugin activation
2663
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2664
		}
2665
2666
		// Jetpack Manage Activation Screen from .com
2667
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2668
2669
		// Add custom column in wp-admin/users.php to show whether user is linked.
2670
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2671
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2672
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2673
	}
2674
2675
	function admin_body_class( $admin_body_class = '' ) {
2676
		$classes = explode( ' ', trim( $admin_body_class ) );
2677
2678
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2679
2680
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2681
		return " $admin_body_class ";
2682
	}
2683
2684
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2685
		return $admin_body_class . ' jetpack-pagestyles ';
2686
	}
2687
2688
	/**
2689
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2690
	 *
2691
	 * @return null
2692
	 */
2693
	function prepare_manage_jetpack_notice() {
2694
2695
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2696
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2697
	}
2698
2699
	function manage_activate_screen() {
2700
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2701
	}
2702
	/**
2703
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2704
	 * This function artificially throws errors for such cases (whitelisted).
2705
	 *
2706
	 * @param string $plugin The activated plugin.
2707
	 */
2708
	function throw_error_on_activate_plugin( $plugin ) {
2709
		$active_modules = Jetpack::get_active_modules();
2710
2711
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2712
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2713
			$throw = false;
2714
2715
			// Try and make sure it really was the stats plugin
2716
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2717
				if ( 'stats.php' == basename( $plugin ) ) {
2718
					$throw = true;
2719
				}
2720
			} else {
2721
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2722
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2723
					$throw = true;
2724
				}
2725
			}
2726
2727
			if ( $throw ) {
2728
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2729
			}
2730
		}
2731
	}
2732
2733
	function intercept_plugin_error_scrape_init() {
2734
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2735
	}
2736
2737
	function intercept_plugin_error_scrape( $action, $result ) {
2738
		if ( ! $result ) {
2739
			return;
2740
		}
2741
2742
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2743
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2744
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2745
			}
2746
		}
2747
	}
2748
2749
	function add_remote_request_handlers() {
2750
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2751
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
2752
	}
2753
2754
	function remote_request_handlers() {
2755
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
2756
2757
		switch ( current_filter() ) {
2758
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2759
			$response = $this->upload_handler();
2760
			break;
2761
2762
		case 'wp_ajax_nopriv_jetpack_update_file' :
2763
			$response = $this->upload_handler( true );
2764
			break;
2765
		default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

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

Loading history...
2766
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2767
			break;
2768
		}
2769
2770
		if ( ! $response ) {
2771
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2772
		}
2773
2774
		if ( is_wp_error( $response ) ) {
2775
			$status_code       = $response->get_error_data();
2776
			$error             = $response->get_error_code();
2777
			$error_description = $response->get_error_message();
2778
2779
			if ( ! is_int( $status_code ) ) {
2780
				$status_code = 400;
2781
			}
2782
2783
			status_header( $status_code );
2784
			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...
2785
		}
2786
2787
		status_header( 200 );
2788
		if ( true === $response ) {
2789
			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...
2790
		}
2791
2792
		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...
2793
	}
2794
2795
	/**
2796
	 * Uploads a file gotten from the global $_FILES.
2797
	 * If `$update_media_item` is true and `post_id` is defined
2798
	 * the attachment file of the media item (gotten through of the post_id)
2799
	 * will be updated instead of add a new one.
2800
	 *
2801
	 * @param  boolean $update_media_item - update media attachment
2802
	 * @return array - An array describing the uploadind files process
2803
	 */
2804
	function upload_handler( $update_media_item = false ) {
2805
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
2806
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
2807
		}
2808
2809
		$user = wp_authenticate( '', '' );
2810
		if ( ! $user || is_wp_error( $user ) ) {
2811
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
2812
		}
2813
2814
		wp_set_current_user( $user->ID );
2815
2816
		if ( ! current_user_can( 'upload_files' ) ) {
2817
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
2818
		}
2819
2820
		if ( empty( $_FILES ) ) {
2821
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
2822
		}
2823
2824
		foreach ( array_keys( $_FILES ) as $files_key ) {
2825
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
2826
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
2827
			}
2828
		}
2829
2830
		$media_keys = array_keys( $_FILES['media'] );
2831
2832
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
2833
		if ( ! $token || is_wp_error( $token ) ) {
2834
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
2835
		}
2836
2837
		$uploaded_files = array();
2838
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
2839
		unset( $GLOBALS['post'] );
2840
		foreach ( $_FILES['media']['name'] as $index => $name ) {
2841
			$file = array();
2842
			foreach ( $media_keys as $media_key ) {
2843
				$file[$media_key] = $_FILES['media'][$media_key][$index];
2844
			}
2845
2846
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
2847
2848
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
2849
			if ( $hmac_provided !== $hmac_file ) {
2850
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
2851
				continue;
2852
			}
2853
2854
			$_FILES['.jetpack.upload.'] = $file;
2855
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
2856
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
2857
				$post_id = 0;
2858
			}
2859
2860
			if ( $update_media_item ) {
2861
				if ( ! isset( $post_id ) || $post_id === 0 ) {
2862
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
2863
				}
2864
2865
				$media_array = $_FILES['media'];
2866
2867
				$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...
2868
				$file_array['type'] = $media_array['type'][0];
2869
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
2870
				$file_array['error'] = $media_array['error'][0];
2871
				$file_array['size'] = $media_array['size'][0];
2872
2873
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
2874
2875
				if ( is_wp_error( $edited_media_item ) ) {
2876
					return $edited_media_item;
2877
				}
2878
2879
				$response = (object) array(
2880
					'id'   => (string) $post_id,
2881
					'file' => (string) $edited_media_item->post_title,
2882
					'url'  => (string) wp_get_attachment_url( $post_id ),
2883
					'type' => (string) $edited_media_item->post_mime_type,
2884
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
2885
				);
2886
2887
				return (array) array( $response );
2888
			}
2889
2890
			$attachment_id = media_handle_upload(
2891
				'.jetpack.upload.',
2892
				$post_id,
2893
				array(),
2894
				array(
2895
					'action' => 'jetpack_upload_file',
2896
				)
2897
			);
2898
2899
			if ( ! $attachment_id ) {
2900
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
2901
			} elseif ( is_wp_error( $attachment_id ) ) {
2902
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
2903
			} else {
2904
				$attachment = get_post( $attachment_id );
2905
				$uploaded_files[$index] = (object) array(
2906
					'id'   => (string) $attachment_id,
2907
					'file' => $attachment->post_title,
2908
					'url'  => wp_get_attachment_url( $attachment_id ),
2909
					'type' => $attachment->post_mime_type,
2910
					'meta' => wp_get_attachment_metadata( $attachment_id ),
2911
				);
2912
				// Zip files uploads are not supported unless they are done for installation purposed
2913
				// lets delete them in case something goes wrong in this whole process
2914
				if ( 'application/zip' === $attachment->post_mime_type ) {
2915
					// Schedule a cleanup for 2 hours from now in case of failed install.
2916
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
2917
				}
2918
			}
2919
		}
2920
		if ( ! is_null( $global_post ) ) {
2921
			$GLOBALS['post'] = $global_post;
2922
		}
2923
2924
		return $uploaded_files;
2925
	}
2926
2927
	/**
2928
	 * Add help to the Jetpack page
2929
	 *
2930
	 * @since Jetpack (1.2.3)
2931
	 * @return false if not the Jetpack page
2932
	 */
2933
	function admin_help() {
2934
		$current_screen = get_current_screen();
2935
2936
		// Overview
2937
		$current_screen->add_help_tab(
2938
			array(
2939
				'id'		=> 'home',
2940
				'title'		=> __( 'Home', 'jetpack' ),
2941
				'content'	=>
2942
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
2943
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
2944
					'<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>',
2945
			)
2946
		);
2947
2948
		// Screen Content
2949
		if ( current_user_can( 'manage_options' ) ) {
2950
			$current_screen->add_help_tab(
2951
				array(
2952
					'id'		=> 'settings',
2953
					'title'		=> __( 'Settings', 'jetpack' ),
2954
					'content'	=>
2955
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
2956
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
2957
						'<ol>' .
2958
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
2959
							'<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>' .
2960
						'</ol>' .
2961
						'<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>'
2962
				)
2963
			);
2964
		}
2965
2966
		// Help Sidebar
2967
		$current_screen->set_help_sidebar(
2968
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
2969
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
2970
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
2971
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
2972
		);
2973
	}
2974
2975
	function admin_menu_css() {
2976
		wp_enqueue_style( 'jetpack-icons' );
2977
	}
2978
2979
	function admin_menu_order() {
2980
		return true;
2981
	}
2982
2983
	function enqueue_gutenberg_locale() {
2984
		wp_add_inline_script(
2985
			'wp-i18n',
2986
			'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2987
		);
2988
	}
2989
2990 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
2991
		$jp_menu_order = array();
2992
2993
		foreach ( $menu_order as $index => $item ) {
2994
			if ( $item != 'jetpack' ) {
2995
				$jp_menu_order[] = $item;
2996
			}
2997
2998
			if ( $index == 0 ) {
2999
				$jp_menu_order[] = 'jetpack';
3000
			}
3001
		}
3002
3003
		return $jp_menu_order;
3004
	}
3005
3006
	function admin_head() {
3007 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3008
			/** This action is documented in class.jetpack-admin-page.php */
3009
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3010
	}
3011
3012
	function admin_banner_styles() {
3013
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3014
3015
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3016
			wp_register_style(
3017
				'jetpack-dops-style',
3018
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3019
				array(),
3020
				JETPACK__VERSION
3021
			);
3022
		}
3023
3024
		wp_enqueue_style(
3025
			'jetpack',
3026
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3027
			array( 'jetpack-dops-style' ),
3028
			 JETPACK__VERSION . '-20121016'
3029
		);
3030
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3031
		wp_style_add_data( 'jetpack', 'suffix', $min );
3032
	}
3033
3034
	function plugin_action_links( $actions ) {
3035
3036
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3037
3038
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3039
			return array_merge(
3040
				$jetpack_home,
3041
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3042
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3043
				$actions
3044
				);
3045
			}
3046
3047
		return array_merge( $jetpack_home, $actions );
3048
	}
3049
3050
	/**
3051
	 * This is the first banner
3052
	 * It should be visible only to user that can update the option
3053
	 * Are not connected
3054
	 *
3055
	 * @return null
3056
	 */
3057
	function admin_jetpack_manage_notice() {
3058
		$screen = get_current_screen();
3059
3060
		// Don't show the connect notice on the jetpack settings page.
3061
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3062
			return;
3063
		}
3064
3065
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3066
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3067
		/**
3068
		 * I think it would be great to have different wordsing depending on where you are
3069
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3070
		 * etc..
3071
		 */
3072
3073
		?>
3074
		<div id="message" class="updated jp-banner">
3075
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3076
				<div class="jp-banner__description-container">
3077
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3078
					<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>
3079
					<p class="jp-banner__button-container">
3080
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3081
						<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>
3082
					</p>
3083
				</div>
3084
		</div>
3085
		<?php
3086
	}
3087
3088
	/**
3089
	 * Returns the url that the user clicks to remove the notice for the big banner
3090
	 * @return string
3091
	 */
3092
	function opt_out_jetpack_manage_url() {
3093
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3094
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3095
	}
3096
	/**
3097
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3098
	 * @return string
3099
	 */
3100
	function opt_in_jetpack_manage_url() {
3101
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3102
	}
3103
3104
	function opt_in_jetpack_manage_notice() {
3105
		?>
3106
		<div class="wrap">
3107
			<div id="message" class="jetpack-message is-opt-in">
3108
				<?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' ); ?>
3109
			</div>
3110
		</div>
3111
		<?php
3112
3113
	}
3114
	/**
3115
	 * Determines whether to show the notice of not true = display notice
3116
	 * @return bool
3117
	 */
3118
	function can_display_jetpack_manage_notice() {
3119
		// never display the notice to users that can't do anything about it anyways
3120
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3121
			return false;
3122
3123
		// don't display if we are in development more
3124
		if( Jetpack::is_development_mode() ) {
3125
			return false;
3126
		}
3127
		// don't display if the site is private
3128
		if(  ! Jetpack_Options::get_option( 'public' ) )
3129
			return false;
3130
3131
		/**
3132
		 * Should the Jetpack Remote Site Management notice be displayed.
3133
		 *
3134
		 * @since 3.3.0
3135
		 *
3136
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3137
		 */
3138
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3139
	}
3140
3141
	/*
3142
	 * Registration flow:
3143
	 * 1 - ::admin_page_load() action=register
3144
	 * 2 - ::try_registration()
3145
	 * 3 - ::register()
3146
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3147
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3148
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3149
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3150
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3151
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3152
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3153
	 *       jetpack_id, jetpack_secret, jetpack_public
3154
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3155
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3156
	 * 5 - user logs in with WP.com account
3157
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3158
	 *		- Jetpack_Client_Server::authorize()
3159
	 *		- Jetpack_Client_Server::get_token()
3160
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3161
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3162
	 *			- which responds with access_token, token_type, scope
3163
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3164
	 *		- Jetpack::activate_default_modules()
3165
	 *     		- Deactivates deprecated plugins
3166
	 *     		- Activates all default modules
3167
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3168
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3169
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3170
	 *     Done!
3171
	 */
3172
3173
	/**
3174
	 * Handles the page load events for the Jetpack admin page
3175
	 */
3176
	function admin_page_load() {
3177
		$error = false;
3178
3179
		// Make sure we have the right body class to hook stylings for subpages off of.
3180
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3181
3182
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3183
			// Should only be used in intermediate redirects to preserve state across redirects
3184
			Jetpack::restate();
3185
		}
3186
3187
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3188
			// User clicked in the iframe to link their accounts
3189
			if ( ! Jetpack::is_user_connected() ) {
3190
				$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3191
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3192
3193
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3194
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3195
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3196
3197
				if ( isset( $_GET['notes_iframe'] ) )
3198
					$connect_url .= '&notes_iframe';
3199
				wp_redirect( $connect_url );
3200
				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...
3201
			} else {
3202
				if ( ! isset( $_GET['calypso_env'] ) ) {
3203
					Jetpack::state( 'message', 'already_authorized' );
3204
					wp_safe_redirect( Jetpack::admin_url() );
3205
					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...
3206
				} else {
3207
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3208
					$connect_url .= '&already_authorized=true';
3209
					wp_redirect( $connect_url );
3210
					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...
3211
				}
3212
			}
3213
		}
3214
3215
3216
		if ( isset( $_GET['action'] ) ) {
3217
			switch ( $_GET['action'] ) {
3218
			case 'authorize':
3219
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3220
					Jetpack::state( 'message', 'already_authorized' );
3221
					wp_safe_redirect( Jetpack::admin_url() );
3222
					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...
3223
				}
3224
				Jetpack::log( 'authorize' );
3225
				$client_server = new Jetpack_Client_Server;
3226
				$client_server->client_authorize();
3227
				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...
3228
			case 'register' :
3229
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3230
					$error = 'cheatin';
3231
					break;
3232
				}
3233
				check_admin_referer( 'jetpack-register' );
3234
				Jetpack::log( 'register' );
3235
				Jetpack::maybe_set_version_option();
3236
				$registered = Jetpack::try_registration();
3237
				if ( is_wp_error( $registered ) ) {
3238
					$error = $registered->get_error_code();
3239
					Jetpack::state( 'error', $error );
3240
					Jetpack::state( 'error', $registered->get_error_message() );
3241
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
3242
						'error_code' => $error,
3243
						'error_message' => $registered->get_error_message()
3244
					) );
3245
					break;
3246
				}
3247
3248
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3249
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3250
3251
				JetpackTracking::record_user_event( 'jpc_register_success', array(
3252
					'from' => $from
3253
				) );
3254
3255
				$url = $this->build_connect_url( true, $redirect, $from );
3256
3257
				if ( ! empty( $_GET['onboarding'] ) ) {
3258
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3259
				}
3260
3261
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3262
					$url = add_query_arg( 'auth_approved', 'true', $url );
3263
				}
3264
3265
				wp_redirect( $url );
3266
				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...
3267
			case 'activate' :
3268
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3269
					$error = 'cheatin';
3270
					break;
3271
				}
3272
3273
				$module = stripslashes( $_GET['module'] );
3274
				check_admin_referer( "jetpack_activate-$module" );
3275
				Jetpack::log( 'activate', $module );
3276
				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...
3277
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
3278
				}
3279
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3280
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3281
				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...
3282
			case 'activate_default_modules' :
3283
				check_admin_referer( 'activate_default_modules' );
3284
				Jetpack::log( 'activate_default_modules' );
3285
				Jetpack::restate();
3286
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3287
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3288
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3289
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3290
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3291
				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...
3292
			case 'disconnect' :
3293
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3294
					$error = 'cheatin';
3295
					break;
3296
				}
3297
3298
				check_admin_referer( 'jetpack-disconnect' );
3299
				Jetpack::log( 'disconnect' );
3300
				Jetpack::disconnect();
3301
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3302
				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...
3303
			case 'reconnect' :
3304
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3305
					$error = 'cheatin';
3306
					break;
3307
				}
3308
3309
				check_admin_referer( 'jetpack-reconnect' );
3310
				Jetpack::log( 'reconnect' );
3311
				$this->disconnect();
3312
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3313
				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...
3314 View Code Duplication
			case 'deactivate' :
3315
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3316
					$error = 'cheatin';
3317
					break;
3318
				}
3319
3320
				$modules = stripslashes( $_GET['module'] );
3321
				check_admin_referer( "jetpack_deactivate-$modules" );
3322
				foreach ( explode( ',', $modules ) as $module ) {
3323
					Jetpack::log( 'deactivate', $module );
3324
					Jetpack::deactivate_module( $module );
3325
					Jetpack::state( 'message', 'module_deactivated' );
3326
				}
3327
				Jetpack::state( 'module', $modules );
3328
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3329
				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...
3330
			case 'unlink' :
3331
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3332
				check_admin_referer( 'jetpack-unlink' );
3333
				Jetpack::log( 'unlink' );
3334
				$this->unlink_user();
3335
				Jetpack::state( 'message', 'unlinked' );
3336
				if ( 'sub-unlink' == $redirect ) {
3337
					wp_safe_redirect( admin_url() );
3338
				} else {
3339
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3340
				}
3341
				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...
3342
			case 'onboard' :
3343
				if ( ! current_user_can( 'manage_options' ) ) {
3344
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3345
				} else {
3346
					Jetpack::create_onboarding_token();
3347
					$url = $this->build_connect_url( true );
3348
3349
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
3350
						$url = add_query_arg( 'onboarding', $token, $url );
3351
					}
3352
3353
					$calypso_env = ! empty( $_GET[ 'calypso_env' ] ) ? $_GET[ 'calypso_env' ] : false;
3354
					if ( $calypso_env ) {
3355
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
3356
					}
3357
3358
					wp_redirect( $url );
3359
					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...
3360
				}
3361
				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...
3362
			default:
3363
				/**
3364
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3365
				 *
3366
				 * @since 2.6.0
3367
				 *
3368
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3369
				 */
3370
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3371
			}
3372
		}
3373
3374
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3375
			self::activate_new_modules( true );
3376
		}
3377
3378
		$message_code = Jetpack::state( 'message' );
3379
		if ( Jetpack::state( 'optin-manage' ) ) {
3380
			$activated_manage = $message_code;
3381
			$message_code = 'jetpack-manage';
3382
		}
3383
3384
		switch ( $message_code ) {
3385
		case 'jetpack-manage':
3386
			$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>';
3387
			if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
3388
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3389
			}
3390
			break;
3391
3392
		}
3393
3394
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3395
3396
		if ( ! empty( $deactivated_plugins ) ) {
3397
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3398
			$deactivated_titles  = array();
3399
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3400
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3401
					continue;
3402
				}
3403
3404
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3405
			}
3406
3407
			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...
3408
				if ( $this->message ) {
3409
					$this->message .= "<br /><br />\n";
3410
				}
3411
3412
				$this->message .= wp_sprintf(
3413
					_n(
3414
						'Jetpack contains the most recent version of the old %l plugin.',
3415
						'Jetpack contains the most recent versions of the old %l plugins.',
3416
						count( $deactivated_titles ),
3417
						'jetpack'
3418
					),
3419
					$deactivated_titles
3420
				);
3421
3422
				$this->message .= "<br />\n";
3423
3424
				$this->message .= _n(
3425
					'The old version has been deactivated and can be removed from your site.',
3426
					'The old versions have been deactivated and can be removed from your site.',
3427
					count( $deactivated_titles ),
3428
					'jetpack'
3429
				);
3430
			}
3431
		}
3432
3433
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3434
3435
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3436
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3437
		}
3438
3439 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3440
			/**
3441
			 * Fires when a module configuration page is loaded.
3442
			 * The dynamic part of the hook is the configure parameter from the URL.
3443
			 *
3444
			 * @since 1.1.0
3445
			 */
3446
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3447
		}
3448
3449
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3450
	}
3451
3452
	function admin_notices() {
3453
3454
		if ( $this->error ) {
3455
?>
3456
<div id="message" class="jetpack-message jetpack-err">
3457
	<div class="squeezer">
3458
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3459
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3460
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3461
<?php	endif; ?>
3462
	</div>
3463
</div>
3464
<?php
3465
		}
3466
3467
		if ( $this->message ) {
3468
?>
3469
<div id="message" class="jetpack-message">
3470
	<div class="squeezer">
3471
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3472
	</div>
3473
</div>
3474
<?php
3475
		}
3476
3477
		if ( $this->privacy_checks ) :
3478
			$module_names = $module_slugs = array();
3479
3480
			$privacy_checks = explode( ',', $this->privacy_checks );
3481
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3482
			foreach ( $privacy_checks as $module_slug ) {
3483
				$module = Jetpack::get_module( $module_slug );
3484
				if ( ! $module ) {
3485
					continue;
3486
				}
3487
3488
				$module_slugs[] = $module_slug;
3489
				$module_names[] = "<strong>{$module['name']}</strong>";
3490
			}
3491
3492
			$module_slugs = join( ',', $module_slugs );
3493
?>
3494
<div id="message" class="jetpack-message jetpack-err">
3495
	<div class="squeezer">
3496
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3497
		<p><?php
3498
			echo wp_kses(
3499
				wptexturize(
3500
					wp_sprintf(
3501
						_nx(
3502
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3503
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3504
							count( $privacy_checks ),
3505
							'%l = list of Jetpack module/feature names',
3506
							'jetpack'
3507
						),
3508
						$module_names
3509
					)
3510
				),
3511
				array( 'strong' => true )
3512
			);
3513
3514
			echo "\n<br />\n";
3515
3516
			echo wp_kses(
3517
				sprintf(
3518
					_nx(
3519
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3520
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3521
						count( $privacy_checks ),
3522
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3523
						'jetpack'
3524
					),
3525
					wp_nonce_url(
3526
						Jetpack::admin_url(
3527
							array(
3528
								'page'   => 'jetpack',
3529
								'action' => 'deactivate',
3530
								'module' => urlencode( $module_slugs ),
3531
							)
3532
						),
3533
						"jetpack_deactivate-$module_slugs"
3534
					),
3535
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3536
				),
3537
				array( 'a' => array( 'href' => true, 'title' => true ) )
3538
			);
3539
		?></p>
3540
	</div>
3541
</div>
3542
<?php endif;
3543
	// only display the notice if the other stuff is not there
3544
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3545
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3546
			$this->opt_in_jetpack_manage_notice();
3547
		}
3548
	}
3549
3550
	/**
3551
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3552
	 */
3553
	function stat( $group, $detail ) {
3554
		if ( ! isset( $this->stats[ $group ] ) )
3555
			$this->stats[ $group ] = array();
3556
		$this->stats[ $group ][] = $detail;
3557
	}
3558
3559
	/**
3560
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3561
	 */
3562
	function do_stats( $method = '' ) {
3563
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3564
			foreach ( $this->stats as $group => $stats ) {
3565
				if ( is_array( $stats ) && count( $stats ) ) {
3566
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3567
					if ( 'server_side' === $method ) {
3568
						self::do_server_side_stat( $args );
3569
					} else {
3570
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3571
					}
3572
				}
3573
				unset( $this->stats[ $group ] );
3574
			}
3575
		}
3576
	}
3577
3578
	/**
3579
	 * Runs stats code for a one-off, server-side.
3580
	 *
3581
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3582
	 *
3583
	 * @return bool If it worked.
3584
	 */
3585
	static function do_server_side_stat( $args ) {
3586
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3587
		if ( is_wp_error( $response ) )
3588
			return false;
3589
3590
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3591
			return false;
3592
3593
		return true;
3594
	}
3595
3596
	/**
3597
	 * Builds the stats url.
3598
	 *
3599
	 * @param $args array|string The arguments to append to the URL.
3600
	 *
3601
	 * @return string The URL to be pinged.
3602
	 */
3603
	static function build_stats_url( $args ) {
3604
		$defaults = array(
3605
			'v'    => 'wpcom2',
3606
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3607
		);
3608
		$args     = wp_parse_args( $args, $defaults );
3609
		/**
3610
		 * Filter the URL used as the Stats tracking pixel.
3611
		 *
3612
		 * @since 2.3.2
3613
		 *
3614
		 * @param string $url Base URL used as the Stats tracking pixel.
3615
		 */
3616
		$base_url = apply_filters(
3617
			'jetpack_stats_base_url',
3618
			'https://pixel.wp.com/g.gif'
3619
		);
3620
		$url      = add_query_arg( $args, $base_url );
3621
		return $url;
3622
	}
3623
3624
	static function sign_role( $role, $user_id = null ) {
3625
		if ( empty( $user_id ) ) {
3626
			$user_id = (int) get_current_user_id();
3627
		}
3628
3629
		if ( ! $user_id  ) {
3630
			return false;
3631
		}
3632
3633
		$token = Jetpack_Data::get_access_token();
3634
		if ( ! $token || is_wp_error( $token ) ) {
3635
			return false;
3636
		}
3637
3638
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3639
	}
3640
3641
3642
	/**
3643
	 * Builds a URL to the Jetpack connection auth page
3644
	 *
3645
	 * @since 3.9.5
3646
	 *
3647
	 * @param bool $raw If true, URL will not be escaped.
3648
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3649
	 *                              If string, will be a custom redirect.
3650
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3651
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
3652
	 *
3653
	 * @return string Connect URL
3654
	 */
3655
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
3656
		$site_id = Jetpack_Options::get_option( 'id' );
3657
		$token = Jetpack_Options::get_option( 'blog_token' );
3658
3659
		if ( $register || ! $token || ! $site_id ) {
3660
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3661
3662
			if ( ! empty( $redirect ) ) {
3663
				$url = add_query_arg(
3664
					'redirect',
3665
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
3666
					$url
3667
				);
3668
			}
3669
3670
			if( is_network_admin() ) {
3671
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3672
			}
3673
		} else {
3674
3675
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
3676
			// because otherwise this logic can get us in to a loop.
3677
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
3678
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
3679
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
3680
3681
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
3682
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
3683
					'1.1'
3684
				);
3685
3686
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
3687
					// Generating a register URL instead to refresh the existing token
3688
					return $this->build_connect_url( $raw, $redirect, $from, true );
3689
				}
3690
			}
3691
3692
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3693
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3694
			}
3695
3696
			$role = self::translate_current_user_to_role();
3697
			$signed_role = self::sign_role( $role );
3698
3699
			$user = wp_get_current_user();
3700
3701
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3702
			$redirect = $redirect
3703
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3704
				: $jetpack_admin_page;
3705
3706
			if( isset( $_REQUEST['is_multisite'] ) ) {
3707
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3708
			}
3709
3710
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
3711
3712
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3713
				? get_site_icon_url()
3714
				: false;
3715
3716
			/**
3717
			 * Filter the type of authorization.
3718
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
3719
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3720
			 *
3721
			 * @since 4.3.3
3722
			 *
3723
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3724
			 */
3725
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3726
3727
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
3728
3729
			$args = urlencode_deep(
3730
				array(
3731
					'response_type' => 'code',
3732
					'client_id'     => Jetpack_Options::get_option( 'id' ),
3733
					'redirect_uri'  => add_query_arg(
3734
						array(
3735
							'action'   => 'authorize',
3736
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3737
							'redirect' => urlencode( $redirect ),
3738
						),
3739
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
3740
					),
3741
					'state'         => $user->ID,
3742
					'scope'         => $signed_role,
3743
					'user_email'    => $user->user_email,
3744
					'user_login'    => $user->user_login,
3745
					'is_active'     => Jetpack::is_active(),
3746
					'jp_version'    => JETPACK__VERSION,
3747
					'auth_type'     => $auth_type,
3748
					'secret'        => $secrets['secret_1'],
3749
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
3750
					'blogname'      => get_option( 'blogname' ),
3751
					'site_url'      => site_url(),
3752
					'home_url'      => home_url(),
3753
					'site_icon'     => $site_icon,
3754
					'site_lang'     => get_locale(),
3755
					'_ui'           => $tracks_identity['_ui'],
3756
					'_ut'           => $tracks_identity['_ut']
3757
				)
3758
			);
3759
3760
			self::apply_activation_source_to_args( $args );
3761
3762
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
3763
		}
3764
3765
		if ( $from ) {
3766
			$url = add_query_arg( 'from', $from, $url );
3767
		}
3768
3769
3770
		if ( isset( $_GET['calypso_env'] ) ) {
3771
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
3772
		}
3773
3774
		return $raw ? $url : esc_url( $url );
3775
	}
3776
3777
	public static function apply_activation_source_to_args( &$args ) {
3778
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
3779
3780
		if ( $activation_source_name ) {
3781
			$args['_as'] = urlencode( $activation_source_name );
3782
		}
3783
3784
		if ( $activation_source_keyword ) {
3785
			$args['_ak'] = urlencode( $activation_source_keyword );
3786
		}
3787
	}
3788
3789
	function build_reconnect_url( $raw = false ) {
3790
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
3791
		return $raw ? $url : esc_url( $url );
3792
	}
3793
3794
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
3795
		$actionurl = str_replace( '&amp;', '&', $actionurl );
3796
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
3797
	}
3798
3799
	function dismiss_jetpack_notice() {
3800
3801
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
3802
			return;
3803
		}
3804
3805
		switch( $_GET['jetpack-notice'] ) {
3806
			case 'dismiss':
3807
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
3808
3809
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
3810
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
3811
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
3812
				}
3813
				break;
3814 View Code Duplication
			case 'jetpack-manage-opt-out':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

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

    doSomethingElse(); //wrong
    break;

}

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

Loading history...
3815
3816
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
3817
					// Don't show the banner again
3818
3819
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
3820
					// redirect back to the page that had the notice
3821
					if ( wp_get_referer() ) {
3822
						wp_safe_redirect( wp_get_referer() );
3823
					} else {
3824
						// Take me to Jetpack
3825
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3826
					}
3827
				}
3828
				break;
3829 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

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

    doSomethingElse(); //wrong
    break;

}

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

Loading history...
3830
3831
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
3832
					// Don't show the banner again
3833
3834
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
3835
					// redirect back to the page that had the notice
3836
					if ( wp_get_referer() ) {
3837
						wp_safe_redirect( wp_get_referer() );
3838
					} else {
3839
						// Take me to Jetpack
3840
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3841
					}
3842
				}
3843
				break;
3844
			case 'jetpack-manage-opt-in':
3845
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
3846
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
3847
3848
					$redirection_url = Jetpack::admin_url();
3849
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3850
3851
					// Don't redirect form the Jetpack Setting Page
3852
					$referer_parsed = parse_url ( wp_get_referer() );
3853
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
3854
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
3855
						// Take the user to Jetpack home except when on the setting page
3856
						$redirection_url = wp_get_referer();
3857
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3858
					}
3859
					// Also update the JSON API FULL MANAGEMENT Option
3860
					Jetpack::activate_module( 'manage', false, false );
3861
3862
					// Special Message when option in.
3863
					Jetpack::state( 'optin-manage', 'true' );
3864
					// Activate the Module if not activated already
3865
3866
					// Redirect properly
3867
					wp_safe_redirect( $redirection_url );
3868
3869
				}
3870
				break;
3871
		}
3872
	}
3873
3874
	public static function admin_screen_configure_module( $module_id ) {
3875
3876
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
3877
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
3878
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
3879
				/**
3880
				 * Fires to diplay a custom module activation screen.
3881
				 *
3882
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
3883
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3884
				 *
3885
				 * @module manage
3886
				 *
3887
				 * @since 3.8.0
3888
				 *
3889
				 * @param int $module_id Module ID.
3890
				 */
3891
				do_action( 'display_activate_module_setting_' . $module_id );
3892
			} else {
3893
				self::display_activate_module_link( $module_id );
3894
			}
3895
3896
			return false;
3897
		} ?>
3898
3899
		<div id="jp-settings-screen" style="position: relative">
3900
			<h3>
3901
			<?php
3902
				$module = Jetpack::get_module( $module_id );
3903
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
3904
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
3905
			?>
3906
			</h3>
3907
			<?php
3908
				/**
3909
				 * Fires within the displayed message when a feature configuation is updated.
3910
				 *
3911
				 * @since 3.4.0
3912
				 *
3913
				 * @param int $module_id Module ID.
3914
				 */
3915
				do_action( 'jetpack_notices_update_settings', $module_id );
3916
				/**
3917
				 * Fires when a feature configuation screen is loaded.
3918
				 * The dynamic part of the hook, $module_id, is the module ID.
3919
				 *
3920
				 * @since 1.1.0
3921
				 */
3922
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
3923
			?>
3924
		</div><?php
3925
	}
3926
3927
	/**
3928
	 * Display link to activate the module to see the settings screen.
3929
	 * @param  string $module_id
3930
	 * @return null
3931
	 */
3932
	public static function display_activate_module_link( $module_id ) {
3933
3934
		$info =  Jetpack::get_module( $module_id );
3935
		$extra = '';
3936
		$activate_url = wp_nonce_url(
3937
				Jetpack::admin_url(
3938
					array(
3939
						'page'   => 'jetpack',
3940
						'action' => 'activate',
3941
						'module' => $module_id,
3942
					)
3943
				),
3944
				"jetpack_activate-$module_id"
3945
			);
3946
3947
		?>
3948
3949
		<div class="wrap configure-module">
3950
			<div id="jp-settings-screen">
3951
				<?php
3952
				if ( $module_id == 'json-api' ) {
3953
3954
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
3955
3956
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
3957
3958
					$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' );
3959
3960
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
3961
				} ?>
3962
3963
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
3964
				<div class="narrow">
3965
					<p><?php echo  $info['description']; ?></p>
3966
					<?php if( $extra ) { ?>
3967
					<p><?php echo esc_html( $extra ); ?></p>
3968
					<?php } ?>
3969
					<p>
3970
						<?php
3971
						if( wp_get_referer() ) {
3972
							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() );
3973
						} else {
3974
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
3975
						} ?>
3976
					</p>
3977
				</div>
3978
3979
			</div>
3980
		</div>
3981
3982
		<?php
3983
	}
3984
3985
	public static function sort_modules( $a, $b ) {
3986
		if ( $a['sort'] == $b['sort'] )
3987
			return 0;
3988
3989
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
3990
	}
3991
3992
	function ajax_recheck_ssl() {
3993
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
3994
		$result = Jetpack::permit_ssl( true );
3995
		wp_send_json( array(
3996
			'enabled' => $result,
3997
			'message' => get_transient( 'jetpack_https_test_message' )
3998
		) );
3999
	}
4000
4001
/* Client API */
4002
4003
	/**
4004
	 * Returns the requested Jetpack API URL
4005
	 *
4006
	 * @return string
4007
	 */
4008
	public static function api_url( $relative_url ) {
4009
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4010
	}
4011
4012
	/**
4013
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4014
	 */
4015
	public static function fix_url_for_bad_hosts( $url ) {
4016
		if ( 0 !== strpos( $url, 'https://' ) ) {
4017
			return $url;
4018
		}
4019
4020
		switch ( JETPACK_CLIENT__HTTPS ) {
4021
			case 'ALWAYS' :
4022
				return $url;
4023
			case 'NEVER' :
4024
				return set_url_scheme( $url, 'http' );
4025
			// default : case 'AUTO' :
4026
		}
4027
4028
		// we now return the unmodified SSL URL by default, as a security precaution
4029
		return $url;
4030
	}
4031
4032
	/**
4033
	 * Create a random secret for validating onboarding payload
4034
	 *
4035
	 * @return string Secret token
4036
	 */
4037
	public static function create_onboarding_token() {
4038
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4039
			$token = wp_generate_password( 32, false );
4040
			Jetpack_Options::update_option( 'onboarding', $token );
4041
		}
4042
4043
		return $token;
4044
	}
4045
4046
	/**
4047
	 * Remove the onboarding token
4048
	 *
4049
	 * @return bool True on success, false on failure
4050
	 */
4051
	public static function invalidate_onboarding_token() {
4052
		return Jetpack_Options::delete_option( 'onboarding' );
4053
	}
4054
4055
	/**
4056
	 * Validate an onboarding token for a specific action
4057
	 *
4058
	 * @return boolean True if token/action pair is accepted, false if not
4059
	 */
4060
	public static function validate_onboarding_token_action( $token, $action ) {
4061
		// Compare tokens, bail if tokens do not match
4062
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4063
			return false;
4064
		}
4065
4066
		// List of valid actions we can take
4067
		$valid_actions = array(
4068
			'/jetpack/v4/settings',
4069
		);
4070
4071
		// Whitelist the action
4072
		if ( ! in_array( $action, $valid_actions ) ) {
4073
			return false;
4074
		}
4075
4076
		return true;
4077
	}
4078
4079
	/**
4080
	 * Checks to see if the URL is using SSL to connect with Jetpack
4081
	 *
4082
	 * @since 2.3.3
4083
	 * @return boolean
4084
	 */
4085
	public static function permit_ssl( $force_recheck = false ) {
4086
		// Do some fancy tests to see if ssl is being supported
4087
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4088
			$message = '';
4089
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4090
				$ssl = 0;
4091
			} else {
4092
				switch ( JETPACK_CLIENT__HTTPS ) {
4093
					case 'NEVER':
4094
						$ssl = 0;
4095
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4096
						break;
4097
					case 'ALWAYS':
4098
					case 'AUTO':
4099
					default:
4100
						$ssl = 1;
4101
						break;
4102
				}
4103
4104
				// If it's not 'NEVER', test to see
4105
				if ( $ssl ) {
4106
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4107
						$ssl = 0;
4108
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4109
					} else {
4110
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4111
						if ( is_wp_error( $response ) ) {
4112
							$ssl = 0;
4113
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4114
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4115
							$ssl = 0;
4116
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4117
						}
4118
					}
4119
				}
4120
			}
4121
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4122
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4123
		}
4124
4125
		return (bool) $ssl;
4126
	}
4127
4128
	/*
4129
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4130
	 */
4131
	public function alert_auto_ssl_fail() {
4132
		if ( ! current_user_can( 'manage_options' ) )
4133
			return;
4134
4135
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4136
		?>
4137
4138
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4139
			<div class="jp-banner__content">
4140
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4141
				<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>
4142
				<p>
4143
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4144
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4145
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4146
				</p>
4147
				<p>
4148
					<?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' ),
4149
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4150
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4151
				</p>
4152
			</div>
4153
		</div>
4154
		<style>
4155
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4156
		</style>
4157
		<script type="text/javascript">
4158
			jQuery( document ).ready( function( $ ) {
4159
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4160
					var $this = $( this );
4161
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4162
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4163
					e.preventDefault();
4164
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4165
					$.post( ajaxurl, data )
4166
					  .done( function( response ) {
4167
					  	if ( response.enabled ) {
4168
					  		$( '#jetpack-ssl-warning' ).hide();
4169
					  	} else {
4170
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4171
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4172
					  	}
4173
					  }.bind( $this ) );
4174
				} );
4175
			} );
4176
		</script>
4177
4178
		<?php
4179
	}
4180
4181
	/**
4182
	 * Creates two secret tokens and the end of life timestamp for them.
4183
	 *
4184
	 * Note these tokens are unique per call, NOT static per site for connecting.
4185
	 *
4186
	 * @since 2.6
4187
	 * @return array
4188
	 */
4189
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4190
		if ( ! $user_id ) {
4191
			$user_id = get_current_user_id();
4192
		}
4193
4194
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
4195
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4196
4197
		if (
4198
			isset( $secrets[ $secret_name ] ) &&
4199
			$secrets[ $secret_name ]['exp'] > time()
4200
		) {
4201
			return $secrets[ $secret_name ];
4202
		}
4203
4204
		$secret_value = array(
4205
			'secret_1'  => wp_generate_password( 32, false ),
4206
			'secret_2'  => wp_generate_password( 32, false ),
4207
			'exp'       => time() + $exp,
4208
		);
4209
4210
		$secrets[ $secret_name ] = $secret_value;
4211
4212
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4213
		return $secrets[ $secret_name ];
4214
	}
4215
4216
	public static function get_secrets( $action, $user_id ) {
4217
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4218
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4219
4220
		if ( ! isset( $secrets[ $secret_name ] ) ) {
4221
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4222
		}
4223
4224
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
4225
			self::delete_secrets( $action, $user_id );
4226
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4227
		}
4228
4229
		return $secrets[ $secret_name ];
4230
	}
4231
4232
	public static function delete_secrets( $action, $user_id ) {
4233
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4234
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4235
		if ( isset( $secrets[ $secret_name ] ) ) {
4236
			unset( $secrets[ $secret_name ] );
4237
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4238
		}
4239
	}
4240
4241
	/**
4242
	 * Builds the timeout limit for queries talking with the wpcom servers.
4243
	 *
4244
	 * Based on local php max_execution_time in php.ini
4245
	 *
4246
	 * @since 2.6
4247
	 * @return int
4248
	 * @deprecated
4249
	 **/
4250
	public function get_remote_query_timeout_limit() {
4251
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4252
		return Jetpack::get_max_execution_time();
4253
	}
4254
4255
	/**
4256
	 * Takes the response from the Jetpack register new site endpoint and
4257
	 * verifies it worked properly.
4258
	 *
4259
	 * @since 2.6
4260
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4261
	 **/
4262
	public function validate_remote_register_response( $response ) {
4263
	  if ( is_wp_error( $response ) ) {
4264
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4265
		}
4266
4267
		$code   = wp_remote_retrieve_response_code( $response );
4268
		$entity = wp_remote_retrieve_body( $response );
4269
		if ( $entity )
4270
			$registration_response = json_decode( $entity );
4271
		else
4272
			$registration_response = false;
4273
4274
		$code_type = intval( $code / 100 );
4275
		if ( 5 == $code_type ) {
4276
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4277
		} elseif ( 408 == $code ) {
4278
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4279
		} elseif ( ! empty( $registration_response->error ) ) {
4280
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4281
				$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' );
4282
			} else {
4283
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4284
			}
4285
4286
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4287
		} elseif ( 200 != $code ) {
4288
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4289
		}
4290
4291
		// Jetpack ID error block
4292
		if ( empty( $registration_response->jetpack_id ) ) {
4293
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4294
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4295
			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 );
4296
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4297
			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 );
4298
		}
4299
4300
	    return $registration_response;
4301
	}
4302
	/**
4303
	 * @return bool|WP_Error
4304
	 */
4305
	public static function register() {
4306
		JetpackTracking::record_user_event( 'jpc_register_begin' );
4307
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4308
		$secrets = Jetpack::generate_secrets( 'register' );
4309
4310 View Code Duplication
		if (
4311
			empty( $secrets['secret_1'] ) ||
4312
			empty( $secrets['secret_2'] ) ||
4313
			empty( $secrets['exp'] )
4314
		) {
4315
			return new Jetpack_Error( 'missing_secrets' );
4316
		}
4317
4318
		// better to try (and fail) to set a higher timeout than this system
4319
		// supports than to have register fail for more users than it should
4320
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
4321
4322
		$gmt_offset = get_option( 'gmt_offset' );
4323
		if ( ! $gmt_offset ) {
4324
			$gmt_offset = 0;
4325
		}
4326
4327
		$stats_options = get_option( 'stats_options' );
4328
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4329
4330
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4331
4332
		$args = array(
4333
			'method'  => 'POST',
4334
			'body'    => array(
4335
				'siteurl'         => site_url(),
4336
				'home'            => home_url(),
4337
				'gmt_offset'      => $gmt_offset,
4338
				'timezone_string' => (string) get_option( 'timezone_string' ),
4339
				'site_name'       => (string) get_option( 'blogname' ),
4340
				'secret_1'        => $secrets['secret_1'],
4341
				'secret_2'        => $secrets['secret_2'],
4342
				'site_lang'       => get_locale(),
4343
				'timeout'         => $timeout,
4344
				'stats_id'        => $stats_id,
4345
				'state'           => get_current_user_id(),
4346
				'_ui'             => $tracks_identity['_ui'],
4347
				'_ut'             => $tracks_identity['_ut'],
4348
				'jetpack_version' => JETPACK__VERSION
4349
			),
4350
			'headers' => array(
4351
				'Accept' => 'application/json',
4352
			),
4353
			'timeout' => $timeout,
4354
		);
4355
4356
		self::apply_activation_source_to_args( $args['body'] );
4357
4358
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4359
4360
		// Make sure the response is valid and does not contain any Jetpack errors
4361
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4362
		if ( is_wp_error( $registration_details ) ) {
4363
			return $registration_details;
4364
		} elseif ( ! $registration_details ) {
4365
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
4366
		}
4367
4368 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4369
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
4370
		}
4371
4372
		if ( isset( $registration_details->jetpack_public ) ) {
4373
			$jetpack_public = (int) $registration_details->jetpack_public;
4374
		} else {
4375
			$jetpack_public = false;
4376
		}
4377
4378
		Jetpack_Options::update_options(
4379
			array(
4380
				'id'         => (int)    $registration_details->jetpack_id,
4381
				'blog_token' => (string) $registration_details->jetpack_secret,
4382
				'public'     => $jetpack_public,
4383
			)
4384
		);
4385
4386
		/**
4387
		 * Fires when a site is registered on WordPress.com.
4388
		 *
4389
		 * @since 3.7.0
4390
		 *
4391
		 * @param int $json->jetpack_id Jetpack Blog ID.
4392
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4393
		 * @param int|bool $jetpack_public Is the site public.
4394
		 */
4395
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
4396
4397
		// Initialize Jump Start for the first and only time.
4398
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4399
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4400
4401
			$jetpack = Jetpack::init();
4402
4403
			$jetpack->stat( 'jumpstart', 'unique-views' );
4404
			$jetpack->do_stats( 'server_side' );
4405
		};
4406
4407
		return true;
4408
	}
4409
4410
	/**
4411
	 * If the db version is showing something other that what we've got now, bump it to current.
4412
	 *
4413
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
4414
	 */
4415
	public static function maybe_set_version_option() {
4416
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4417
		if ( JETPACK__VERSION != $version ) {
4418
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4419
4420
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4421
				/** This action is documented in class.jetpack.php */
4422
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4423
			}
4424
4425
			return true;
4426
		}
4427
		return false;
4428
	}
4429
4430
/* Client Server API */
4431
4432
	/**
4433
	 * Loads the Jetpack XML-RPC client
4434
	 */
4435
	public static function load_xml_rpc_client() {
4436
		require_once ABSPATH . WPINC . '/class-IXR.php';
4437
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4438
	}
4439
4440
	/**
4441
	 * Resets the saved authentication state in between testing requests.
4442
	 */
4443
	public function reset_saved_auth_state() {
4444
		$this->xmlrpc_verification = null;
4445
		$this->rest_authentication_status = null;
4446
	}
4447
4448
	function verify_xml_rpc_signature() {
4449
		if ( $this->xmlrpc_verification ) {
4450
			return $this->xmlrpc_verification;
4451
		}
4452
4453
		// It's not for us
4454
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4455
			return false;
4456
		}
4457
4458
		@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...
4459
		if (
4460
			empty( $token_key )
4461
		||
4462
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4463
		) {
4464
			return false;
4465
		}
4466
4467
		if ( '0' === $user_id ) {
4468
			$token_type = 'blog';
4469
			$user_id = 0;
4470
		} else {
4471
			$token_type = 'user';
4472
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4473
				return false;
4474
			}
4475
			$user_id = (int) $user_id;
4476
4477
			$user = new WP_User( $user_id );
4478
			if ( ! $user || ! $user->exists() ) {
4479
				return false;
4480
			}
4481
		}
4482
4483
		$token = Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4484
		if ( ! $token ) {
4485
			return false;
4486
		}
4487
4488
		$token_check = "$token_key.";
4489
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4490
			return false;
4491
		}
4492
4493
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4494
4495
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4496
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4497
			$post_data   = $_POST;
4498
			$file_hashes = array();
4499
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4500
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4501
					continue;
4502
				}
4503
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4504
				$file_hashes[$post_data_key] = $post_data_value;
4505
			}
4506
4507
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4508
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4509
				$post_data[$post_data_key] = $post_data_value;
4510
			}
4511
4512
			ksort( $post_data );
4513
4514
			$body = http_build_query( stripslashes_deep( $post_data ) );
4515
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4516
			$body = file_get_contents( 'php://input' );
4517
		} else {
4518
			$body = null;
4519
		}
4520
4521
		$signature = $jetpack_signature->sign_current_request(
4522
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4523
		);
4524
4525
		if ( ! $signature ) {
4526
			return false;
4527
		} else if ( is_wp_error( $signature ) ) {
4528
			return $signature;
4529
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4530
			return false;
4531
		}
4532
4533
		$timestamp = (int) $_GET['timestamp'];
4534
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4535
4536
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4537
			return false;
4538
		}
4539
4540
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4541
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
4542
			if ( ! empty( $_GET['onboarding'] ) ) {
4543
				$jpo = $_GET;
4544
			} else {
4545
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
4546
			}
4547
4548
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4549
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4550
4551
			if (
4552
				isset( $jpo_user ) && isset( $jpo_token ) &&
4553
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
4554
				isset( $_GET['rest_route'] ) &&
4555
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
4556
			) {
4557
				$jpUser = get_user_by( 'email', $jpo_user );
4558
				if ( is_a( $jpUser, 'WP_User' ) ) {
4559
					wp_set_current_user( $jpUser->ID );
4560
					$user_can = is_multisite()
4561
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4562
						: current_user_can( 'manage_options' );
4563
					if ( $user_can ) {
4564
						$token_type = 'user';
4565
						$token->external_user_id = $jpUser->ID;
4566
					}
4567
				}
4568
			}
4569
		}
4570
4571
		$this->xmlrpc_verification = array(
4572
			'type'    => $token_type,
4573
			'user_id' => $token->external_user_id,
4574
		);
4575
4576
		return $this->xmlrpc_verification;
4577
	}
4578
4579
	/**
4580
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4581
	 */
4582
	function authenticate_jetpack( $user, $username, $password ) {
4583
		if ( is_a( $user, 'WP_User' ) ) {
4584
			return $user;
4585
		}
4586
4587
		$token_details = $this->verify_xml_rpc_signature();
4588
4589
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4590
			return $user;
4591
		}
4592
4593
		if ( 'user' !== $token_details['type'] ) {
4594
			return $user;
4595
		}
4596
4597
		if ( ! $token_details['user_id'] ) {
4598
			return $user;
4599
		}
4600
4601
		nocache_headers();
4602
4603
		return new WP_User( $token_details['user_id'] );
4604
	}
4605
4606
	// Authenticates requests from Jetpack server to WP REST API endpoints.
4607
	// Uses the existing XMLRPC request signing implementation.
4608
	function wp_rest_authenticate( $user ) {
4609
		if ( ! empty( $user ) ) {
4610
			// Another authentication method is in effect.
4611
			return $user;
4612
		}
4613
4614
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
4615
			// Nothing to do for this authentication method.
4616
			return null;
4617
		}
4618
4619
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
4620
			// Nothing to do for this authentication method.
4621
			return null;
4622
		}
4623
4624
		// Ensure that we always have the request body available.  At this
4625
		// point, the WP REST API code to determine the request body has not
4626
		// run yet.  That code may try to read from 'php://input' later, but
4627
		// this can only be done once per request in PHP versions prior to 5.6.
4628
		// So we will go ahead and perform this read now if needed, and save
4629
		// the request body where both the Jetpack signature verification code
4630
		// and the WP REST API code can see it.
4631
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
4632
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
4633
		}
4634
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4635
4636
		// Only support specific request parameters that have been tested and
4637
		// are known to work with signature verification.  A different method
4638
		// can be passed to the WP REST API via the '?_method=' parameter if
4639
		// needed.
4640
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
4641
			$this->rest_authentication_status = new WP_Error(
4642
				'rest_invalid_request',
4643
				__( 'This request method is not supported.', 'jetpack' ),
4644
				array( 'status' => 400 )
4645
			);
4646
			return null;
4647
		}
4648
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
4649
			$this->rest_authentication_status = new WP_Error(
4650
				'rest_invalid_request',
4651
				__( 'This request method does not support body parameters.', 'jetpack' ),
4652
				array( 'status' => 400 )
4653
			);
4654
			return null;
4655
		}
4656
4657
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
4658
			$content_type = $_SERVER['CONTENT_TYPE'];
4659
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
4660
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
4661
		}
4662
4663
		if (
4664
			isset( $content_type ) &&
4665
			$content_type !== 'application/x-www-form-urlencoded' &&
4666
			$content_type !== 'application/json'
4667
		) {
4668
			$this->rest_authentication_status = new WP_Error(
4669
				'rest_invalid_request',
4670
				__( 'This Content-Type is not supported.', 'jetpack' ),
4671
				array( 'status' => 400 )
4672
			);
4673
			return null;
4674
		}
4675
4676
		$verified = $this->verify_xml_rpc_signature();
4677
4678
		if ( is_wp_error( $verified ) ) {
4679
			$this->rest_authentication_status = $verified;
4680
			return null;
4681
		}
4682
4683
		if (
4684
			$verified &&
4685
			isset( $verified['type'] ) &&
4686
			'user' === $verified['type'] &&
4687
			! empty( $verified['user_id'] )
4688
		) {
4689
			// Authentication successful.
4690
			$this->rest_authentication_status = true;
4691
			return $verified['user_id'];
4692
		}
4693
4694
		// Something else went wrong.  Probably a signature error.
4695
		$this->rest_authentication_status = new WP_Error(
4696
			'rest_invalid_signature',
4697
			__( 'The request is not signed correctly.', 'jetpack' ),
4698
			array( 'status' => 400 )
4699
		);
4700
		return null;
4701
	}
4702
4703
	/**
4704
	 * Report authentication status to the WP REST API.
4705
	 *
4706
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
4707
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
4708
	 */
4709
	public function wp_rest_authentication_errors( $value ) {
4710
		if ( $value !== null ) {
4711
			return $value;
4712
		}
4713
		return $this->rest_authentication_status;
4714
	}
4715
4716
	function add_nonce( $timestamp, $nonce ) {
4717
		global $wpdb;
4718
		static $nonces_used_this_request = array();
4719
4720
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4721
			return $nonces_used_this_request["$timestamp:$nonce"];
4722
		}
4723
4724
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4725
		$timestamp = (int) $timestamp;
4726
		$nonce     = esc_sql( $nonce );
4727
4728
		// Raw query so we can avoid races: add_option will also update
4729
		$show_errors = $wpdb->show_errors( false );
4730
4731
		$old_nonce = $wpdb->get_row(
4732
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4733
		);
4734
4735
		if ( is_null( $old_nonce ) ) {
4736
			$return = $wpdb->query(
4737
				$wpdb->prepare(
4738
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4739
					"jetpack_nonce_{$timestamp}_{$nonce}",
4740
					time(),
4741
					'no'
4742
				)
4743
			);
4744
		} else {
4745
			$return = false;
4746
		}
4747
4748
		$wpdb->show_errors( $show_errors );
4749
4750
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4751
4752
		return $return;
4753
	}
4754
4755
	/**
4756
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4757
	 * Capture it here so we can verify the signature later.
4758
	 */
4759
	function xmlrpc_methods( $methods ) {
4760
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4761
		return $methods;
4762
	}
4763
4764
	function public_xmlrpc_methods( $methods ) {
4765
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4766
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4767
		}
4768
		return $methods;
4769
	}
4770
4771
	function jetpack_getOptions( $args ) {
4772
		global $wp_xmlrpc_server;
4773
4774
		$wp_xmlrpc_server->escape( $args );
4775
4776
		$username	= $args[1];
4777
		$password	= $args[2];
4778
4779
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4780
			return $wp_xmlrpc_server->error;
4781
		}
4782
4783
		$options = array();
4784
		$user_data = $this->get_connected_user_data();
4785
		if ( is_array( $user_data ) ) {
4786
			$options['jetpack_user_id'] = array(
4787
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4788
				'readonly'      => true,
4789
				'value'         => $user_data['ID'],
4790
			);
4791
			$options['jetpack_user_login'] = array(
4792
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4793
				'readonly'      => true,
4794
				'value'         => $user_data['login'],
4795
			);
4796
			$options['jetpack_user_email'] = array(
4797
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4798
				'readonly'      => true,
4799
				'value'         => $user_data['email'],
4800
			);
4801
			$options['jetpack_user_site_count'] = array(
4802
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4803
				'readonly'      => true,
4804
				'value'         => $user_data['site_count'],
4805
			);
4806
		}
4807
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4808
		$args = stripslashes_deep( $args );
4809
		return $wp_xmlrpc_server->wp_getOptions( $args );
4810
	}
4811
4812
	function xmlrpc_options( $options ) {
4813
		$jetpack_client_id = false;
4814
		if ( self::is_active() ) {
4815
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4816
		}
4817
		$options['jetpack_version'] = array(
4818
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4819
				'readonly'      => true,
4820
				'value'         => JETPACK__VERSION,
4821
		);
4822
4823
		$options['jetpack_client_id'] = array(
4824
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4825
				'readonly'      => true,
4826
				'value'         => $jetpack_client_id,
4827
		);
4828
		return $options;
4829
	}
4830
4831
	public static function clean_nonces( $all = false ) {
4832
		global $wpdb;
4833
4834
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4835
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4836
4837
		if ( true !== $all ) {
4838
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4839
			$sql_args[] = time() - 3600;
4840
		}
4841
4842
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4843
4844
		$sql = $wpdb->prepare( $sql, $sql_args );
4845
4846
		for ( $i = 0; $i < 1000; $i++ ) {
4847
			if ( ! $wpdb->query( $sql ) ) {
4848
				break;
4849
			}
4850
		}
4851
	}
4852
4853
	/**
4854
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4855
	 * SET: state( $key, $value );
4856
	 * GET: $value = state( $key );
4857
	 *
4858
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

Loading history...
4859
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

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

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

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

Loading history...
4860
	 * @param bool $restate private
4861
	 */
4862
	public static function state( $key = null, $value = null, $restate = false ) {
4863
		static $state = array();
4864
		static $path, $domain;
4865
		if ( ! isset( $path ) ) {
4866
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4867
			$admin_url = Jetpack::admin_url();
4868
			$bits      = parse_url( $admin_url );
4869
4870
			if ( is_array( $bits ) ) {
4871
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4872
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4873
			} else {
4874
				$path = $domain = null;
4875
			}
4876
		}
4877
4878
		// Extract state from cookies and delete cookies
4879
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4880
			$yum = $_COOKIE[ 'jetpackState' ];
4881
			unset( $_COOKIE[ 'jetpackState' ] );
4882
			foreach ( $yum as $k => $v ) {
4883
				if ( strlen( $v ) )
4884
					$state[ $k ] = $v;
4885
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4886
			}
4887
		}
4888
4889
		if ( $restate ) {
4890
			foreach ( $state as $k => $v ) {
4891
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4892
			}
4893
			return;
4894
		}
4895
4896
		// Get a state variable
4897
		if ( isset( $key ) && ! isset( $value ) ) {
4898
			if ( array_key_exists( $key, $state ) )
4899
				return $state[ $key ];
4900
			return null;
4901
		}
4902
4903
		// Set a state variable
4904
		if ( isset ( $key ) && isset( $value ) ) {
4905
			if( is_array( $value ) && isset( $value[0] ) ) {
4906
				$value = $value[0];
4907
			}
4908
			$state[ $key ] = $value;
4909
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4910
		}
4911
	}
4912
4913
	public static function restate() {
4914
		Jetpack::state( null, null, true );
4915
	}
4916
4917
	public static function check_privacy( $file ) {
4918
		static $is_site_publicly_accessible = null;
4919
4920
		if ( is_null( $is_site_publicly_accessible ) ) {
4921
			$is_site_publicly_accessible = false;
4922
4923
			Jetpack::load_xml_rpc_client();
4924
			$rpc = new Jetpack_IXR_Client();
4925
4926
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4927
			if ( $success ) {
4928
				$response = $rpc->getResponse();
4929
				if ( $response ) {
4930
					$is_site_publicly_accessible = true;
4931
				}
4932
			}
4933
4934
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4935
		}
4936
4937
		if ( $is_site_publicly_accessible ) {
4938
			return;
4939
		}
4940
4941
		$module_slug = self::get_module_slug( $file );
4942
4943
		$privacy_checks = Jetpack::state( 'privacy_checks' );
4944
		if ( ! $privacy_checks ) {
4945
			$privacy_checks = $module_slug;
4946
		} else {
4947
			$privacy_checks .= ",$module_slug";
4948
		}
4949
4950
		Jetpack::state( 'privacy_checks', $privacy_checks );
4951
	}
4952
4953
	/**
4954
	 * Helper method for multicall XMLRPC.
4955
	 */
4956
	public static function xmlrpc_async_call() {
4957
		global $blog_id;
4958
		static $clients = array();
4959
4960
		$client_blog_id = is_multisite() ? $blog_id : 0;
4961
4962
		if ( ! isset( $clients[$client_blog_id] ) ) {
4963
			Jetpack::load_xml_rpc_client();
4964
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
4965
			if ( function_exists( 'ignore_user_abort' ) ) {
4966
				ignore_user_abort( true );
4967
			}
4968
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
4969
		}
4970
4971
		$args = func_get_args();
4972
4973
		if ( ! empty( $args[0] ) ) {
4974
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
4975
		} elseif ( is_multisite() ) {
4976
			foreach ( $clients as $client_blog_id => $client ) {
4977
				if ( ! $client_blog_id || empty( $client->calls ) ) {
4978
					continue;
4979
				}
4980
4981
				$switch_success = switch_to_blog( $client_blog_id, true );
4982
				if ( ! $switch_success ) {
4983
					continue;
4984
				}
4985
4986
				flush();
4987
				$client->query();
4988
4989
				restore_current_blog();
4990
			}
4991
		} else {
4992
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
4993
				flush();
4994
				$clients[0]->query();
4995
			}
4996
		}
4997
	}
4998
4999
/* JSON API Authorization */
5000
5001
	/**
5002
	 * Handles the login action for Authorizing the JSON API
5003
	 */
5004
	function login_form_json_api_authorization() {
5005
		$this->verify_json_api_authorization_request();
5006
5007
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5008
5009
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5010
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5011
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5012
	}
5013
5014
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5015
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5016
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5017
			return $url;
5018
		}
5019
5020
		$parsed_url = parse_url( $url );
5021
		$url = strtok( $url, '?' );
5022
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5023
		if ( ! empty( $parsed_url['query'] ) )
5024
			$url .= "&{$parsed_url['query']}";
5025
5026
		return $url;
5027
	}
5028
5029
	// Make sure the POSTed request is handled by the same action
5030
	function preserve_action_in_login_form_for_json_api_authorization() {
5031
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5032
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5033
	}
5034
5035
	// If someone logs in to approve API access, store the Access Code in usermeta
5036
	function store_json_api_authorization_token( $user_login, $user ) {
5037
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5038
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5039
		$token = wp_generate_password( 32, false );
5040
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5041
	}
5042
5043
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5044
	function allow_wpcom_public_api_domain( $domains ) {
5045
		$domains[] = 'public-api.wordpress.com';
5046
		return $domains;
5047
	}
5048
5049
	// Add all wordpress.com environments to the safe redirect whitelist
5050
	function allow_wpcom_environments( $domains ) {
5051
		$domains[] = 'wordpress.com';
5052
		$domains[] = 'wpcalypso.wordpress.com';
5053
		$domains[] = 'horizon.wordpress.com';
5054
		$domains[] = 'calypso.localhost';
5055
		return $domains;
5056
	}
5057
5058
	// Add the Access Code details to the public-api.wordpress.com redirect
5059
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5060
		return add_query_arg(
5061
			urlencode_deep(
5062
				array(
5063
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5064
					'jetpack-user-id' => (int) $user->ID,
5065
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5066
				)
5067
			),
5068
			$redirect_to
5069
		);
5070
	}
5071
5072
5073
	/**
5074
	 * Verifies the request by checking the signature
5075
	 *
5076
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5077
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5078
	 *
5079
	 * @param null|array $environment
5080
	 */
5081
	function verify_json_api_authorization_request( $environment = null ) {
5082
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5083
5084
		$environment = is_null( $environment )
5085
			? $_REQUEST
5086
			: $environment;
5087
5088
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envToken is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5089
		$token = Jetpack_Data::get_access_token( $envUserId );
5090
		if ( ! $token || empty( $token->secret ) ) {
5091
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5092
		}
5093
5094
		$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' );
5095
5096
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5097
5098
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5099
			$signature = $jetpack_signature->sign_request(
5100
				$environment['token'],
5101
				$environment['timestamp'],
5102
				$environment['nonce'],
5103
				'',
5104
				'GET',
5105
				$environment['jetpack_json_api_original_query'],
5106
				null,
5107
				true
5108
			);
5109
		} else {
5110
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5111
		}
5112
5113
		if ( ! $signature ) {
5114
			wp_die( $die_error );
5115
		} else if ( is_wp_error( $signature ) ) {
5116
			wp_die( $die_error );
5117
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5118
			if ( is_ssl() ) {
5119
				// 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
5120
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5121
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5122
					wp_die( $die_error );
5123
				}
5124
			} else {
5125
				wp_die( $die_error );
5126
			}
5127
		}
5128
5129
		$timestamp = (int) $environment['timestamp'];
5130
		$nonce     = stripslashes( (string) $environment['nonce'] );
5131
5132
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5133
			// De-nonce the nonce, at least for 5 minutes.
5134
			// 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)
5135
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5136
			if ( $old_nonce_time < time() - 300 ) {
5137
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5138
			}
5139
		}
5140
5141
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5142
		$data_filters = array(
5143
			'state'        => 'opaque',
5144
			'client_id'    => 'int',
5145
			'client_title' => 'string',
5146
			'client_image' => 'url',
5147
		);
5148
5149
		foreach ( $data_filters as $key => $sanitation ) {
5150
			if ( ! isset( $data->$key ) ) {
5151
				wp_die( $die_error );
5152
			}
5153
5154
			switch ( $sanitation ) {
5155
			case 'int' :
5156
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5157
				break;
5158
			case 'opaque' :
5159
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5160
				break;
5161
			case 'string' :
5162
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5163
				break;
5164
			case 'url' :
5165
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5166
				break;
5167
			}
5168
		}
5169
5170
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5171
			wp_die( $die_error );
5172
		}
5173
	}
5174
5175
	function login_message_json_api_authorization( $message ) {
5176
		return '<p class="message">' . sprintf(
5177
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5178
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5179
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5180
	}
5181
5182
	/**
5183
	 * Pings the WordPress.com Mirror Site for the specified options.
5184
	 *
5185
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5186
	 *
5187
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5188
	 */
5189
	public function get_cloud_site_options( $option_names ) {
5190
		$option_names = array_filter( (array) $option_names, 'is_string' );
5191
5192
		Jetpack::load_xml_rpc_client();
5193
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5194
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5195
		if ( $xml->isError() ) {
5196
			return array(
5197
				'error_code' => $xml->getErrorCode(),
5198
				'error_msg'  => $xml->getErrorMessage(),
5199
			);
5200
		}
5201
		$cloud_site_options = $xml->getResponse();
5202
5203
		return $cloud_site_options;
5204
	}
5205
5206
	/**
5207
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5208
	 *
5209
	 * @since 4.4.0
5210
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5211
	 *
5212
	 * @param array $response
5213
	 * @return array Array of the local urls, wpcom urls, and error code
5214
	 */
5215
	public static function get_sync_error_idc_option( $response = array() ) {
5216
		// Since the local options will hit the database directly, store the values
5217
		// in a transient to allow for autoloading and caching on subsequent views.
5218
		$local_options = get_transient( 'jetpack_idc_local' );
5219
		if ( false === $local_options ) {
5220
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
5221
			$local_options = array(
5222
				'home'    => Jetpack_Sync_Functions::home_url(),
5223
				'siteurl' => Jetpack_Sync_Functions::site_url(),
5224
			);
5225
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5226
		}
5227
5228
		$options = array_merge( $local_options, $response );
5229
5230
		$returned_values = array();
5231
		foreach( $options as $key => $option ) {
5232
			if ( 'error_code' === $key ) {
5233
				$returned_values[ $key ] = $option;
5234
				continue;
5235
			}
5236
5237
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5238
				continue;
5239
			}
5240
5241
			$returned_values[ $key ] = $normalized_url;
5242
		}
5243
5244
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5245
5246
		return $returned_values;
5247
	}
5248
5249
	/**
5250
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5251
	 * If set to true, the site will be put into staging mode.
5252
	 *
5253
	 * @since 4.3.2
5254
	 * @return bool
5255
	 */
5256
	public static function sync_idc_optin() {
5257
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5258
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5259
		} else {
5260
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5261
		}
5262
5263
		/**
5264
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5265
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5266
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5267
		 *
5268
		 * @since 4.3.2
5269
		 *
5270
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5271
		 */
5272
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5273
	}
5274
5275
	/**
5276
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5277
	 *
5278
	 * @since 4.4.0
5279
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5280
	 *
5281
	 * @return bool
5282
	 */
5283
	public static function validate_sync_error_idc_option() {
5284
		$is_valid = false;
5285
5286
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5287
		if ( false === $idc_allowed ) {
5288
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5289
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5290
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5291
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5292
				$transient_duration = HOUR_IN_SECONDS;
5293
			} else {
5294
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5295
				$idc_allowed = '1';
5296
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5297
			}
5298
5299
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5300
		}
5301
5302
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5303
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5304
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5305
			$local_options = self::get_sync_error_idc_option();
5306
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5307
				$is_valid = true;
5308
			}
5309
		}
5310
5311
		/**
5312
		 * Filters whether the sync_error_idc option is valid.
5313
		 *
5314
		 * @since 4.4.0
5315
		 *
5316
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5317
		 */
5318
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5319
5320
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5321
			// Since the option exists, and did not validate, delete it
5322
			Jetpack_Options::delete_option( 'sync_error_idc' );
5323
		}
5324
5325
		return $is_valid;
5326
	}
5327
5328
	/**
5329
	 * Maybe Use a .min.css stylesheet, maybe not.
5330
	 *
5331
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5332
	 */
5333
	public static function maybe_min_asset( $url, $path, $plugin ) {
5334
		// Short out on things trying to find actual paths.
5335
		if ( ! $path || empty( $plugin ) ) {
5336
			return $url;
5337
		}
5338
5339
		$path = ltrim( $path, '/' );
5340
5341
		// Strip out the abspath.
5342
		$base = dirname( plugin_basename( $plugin ) );
5343
5344
		// Short out on non-Jetpack assets.
5345
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5346
			return $url;
5347
		}
5348
5349
		// File name parsing.
5350
		$file              = "{$base}/{$path}";
5351
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5352
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5353
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5354
		$extension         = array_shift( $file_name_parts_r );
5355
5356
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5357
			// Already pointing at the minified version.
5358
			if ( 'min' === $file_name_parts_r[0] ) {
5359
				return $url;
5360
			}
5361
5362
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5363
			if ( file_exists( $min_full_path ) ) {
5364
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5365
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5366
				if ( 'css' === $extension ) {
5367
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5368
					self::$min_assets[ $key ] = $path;
5369
				}
5370
			}
5371
		}
5372
5373
		return $url;
5374
	}
5375
5376
	/**
5377
	 * If the asset is minified, let's flag .min as the suffix.
5378
	 *
5379
	 * Attached to `style_loader_src` filter.
5380
	 *
5381
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
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...
5382
	 * @param string $handle The registered handle of the script in question.
5383
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
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...
5384
	 */
5385
	public static function set_suffix_on_min( $src, $handle ) {
5386
		if ( false === strpos( $src, '.min.css' ) ) {
5387
			return $src;
5388
		}
5389
5390
		if ( ! empty( self::$min_assets ) ) {
5391
			foreach ( self::$min_assets as $file => $path ) {
5392
				if ( false !== strpos( $src, $file ) ) {
5393
					wp_style_add_data( $handle, 'suffix', '.min' );
5394
					return $src;
5395
				}
5396
			}
5397
		}
5398
5399
		return $src;
5400
	}
5401
5402
	/**
5403
	 * Maybe inlines a stylesheet.
5404
	 *
5405
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5406
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5407
	 *
5408
	 * Attached to `style_loader_tag` filter.
5409
	 *
5410
	 * @param string $tag The tag that would link to the external asset.
5411
	 * @param string $handle The registered handle of the script in question.
5412
	 *
5413
	 * @return string
5414
	 */
5415
	public static function maybe_inline_style( $tag, $handle ) {
5416
		global $wp_styles;
5417
		$item = $wp_styles->registered[ $handle ];
5418
5419
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5420
			return $tag;
5421
		}
5422
5423
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5424
			$href = $matches[1];
5425
			// Strip off query string
5426
			if ( $pos = strpos( $href, '?' ) ) {
5427
				$href = substr( $href, 0, $pos );
5428
			}
5429
			// Strip off fragment
5430
			if ( $pos = strpos( $href, '#' ) ) {
5431
				$href = substr( $href, 0, $pos );
5432
			}
5433
		} else {
5434
			return $tag;
5435
		}
5436
5437
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5438
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5439
			return $tag;
5440
		}
5441
5442
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5443
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5444
			// And this isn't the pass that actually deals with the RTL version...
5445
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5446
				// Short out, as the RTL version will deal with it in a moment.
5447
				return $tag;
5448
			}
5449
		}
5450
5451
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5452
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5453
		if ( $css ) {
5454
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5455
			if ( empty( $item->extra['after'] ) ) {
5456
				wp_add_inline_style( $handle, $css );
5457
			} else {
5458
				array_unshift( $item->extra['after'], $css );
5459
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5460
			}
5461
		}
5462
5463
		return $tag;
5464
	}
5465
5466
	/**
5467
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5468
	 */
5469
	public function deprecated_hooks() {
5470
		global $wp_filter;
5471
5472
		/*
5473
		 * Format:
5474
		 * deprecated_filter_name => replacement_name
5475
		 *
5476
		 * If there is no replacement, use null for replacement_name
5477
		 */
5478
		$deprecated_list = array(
5479
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5480
			'wpl_sharing_2014_1'                                     => null,
5481
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5482
			'jetpack_identity_crisis_options_to_check'               => null,
5483
			'update_option_jetpack_single_user_site'                 => null,
5484
			'audio_player_default_colors'                            => null,
5485
			'add_option_jetpack_featured_images_enabled'             => null,
5486
			'add_option_jetpack_update_details'                      => null,
5487
			'add_option_jetpack_updates'                             => null,
5488
			'add_option_jetpack_network_name'                        => null,
5489
			'add_option_jetpack_network_allow_new_registrations'     => null,
5490
			'add_option_jetpack_network_add_new_users'               => null,
5491
			'add_option_jetpack_network_site_upload_space'           => null,
5492
			'add_option_jetpack_network_upload_file_types'           => null,
5493
			'add_option_jetpack_network_enable_administration_menus' => null,
5494
			'add_option_jetpack_is_multi_site'                       => null,
5495
			'add_option_jetpack_is_main_network'                     => null,
5496
			'add_option_jetpack_main_network_site'                   => null,
5497
			'jetpack_sync_all_registered_options'                    => null,
5498
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5499
			'jetpack_is_post_mailable'                               => null,
5500
			'jetpack_seo_site_host'                                  => null,
5501
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
5502
			'jetpack_holiday_snow_option_name'                       => null,
5503
			'jetpack_holiday_chance_of_snow'                         => null,
5504
			'jetpack_holiday_snow_js_url'                            => null,
5505
			'jetpack_is_holiday_snow_season'                         => null,
5506
			'jetpack_holiday_snow_option_updated'                    => null,
5507
			'jetpack_holiday_snowing'                                => null,
5508
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
5509
			'jetpack_cache_plans'                                    => null,
5510
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
5511
		);
5512
5513
		// This is a silly loop depth. Better way?
5514
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5515
			if ( has_action( $hook ) ) {
5516
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
5517
					foreach( $values AS $hooked ) {
5518
						if ( is_callable( $hooked['function'] ) ) {
5519
							$function_name = 'an anonymous function';
5520
						} else {
5521
							$function_name = $hooked['function'];
5522
						}
5523
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
5524
					}
5525
				}
5526
			}
5527
		}
5528
	}
5529
5530
	/**
5531
	 * This methods removes all of the registered css files on the front end
5532
	 * from Jetpack in favor of using a single file. In effect "imploding"
5533
	 * all the files into one file.
5534
	 *
5535
	 * Pros:
5536
	 * - Uses only ONE css asset connection instead of 15
5537
	 * - Saves a minimum of 56k
5538
	 * - Reduces server load
5539
	 * - Reduces time to first painted byte
5540
	 *
5541
	 * Cons:
5542
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5543
	 *		should not cause any issues with themes.
5544
	 * - Plugins/themes dequeuing styles no longer do anything. See
5545
	 *		jetpack_implode_frontend_css filter for a workaround
5546
	 *
5547
	 * For some situations developers may wish to disable css imploding and
5548
	 * instead operate in legacy mode where each file loads seperately and
5549
	 * can be edited individually or dequeued. This can be accomplished with
5550
	 * the following line:
5551
	 *
5552
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5553
	 *
5554
	 * @since 3.2
5555
	 **/
5556
	public function implode_frontend_css( $travis_test = false ) {
5557
		$do_implode = true;
5558
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5559
			$do_implode = false;
5560
		}
5561
5562
		/**
5563
		 * Allow CSS to be concatenated into a single jetpack.css file.
5564
		 *
5565
		 * @since 3.2.0
5566
		 *
5567
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5568
		 */
5569
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5570
5571
		// Do not use the imploded file when default behaviour was altered through the filter
5572
		if ( ! $do_implode ) {
5573
			return;
5574
		}
5575
5576
		// We do not want to use the imploded file in dev mode, or if not connected
5577
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5578
			if ( ! $travis_test ) {
5579
				return;
5580
			}
5581
		}
5582
5583
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5584
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5585
			return;
5586
		}
5587
5588
		/*
5589
		 * Now we assume Jetpack is connected and able to serve the single
5590
		 * file.
5591
		 *
5592
		 * In the future there will be a check here to serve the file locally
5593
		 * or potentially from the Jetpack CDN
5594
		 *
5595
		 * For now:
5596
		 * - Enqueue a single imploded css file
5597
		 * - Zero out the style_loader_tag for the bundled ones
5598
		 * - Be happy, drink scotch
5599
		 */
5600
5601
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5602
5603
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5604
5605
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5606
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5607
	}
5608
5609
	function concat_remove_style_loader_tag( $tag, $handle ) {
5610
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5611
			$tag = '';
5612
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5613
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5614
			}
5615
		}
5616
5617
		return $tag;
5618
	}
5619
5620
	/*
5621
	 * Check the heartbeat data
5622
	 *
5623
	 * Organizes the heartbeat data by severity.  For example, if the site
5624
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5625
	 *
5626
	 * Data will be added to "caution" array, if it either:
5627
	 *  - Out of date Jetpack version
5628
	 *  - Out of date WP version
5629
	 *  - Out of date PHP version
5630
	 *
5631
	 * $return array $filtered_data
5632
	 */
5633
	public static function jetpack_check_heartbeat_data() {
5634
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5635
5636
		$good    = array();
5637
		$caution = array();
5638
		$bad     = array();
5639
5640
		foreach ( $raw_data as $stat => $value ) {
5641
5642
			// Check jetpack version
5643
			if ( 'version' == $stat ) {
5644
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5645
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5646
					continue;
5647
				}
5648
			}
5649
5650
			// Check WP version
5651
			if ( 'wp-version' == $stat ) {
5652
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5653
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5654
					continue;
5655
				}
5656
			}
5657
5658
			// Check PHP version
5659
			if ( 'php-version' == $stat ) {
5660
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5661
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5662
					continue;
5663
				}
5664
			}
5665
5666
			// Check ID crisis
5667
			if ( 'identitycrisis' == $stat ) {
5668
				if ( 'yes' == $value ) {
5669
					$bad[ $stat ] = $value;
5670
					continue;
5671
				}
5672
			}
5673
5674
			// The rest are good :)
5675
			$good[ $stat ] = $value;
5676
		}
5677
5678
		$filtered_data = array(
5679
			'good'    => $good,
5680
			'caution' => $caution,
5681
			'bad'     => $bad
5682
		);
5683
5684
		return $filtered_data;
5685
	}
5686
5687
	/**
5688
	 * Check if an option of a Jetpack module has been updated.
5689
	 *
5690
	 * If any module option has been updated before Jump Start has been dismissed,
5691
	 * update the 'jumpstart' option so we can hide Jump Start.
5692
	 *
5693
	 * @param string $option_name
5694
	 *
5695
	 * @return bool
5696
	 */
5697
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5698
		// Bail if Jump Start has already been dismissed
5699
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
5700
			return false;
5701
		}
5702
5703
		$jetpack = Jetpack::init();
5704
5705
		// Manual build of module options
5706
		$option_names = self::get_jetpack_options_for_reset();
5707
5708
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5709
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5710
5711
			//Jump start is being dismissed send data to MC Stats
5712
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5713
5714
			$jetpack->do_stats( 'server_side' );
5715
		}
5716
5717
	}
5718
5719
	/**
5720
	 * Stores and prints out domains to prefetch for page speed optimization.
5721
	 *
5722
	 * @param mixed $new_urls
5723
	 */
5724
	public static function dns_prefetch( $new_urls = null ) {
5725
		static $prefetch_urls = array();
5726
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
5727
			echo "\r\n";
5728
			foreach ( $prefetch_urls as $this_prefetch_url ) {
5729
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
5730
			}
5731
		} elseif ( ! empty( $new_urls ) ) {
5732
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
5733
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
5734
			}
5735
			foreach ( (array) $new_urls as $this_new_url ) {
5736
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
5737
			}
5738
			$prefetch_urls = array_unique( $prefetch_urls );
5739
		}
5740
	}
5741
5742
	public function wp_dashboard_setup() {
5743
		if ( self::is_active() ) {
5744
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
5745
		}
5746
5747
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
5748
			wp_add_dashboard_widget(
5749
				'jetpack_summary_widget',
5750
				esc_html__( 'Site Stats', 'jetpack' ),
5751
				array( __CLASS__, 'dashboard_widget' )
5752
			);
5753
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
5754
5755
			// If we're inactive and not in development mode, sort our box to the top.
5756
			if ( ! self::is_active() && ! self::is_development_mode() ) {
5757
				global $wp_meta_boxes;
5758
5759
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
5760
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
5761
5762
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
5763
			}
5764
		}
5765
	}
5766
5767
	/**
5768
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5769
	 * @return mixed
5770
	 */
5771
	function get_user_option_meta_box_order_dashboard( $sorted ) {
5772
		if ( ! is_array( $sorted ) ) {
5773
			return $sorted;
5774
		}
5775
5776
		foreach ( $sorted as $box_context => $ids ) {
5777
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
5778
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
5779
				continue;
5780
			}
5781
5782
			$ids_array = explode( ',', $ids );
5783
			$key = array_search( 'dashboard_stats', $ids_array );
5784
5785
			if ( false !== $key ) {
5786
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
5787
				$ids_array[ $key ] = 'jetpack_summary_widget';
5788
				$sorted[ $box_context ] = implode( ',', $ids_array );
5789
				// We've found it, stop searching, and just return.
5790
				break;
5791
			}
5792
		}
5793
5794
		return $sorted;
5795
	}
5796
5797
	public static function dashboard_widget() {
5798
		/**
5799
		 * Fires when the dashboard is loaded.
5800
		 *
5801
		 * @since 3.4.0
5802
		 */
5803
		do_action( 'jetpack_dashboard_widget' );
5804
	}
5805
5806
	public static function dashboard_widget_footer() {
5807
		?>
5808
		<footer>
5809
5810
		<div class="protect">
5811
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
5812
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
5813
				<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>
5814
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
5815
				<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' ); ?>">
5816
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
5817
				</a>
5818
			<?php else : ?>
5819
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
5820
			<?php endif; ?>
5821
		</div>
5822
5823
		<div class="akismet">
5824
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
5825
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
5826
				<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>
5827
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
5828
				<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">
5829
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
5830
				</a>
5831
			<?php else : ?>
5832
				<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>
5833
			<?php endif; ?>
5834
		</div>
5835
5836
		</footer>
5837
		<?php
5838
	}
5839
5840
	/*
5841
	 * Adds a "blank" column in the user admin table to display indication of user connection.
5842
	 */
5843
	function jetpack_icon_user_connected( $columns ) {
5844
		$columns['user_jetpack'] = '';
5845
		return $columns;
5846
	}
5847
5848
	/*
5849
	 * Show Jetpack icon if the user is linked.
5850
	 */
5851
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
5852
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
5853
			$emblem_html = sprintf(
5854
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
5855
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
5856
				Jetpack::get_jp_emblem()
5857
			);
5858
			return $emblem_html;
5859
		}
5860
5861
		return $val;
5862
	}
5863
5864
	/*
5865
	 * Style the Jetpack user column
5866
	 */
5867
	function jetpack_user_col_style() {
5868
		global $current_screen;
5869
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
5870
			<style>
5871
				.fixed .column-user_jetpack {
5872
					width: 21px;
5873
				}
5874
				.jp-emblem-user-admin svg {
5875
					width: 20px;
5876
					height: 20px;
5877
				}
5878
				.jp-emblem-user-admin path {
5879
					fill: #00BE28;
5880
				}
5881
			</style>
5882
		<?php }
5883
	}
5884
5885
	/**
5886
	 * Checks if one or more function names is in debug_backtrace
5887
	 *
5888
	 * @param $names Mixed string name of function or array of string names of functions
5889
	 *
5890
	 * @return bool
5891
	 */
5892
	public static function is_function_in_backtrace( $names ) {
5893
		$backtrace = debug_backtrace( false );
5894
		if ( ! is_array( $names ) ) {
5895
			$names = array( $names );
5896
		}
5897
		$names_as_keys = array_flip( $names );
5898
5899
		//Do check in constant O(1) time for PHP5.5+
5900
		if ( function_exists( 'array_column' ) ) {
5901
			$backtrace_functions = array_column( $backtrace, 'function' );
5902
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
5903
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
5904
			return ! empty ( $intersection );
5905
		}
5906
5907
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
5908
		foreach ( $backtrace as $call ) {
5909
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
5910
				return true;
5911
			}
5912
		}
5913
		return false;
5914
	}
5915
5916
	/**
5917
	 * Handles activating default modules as well general cleanup for the new connection.
5918
	 *
5919
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
5920
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
5921
	 * @return void
5922
	 */
5923
	public static function handle_post_authorization_actions( $activate_sso = false, $redirect_on_activation_error = false ) {
5924
		$other_modules = $activate_sso
5925
			? array( 'sso' )
5926
			: array();
5927
5928 View Code Duplication
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
5929
			Jetpack::delete_active_modules();
5930
5931
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, false );
0 ignored issues
show
Documentation introduced by
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...
5932
		} else {
5933
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, false );
5934
		}
5935
5936
		// Since this is a fresh connection, be sure to clear out IDC options
5937
		Jetpack_IDC::clear_all_idc_options();
5938
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
5939
5940
		// Start nonce cleaner
5941
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
5942
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
5943
5944
		Jetpack::state( 'message', 'authorized' );
5945
	}
5946
}
5947