Completed
Push — fix/3641-connect-site-network-... ( 8abb64...41619d )
by
unknown
478:50 queued 469:13
created

Jetpack::fix_url_for_bad_hosts()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 16
rs 9.2
1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'tiled-gallery',
46
		'widget-conditions',
47
		'jetpack_display_posts_widget',
48
		'gravatar-profile-widget',
49
		'widget-grid-and-list',
50
		'jetpack-widgets',
51
		'goodreads-widget',
52
		'jetpack_social_media_icons_widget',
53
	);
54
55
	public $plugins_to_deactivate = array(
56
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
57
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
63
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
64
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
65
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
66
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
67
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
68
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
69
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
70
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
71
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
72
	);
73
74
	public $capability_translations = array(
75
		'administrator' => 'manage_options',
76
		'editor'        => 'edit_others_posts',
77
		'author'        => 'publish_posts',
78
		'contributor'   => 'edit_posts',
79
		'subscriber'    => 'read',
80
	);
81
82
	/**
83
	 * Map of modules that have conflicts with plugins and should not be auto-activated
84
	 * if the plugins are active.  Used by filter_default_modules
85
	 *
86
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
87
	 * change `module-slug` and add this to your plugin:
88
	 *
89
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
90
	 * function my_jetpack_get_default_modules( $modules ) {
91
	 *     return array_diff( $modules, array( 'module-slug' ) );
92
	 * }
93
	 *
94
	 * @var array
95
	 */
96
	private $conflicting_plugins = array(
97
		'comments'          => array(
98
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
99
			'Disqus'                               => 'disqus-comment-system/disqus.php',
100
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
101
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
102
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
103
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
104
		),
105
		'contact-form'      => array(
106
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
107
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
108
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
109
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
110
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
111
		),
112
		'minileven'         => array(
113
			'WPtouch'                              => 'wptouch/wptouch.php',
114
		),
115
		'latex'             => array(
116
			'LaTeX for WordPress'                  => 'latex/latex.php',
117
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
118
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
119
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
120
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
121
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
122
		),
123
		'protect'           => array(
124
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
125
			'Captcha'                              => 'captcha/captcha.php',
126
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
127
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
128
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
129
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
130
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
131
			'Security-protection'                  => 'security-protection/security-protection.php',
132
			'Login Security'                       => 'login-security/login-security.php',
133
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
134
			'Wordfence Security'                   => 'wordfence/wordfence.php',
135
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
136
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
137
		),
138
		'random-redirect'   => array(
139
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
140
		),
141
		'related-posts'     => array(
142
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
143
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
144
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
145
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
146
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
147
			'outbrain'                             => 'outbrain/outbrain.php',
148
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
149
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
150
		),
151
		'sharedaddy'        => array(
152
			'AddThis'                              => 'addthis/addthis_social_widget.php',
153
			'Add To Any'                           => 'add-to-any/add-to-any.php',
154
			'ShareThis'                            => 'share-this/sharethis.php',
155
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
156
		),
157
		'verification-tools' => array(
158
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
159
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
160
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
161
		),
162
		'widget-visibility' => array(
163
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
164
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
165
		),
166
		'sitemaps' => array(
167
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
168
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
169
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
170
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
171
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
172
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
173
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
174
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
175
			'Sitemap'                              => 'sitemap/sitemap.php',
176
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
177
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
178
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
179
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
180
		),
181
	);
182
183
	/**
184
	 * Plugins for which we turn off our Facebook OG Tags implementation.
185
	 *
186
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
187
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
188
	 *
189
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
190
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
191
	 */
192
	private $open_graph_conflicting_plugins = array(
193
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
194
		                                                         // 2 Click Social Media Buttons
195
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
196
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
197
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
198
		'facebook/facebook.php',                                 // Facebook (official plugin)
199
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
200
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
201
		                                                         // Facebook Featured Image & OG Meta Tags
202
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
203
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
204
		                                                         // Facebook Open Graph Meta Tags for WordPress
205
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
206
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
207
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
208
		                                                         // Fedmich's Facebook Open Graph Meta
209
		'header-footer/plugin.php',                              // Header and Footer
210
		'network-publisher/networkpub.php',                      // Network Publisher
211
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
212
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
213
		                                                         // NextScripts SNAP
214
		'opengraph/opengraph.php',                               // Open Graph
215
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
216
		                                                         // Open Graph Protocol Framework
217
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
218
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
219
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
220
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
221
		'sharepress/sharepress.php',                             // SharePress
222
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
223
		'social-discussions/social-discussions.php',             // Social Discussions
224
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
225
		'socialize/socialize.php',                               // Socialize
226
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
227
		                                                         // Tweet, Like, Google +1 and Share
228
		'wordbooker/wordbooker.php',                             // Wordbooker
229
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
230
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
231
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
232
		                                                         // WP Facebook Like Send & Open Graph Meta
233
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
234
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
235
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
236
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
237
	);
238
239
	/**
240
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
241
	 */
242
	private $twitter_cards_conflicting_plugins = array(
243
	//	'twitter/twitter.php',                       // The official one handles this on its own.
244
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
245
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
246
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
247
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
248
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
249
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
250
		'twitter-cards/twitter-cards.php',           // Twitter Cards
251
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
252
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
253
	);
254
255
	/**
256
	 * Message to display in admin_notice
257
	 * @var string
258
	 */
259
	public $message = '';
260
261
	/**
262
	 * Error to display in admin_notice
263
	 * @var string
264
	 */
265
	public $error = '';
266
267
	/**
268
	 * Modules that need more privacy description.
269
	 * @var string
270
	 */
271
	public $privacy_checks = '';
272
273
	/**
274
	 * Stats to record once the page loads
275
	 *
276
	 * @var array
277
	 */
278
	public $stats = array();
279
280
	/**
281
	 * Allows us to build a temporary security report
282
	 *
283
	 * @var array
284
	 */
285
	static $security_report = array();
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $security_report.

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...
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	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...
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			if ( did_action( 'plugins_loaded' ) )
311
				self::plugin_textdomain();
312
			else
313
				add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
314
315
			self::$instance = new Jetpack;
316
317
			self::$instance->plugin_upgrade();
318
319
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
320
321
		}
322
323
		return self::$instance;
324
	}
325
326
	/**
327
	 * Must never be called statically
328
	 */
329
	function plugin_upgrade() {
330
		if ( Jetpack::is_active() ) {
331
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
332
			if ( JETPACK__VERSION != $version ) {
333
334
				// Check which active modules actually exist and remove others from active_modules list
335
				$unfiltered_modules = Jetpack::get_active_modules();
336
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
337
				if ( array_diff( $unfiltered_modules, $modules ) ) {
338
					Jetpack_Options::update_option( 'active_modules', $modules );
339
				}
340
341
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
342
				/**
343
				 * Fires when synchronizing all registered options and constants.
344
				 *
345
				 * @since 3.3.0
346
				 */
347
				do_action( 'jetpack_sync_all_registered_options' );
348
			}
349
		}
350
	}
351
352
	static function activate_manage( ) {
353
354
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
355
			self::activate_module( 'manage', false, false );
356
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
357
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
358
		}
359
360
	}
361
362
	/**
363
	 * Constructor.  Initializes WordPress hooks
364
	 */
365
	private function __construct() {
366
		/*
367
		 * Check for and alert any deprecated hooks
368
		 */
369
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
370
371
		/**
372
		 * We need sync object even in Multisite mode
373
		 */
374
		$this->sync = new Jetpack_Sync;
375
376
		/**
377
		 * Trigger a wp_version sync when updating WP versions
378
		 **/
379
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
380
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
381
382
		add_action( 'init', array( $this, 'sync_update_data') );
383
		add_action( 'init', array( $this, 'sync_theme_data' ) );
384
385
		/*
386
		 * Load things that should only be in Network Admin.
387
		 *
388
		 * For now blow away everything else until a more full
389
		 * understanding of what is needed at the network level is
390
		 * available
391
		 */
392
		if( is_multisite() ) {
393
			Jetpack_Network::init();
394
395
			// Only sync this info if we are on a multi site
396
			// @since  3.7
397
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
398
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
399
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
400
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
401
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
402
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
403
404
			if( is_network_admin() ) {
405
				// Sync network site data if it is updated or not.
406
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
407
				return; // End here to prevent single site actions from firing
408
			}
409
		}
410
411
412
		$theme_slug = get_option( 'stylesheet' );
413
414
415
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
416
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
417
		$this->sync->options(
418
			JETPACK__PLUGIN_DIR . 'jetpack.php',
419
			'home',
420
			'siteurl',
421
			'blogname',
422
			'gmt_offset',
423
			'timezone_string',
424
			'security_report',
425
			'stylesheet',
426
			"theme_mods_{$theme_slug}",
427
			'jetpack_sync_non_public_post_stati',
428
			'jetpack_options',
429
			'site_icon', // (int) - ID of core's Site Icon attachment ID
430
			'default_post_format',
431
			'default_category',
432
			'large_size_w',
433
			'large_size_h',
434
			'thumbnail_size_w',
435
			'thumbnail_size_h',
436
			'medium_size_w',
437
			'medium_size_h',
438
			'thumbnail_crop',
439
			'image_default_link_type'
440
		);
441
442
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
443
			$this->sync->options( __FILE__, 'jetpack_' . $option );
444
		}
445
446
		/**
447
		 * Sometimes you want to sync data to .com without adding options to .org sites.
448
		 * The mock option allows you to do just that.
449
		 */
450
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
451
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
452
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
453
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
454
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
455
456
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
457
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
458
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
459
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
460
461
		/**
462
		 * Trigger an update to the main_network_site when we update the blogname of a site.
463
		 *
464
		 */
465
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
466
467
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
468
469
		// Update the settings everytime the we register a new user to the site or we delete a user.
470
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
471
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
472
473
		// Unlink user before deleting the user from .com
474
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
475
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
476
477
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
478
			@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...
479
480
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
481
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
482
483
			$this->require_jetpack_authentication();
484
485
			if ( Jetpack::is_active() ) {
486
				// Hack to preserve $HTTP_RAW_POST_DATA
487
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
488
489
				$signed = $this->verify_xml_rpc_signature();
490
				if ( $signed && ! is_wp_error( $signed ) ) {
491
					// The actual API methods.
492
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
493
				} else {
494
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
495
					// active Jetpack connection, so that additional users can link their account.
496
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
497
				}
498
			} else {
499
				// The bootstrap API methods.
500
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
501
			}
502
503
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
504
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
505
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
506
			$this->require_jetpack_authentication();
507
			$this->add_remote_request_handlers();
508
		} else {
509
			if ( Jetpack::is_active() ) {
510
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
511
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
512
			}
513
		}
514
515
		if ( Jetpack::is_active() ) {
516
			Jetpack_Heartbeat::init();
517
		}
518
519
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
520
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
521
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
522
		}
523
524
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
525
526
		add_action( 'admin_init', array( $this, 'admin_init' ) );
527
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
528
529
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
530
531
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
532
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
533
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
534
535
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
536
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
537
538
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
539
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
540
541
		// Identity Crisis AJAX callback function
542
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
543
544
		// JITM AJAX callback function
545
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
546
547
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
548
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
549
550
		// Universal ajax callback for all tracking events triggered via js
551
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
552
553
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
554
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
555
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
556
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
557
558
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
559
560
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
561
562
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
563
564
		/**
565
		 * These actions run checks to load additional files.
566
		 * They check for external files or plugins, so they need to run as late as possible.
567
		 */
568
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
569
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
570
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
571
572
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
573
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
574
575
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
576
577
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
578
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
579
580
		// A filter to control all just in time messages
581
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
582
583
		/**
584
		 * This is the hack to concatinate all css files into one.
585
		 * For description and reasoning see the implode_frontend_css method
586
		 *
587
		 * Super late priority so we catch all the registered styles
588
		 */
589
		if( !is_admin() ) {
590
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
591
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
592
		}
593
594
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
595
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
596
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
597
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
598
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
599
600
	}
601
602
	/*
603
	 * Make sure any site icon added to core can get
604
	 * synced back to dotcom, so we can display it there.
605
	 */
606
	function jetpack_sync_core_icon() {
607
		if ( function_exists( 'get_site_icon_url' ) ) {
608
			$url = get_site_icon_url();
609
		} else {
610
			return;
611
		}
612
613
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
614
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
615
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
616
			// This is the option that is synced with dotcom
617
			Jetpack_Options::update_option( 'site_icon_url', $url );
618
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
619
			Jetpack_Options::delete_option( 'site_icon_url' );
620
		}
621
	}
622
623
	function jetpack_admin_ajax_tracks_callback() {
624
		// Check for nonce
625
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
626
			wp_die( 'Permissions check failed.' );
627
		}
628
629
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
630
			wp_die( 'No valid event name or type.' );
631
		}
632
633
		$tracks_data = array();
634
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
635
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
636
		}
637
638
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
639
		wp_send_json_success();
640
		wp_die();
641
	}
642
643
	function jetpack_admin_ajax_callback() {
644
		// Check for nonce
645 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
646
			wp_die( 'permissions check failed' );
647
		}
648
649
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
650
			$slug = $_REQUEST['thisModuleSlug'];
651
652
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
653
				wp_die( 'That is not a Jetpack module slug' );
654
			}
655
656
			if ( Jetpack::is_module_active( $slug ) ) {
657
				Jetpack::deactivate_module( $slug );
658
			} else {
659
				Jetpack::activate_module( $slug, false, false );
660
			}
661
662
			$modules = Jetpack_Admin::init()->get_modules();
663
			echo json_encode( $modules[ $slug ] );
664
665
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method jetpack_admin_ajax_callback() 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...
666
		}
667
668
		wp_die();
669
	}
670
671
	/*
672
	 * Sometimes we need to refresh the data,
673
	 * especially if the page is visited via a 'history'
674
	 * event like back/forward
675
	 */
676
	function jetpack_admin_ajax_refresh_data() {
677
		// Check for nonce
678 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
679
			wp_die( 'permissions check failed' );
680
		}
681
682
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
683
			$modules = Jetpack_Admin::init()->get_modules();
684
			echo json_encode( $modules );
685
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method jetpack_admin_ajax_refresh_data() 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...
686
		}
687
688
		wp_die();
689
	}
690
691
	/**
692
	 * The callback for the JITM ajax requests.
693
	 */
694
	function jetpack_jitm_ajax_callback() {
695
		// Check for nonce
696
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
697
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
698
		}
699
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
700
			$module_slug = $_REQUEST['jitmModule'];
701
			Jetpack::log( 'activate', $module_slug );
702
			Jetpack::activate_module( $module_slug, false, false );
703
			Jetpack::state( 'message', 'no_message' );
704
705
			//A Jetpack module is being activated through a JITM, track it
706
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
707
			$this->do_stats( 'server_side' );
708
709
			wp_send_json_success();
710
		}
711
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
712
			// get the hide_jitm options array
713
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
714
			$module_slug = $_REQUEST['jitmModule'];
715
716
			if( ! $jetpack_hide_jitm ) {
717
				$jetpack_hide_jitm = array(
718
					$module_slug => 'hide'
719
				);
720
			} else {
721
				$jetpack_hide_jitm[$module_slug] = 'hide';
722
			}
723
724
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
725
726
			//jitm is being dismissed forever, track it
727
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
728
			$this->do_stats( 'server_side' );
729
730
			wp_send_json_success();
731
		}
732 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
733
			$module_slug = $_REQUEST['jitmModule'];
734
735
			// User went to WordPress.com, track this
736
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
737
			$this->do_stats( 'server_side' );
738
739
			wp_send_json_success();
740
		}
741 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
742
			$track = $_REQUEST['jitmModule'];
743
744
			// User is viewing JITM, track it.
745
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
746
			$this->do_stats( 'server_side' );
747
748
			wp_send_json_success();
749
		}
750
	}
751
752
	/**
753
	 * If there are any stats that need to be pushed, but haven't been, push them now.
754
	 */
755
	function __destruct() {
756
		if ( ! empty( $this->stats ) ) {
757
			$this->do_stats( 'server_side' );
758
		}
759
	}
760
761
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
762
		switch( $cap ) {
763
			case 'jetpack_connect' :
764
			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...
765
				if ( Jetpack::is_development_mode() ) {
766
					$caps = array( 'do_not_allow' );
767
					break;
768
				}
769
				/**
770
				 * Pass through. If it's not development mode, these should match disconnect.
771
				 * Let users disconnect if it's development mode, just in case things glitch.
772
				 */
773
			case 'jetpack_disconnect' :
774
				/**
775
				 * In multisite, can individual site admins manage their own connection?
776
				 *
777
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
778
				 */
779
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
780
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
781
						/**
782
						 * We need to update the option name -- it's terribly unclear which
783
						 * direction the override goes.
784
						 *
785
						 * @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...
786
						 */
787
						$caps = array( 'do_not_allow' );
788
						break;
789
					}
790
				}
791
792
				$caps = array( 'manage_options' );
793
				break;
794
			case 'jetpack_manage_modules' :
795
			case 'jetpack_activate_modules' :
796
			case 'jetpack_deactivate_modules' :
797
				$caps = array( 'manage_options' );
798
				break;
799
			case 'jetpack_configure_modules' :
800
				$caps = array( 'manage_options' );
801
				break;
802
			case 'jetpack_network_admin_page':
803
			case 'jetpack_network_settings_page':
804
				$caps = array( 'manage_network_plugins' );
805
				break;
806
			case 'jetpack_network_sites_page':
807
				$caps = array( 'manage_sites' );
808
				break;
809
			case 'jetpack_admin_page' :
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...
810
				if ( Jetpack::is_development_mode() ) {
811
					$caps = array( 'manage_options' );
812
					break;
813
				}
814
815
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
816
				if ( ! current_user_can( 'edit_posts' ) ) {
817
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
818
						// We need this in order to unlink the user.
819
						$this->admin_page_load();
820
					}
821
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
822
						$caps = array( 'do_not_allow' );
823
						break;
824
					}
825
				}
826
827
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
828
					$caps = array( 'do_not_allow' );
829
					break;
830
				}
831
				/**
832
				 * Pass through. If it's not development mode, these should match the admin page.
833
				 * Let users disconnect if it's development mode, just in case things glitch.
834
				 */
835
			case 'jetpack_connect_user' :
836
				if ( Jetpack::is_development_mode() ) {
837
					$caps = array( 'do_not_allow' );
838
					break;
839
				}
840
				$caps = array( 'read' );
841
				break;
842
		}
843
		return $caps;
844
	}
845
846
	function require_jetpack_authentication() {
847
		// Don't let anyone authenticate
848
		$_COOKIE = array();
849
		remove_all_filters( 'authenticate' );
850
851
		/**
852
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
853
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
854
		 * generate false-positives.
855
		 */
856
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
857
858
		if ( Jetpack::is_active() ) {
859
			// Allow Jetpack authentication
860
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
861
		}
862
	}
863
864
	/**
865
	 * Load language files
866
	 */
867
	public static function plugin_textdomain() {
868
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
869
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
870
	}
871
872
	/**
873
	 * Register assets for use in various modules and the Jetpack admin page.
874
	 *
875
	 * @uses wp_script_is, wp_register_script, plugins_url
876
	 * @action wp_loaded
877
	 * @return null
878
	 */
879
	public function register_assets() {
880
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
881
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
882
		}
883
884 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
885
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
886
		}
887
888 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
889
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
890
		}
891
892 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
893
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
894
		}
895
896
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
897
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
898
899
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
900
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
901
			if ( ! is_numeric( $fb_app_id ) ) {
902
				$fb_app_id = '';
903
			}
904
			wp_localize_script(
905
				'jetpack-facebook-embed',
906
				'jpfbembed',
907
				array(
908
					'appid' => $fb_app_id,
909
					'locale' => $this->get_locale(),
910
				)
911
			);
912
		}
913
914
		/**
915
		 * As jetpack_register_genericons is by default fired off a hook,
916
		 * the hook may have already fired by this point.
917
		 * So, let's just trigger it manually.
918
		 */
919
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
920
		jetpack_register_genericons();
921
922 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
923
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
924
	}
925
926
	/**
927
	 * Guess locale from language code.
928
	 *
929
	 * @param string $lang Language code.
930
	 * @return string|bool
931
	 */
932 View Code Duplication
	function guess_locale_from_lang( $lang ) {
933
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
934
			return 'en_US';
935
		}
936
937
		if ( ! class_exists( 'GP_Locales' ) ) {
938
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
939
				return false;
940
			}
941
942
			require JETPACK__GLOTPRESS_LOCALES_PATH;
943
		}
944
945
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
946
			// WP.com: get_locale() returns 'it'
947
			$locale = GP_Locales::by_slug( $lang );
948
		} else {
949
			// Jetpack: get_locale() returns 'it_IT';
950
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
951
		}
952
953
		if ( ! $locale ) {
954
			return false;
955
		}
956
957
		if ( empty( $locale->facebook_locale ) ) {
958
			if ( empty( $locale->wp_locale ) ) {
959
				return false;
960
			} else {
961
				// Facebook SDK is smart enough to fall back to en_US if a
962
				// locale isn't supported. Since supported Facebook locales
963
				// can fall out of sync, we'll attempt to use the known
964
				// wp_locale value and rely on said fallback.
965
				return $locale->wp_locale;
966
			}
967
		}
968
969
		return $locale->facebook_locale;
970
	}
971
972
	/**
973
	 * Get the locale.
974
	 *
975
	 * @return string|bool
976
	 */
977
	function get_locale() {
978
		$locale = $this->guess_locale_from_lang( get_locale() );
979
980
		if ( ! $locale ) {
981
			$locale = 'en_US';
982
		}
983
984
		return $locale;
985
	}
986
987
	/**
988
	 * Device Pixels support
989
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
990
	 */
991
	function devicepx() {
992
		if ( Jetpack::is_active() ) {
993
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
994
		}
995
	}
996
997
	/**
998
	 * Return the network_site_url so that .com knows what network this site is a part of.
999
	 * @param  bool $option
1000
	 * @return string
1001
	 */
1002
	public function jetpack_main_network_site_option( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1003
		return network_site_url();
1004
	}
1005
	/**
1006
	 * Network Name.
1007
	 */
1008
	static function network_name( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1009
		global $current_site;
1010
		return $current_site->site_name;
1011
	}
1012
	/**
1013
	 * Does the network allow new user and site registrations.
1014
	 * @return string
1015
	 */
1016
	static function network_allow_new_registrations( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1017
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1018
	}
1019
	/**
1020
	 * Does the network allow admins to add new users.
1021
	 * @return boolian
1022
	 */
1023
	static function network_add_new_users( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1024
		return (bool) get_site_option( 'add_new_users' );
1025
	}
1026
	/**
1027
	 * File upload psace left per site in MB.
1028
	 *  -1 means NO LIMIT.
1029
	 * @return number
1030
	 */
1031
	static function network_site_upload_space( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1032
		// value in MB
1033
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1034
	}
1035
1036
	/**
1037
	 * Network allowed file types.
1038
	 * @return string
1039
	 */
1040
	static function network_upload_file_types( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1041
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1042
	}
1043
1044
	/**
1045
	 * Maximum file upload size set by the network.
1046
	 * @return number
1047
	 */
1048
	static function network_max_upload_file_size( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1049
		// value in KB
1050
		return get_site_option( 'fileupload_maxk', 300 );
1051
	}
1052
1053
	/**
1054
	 * Lets us know if a site allows admins to manage the network.
1055
	 * @return array
1056
	 */
1057
	static function network_enable_administration_menus( $option = null ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1058
		return get_site_option( 'menu_items' );
1059
	}
1060
1061
	/**
1062
	 * Return whether we are dealing with a multi network setup or not.
1063
	 * The reason we are type casting this is because we want to avoid the situation where
1064
	 * the result is false since when is_main_network_option return false it cases
1065
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1066
	 * database which could be set to anything as opposed to what this function returns.
1067
	 * @param  bool  $option
1068
	 *
1069
	 * @return boolean
1070
	 */
1071
	public function is_main_network_option( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1072
		// return '1' or ''
1073
		return (string) (bool) Jetpack::is_multi_network();
1074
	}
1075
1076
	/**
1077
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1078
	 *
1079
	 * @param  string  $option
1080
	 * @return boolean
1081
	 */
1082
	public function is_multisite( $option ) {
0 ignored issues
show
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1083
		return (string) (bool) is_multisite();
1084
	}
1085
1086
	/**
1087
	 * Implemented since there is no core is multi network function
1088
	 * Right now there is no way to tell if we which network is the dominant network on the system
1089
	 *
1090
	 * @since  3.3
1091
	 * @return boolean
1092
	 */
1093
	public static function is_multi_network() {
1094
		global  $wpdb;
1095
1096
		// if we don't have a multi site setup no need to do any more
1097
		if ( ! is_multisite() ) {
1098
			return false;
1099
		}
1100
1101
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1102
		if ( $num_sites > 1 ) {
1103
			return true;
1104
		} else {
1105
			return false;
1106
		}
1107
	}
1108
1109
	/**
1110
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1111
	 * @return null
1112
	 */
1113
	function update_jetpack_main_network_site_option() {
1114
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1115
		/**
1116
		 * Fires when the site URL is updated.
1117
		 * Determines if the site is the main site of a Mulitiste network.
1118
		 *
1119
		 * @since 3.3.0
1120
		 *
1121
		 * @param string jetpack_main_network_site.
1122
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1123
		 */
1124
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1125
		/**
1126
		 * Fires when the site URL is updated.
1127
		 * Determines if the is part of a multi network.
1128
		 *
1129
		 * @since 3.3.0
1130
		 *
1131
		 * @param string jetpack_is_main_network.
1132
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1133
		 */
1134
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1135
		/**
1136
		 * Fires when the site URL is updated.
1137
		 * Determines if the site is part of a multisite network.
1138
		 *
1139
		 * @since 3.4.0
1140
		 *
1141
		 * @param string jetpack_is_multi_site.
1142
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1143
		 */
1144
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1145
	}
1146
	/**
1147
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1148
	 *
1149
	 */
1150
	function update_jetpack_network_settings() {
1151
		// Only sync this info for the main network site.
1152
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1153
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1154
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1155
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1156
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1157
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1158
1159
	}
1160
1161
	/**
1162
	 * Get back if the current site is single user site.
1163
	 *
1164
	 * @return bool
1165
	 */
1166
	public static function is_single_user_site() {
1167
1168
		$user_query = new WP_User_Query( array(
1169
			'blog_id' => get_current_blog_id(),
1170
			'fields'  => 'ID',
1171
			'number' => 2
1172
		) );
1173
		return 1 === (int) $user_query->get_total();
1174
	}
1175
1176
	/**
1177
	 * Returns true if the site has file write access false otherwise.
1178
	 * @return string ( '1' | '0' )
1179
	 **/
1180
	public static function file_system_write_access() {
1181
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1182
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1183
		}
1184
1185
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1186
1187
		$filesystem_method = get_filesystem_method();
1188
		if ( $filesystem_method === 'direct' ) {
1189
			return 1;
1190
		}
1191
1192
		ob_start();
1193
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1194
		ob_end_clean();
1195
		if ( $filesystem_credentials_are_stored ) {
1196
			return 1;
1197
		}
1198
		return 0;
1199
	}
1200
1201
	/**
1202
	 * Finds out if a site is using a version control system.
1203
	 * @return string ( '1' | '0' )
1204
	 **/
1205
	public static function is_version_controlled() {
1206
1207
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1208
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1209
		}
1210
		$updater = new WP_Automatic_Updater();
1211
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1212
		// transients should not be empty
1213
		if ( empty( $is_version_controlled ) ) {
1214
			$is_version_controlled = '0';
1215
		}
1216
		return $is_version_controlled;
1217
	}
1218
1219
	/**
1220
	 * Determines whether the current theme supports featured images or not.
1221
	 * @return string ( '1' | '0' )
1222
	 */
1223
	public static function featured_images_enabled() {
1224
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1225
	}
1226
1227
	/*
1228
	 * Sync back wp_version
1229
	 */
1230
	public static function get_wp_version() {
1231
		global $wp_version;
1232
		return $wp_version;
1233
	}
1234
1235
	/**
1236
	 * Keeps wp_version in sync with .com when WordPress core updates
1237
	 **/
1238
	public static function update_get_wp_version( $update, $meta_data ) {
1239
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1240
			/** This action is documented in wp-includes/option.php */
1241
			/**
1242
			 * This triggers the sync for the jetpack version
1243
			 * See Jetpack_Sync options method for more info.
1244
			 */
1245
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1246
		}
1247
	}
1248
1249
	/**
1250
	 * Triggers a sync of update counts and update details
1251
	 */
1252
	function sync_update_data() {
1253
		// Anytime WordPress saves update data, we'll want to sync update data
1254
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1255
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1256
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1257
		// Anytime a connection to jetpack is made, sync the update data
1258
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1259
		// Anytime the Jetpack Version changes, sync the the update data
1260
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1261
1262
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1263
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1264
		}
1265
1266
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1267
	}
1268
1269
	/**
1270
	 * Triggers a sync of information specific to the current theme.
1271
	 */
1272
	function sync_theme_data() {
1273
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1274
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1275
	}
1276
1277
	/**
1278
	 * jetpack_updates is saved in the following schema:
1279
	 *
1280
	 * array (
1281
	 *      'plugins'                       => (int) Number of plugin updates available.
1282
	 *      'themes'                        => (int) Number of theme updates available.
1283
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1284
	 *      'translations'                  => (int) Number of translation updates available.
1285
	 *      'total'                         => (int) Total of all available updates.
1286
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1287
	 * )
1288
	 * @return array
1289
	 */
1290
	public static function get_updates() {
1291
		$update_data = wp_get_update_data();
1292
1293
		// Stores the individual update counts as well as the total count.
1294
		if ( isset( $update_data['counts'] ) ) {
1295
			$updates = $update_data['counts'];
1296
		}
1297
1298
		// If we need to update WordPress core, let's find the latest version number.
1299 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1300
			$cur = get_preferred_from_update_core();
1301
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1302
				$updates['wp_update_version'] = $cur->current;
1303
			}
1304
		}
1305
		return isset( $updates ) ? $updates : array();
1306
	}
1307
1308
	public static function get_update_details() {
1309
		$update_details = array(
1310
			'update_core' => get_site_transient( 'update_core' ),
1311
			'update_plugins' => get_site_transient( 'update_plugins' ),
1312
			'update_themes' => get_site_transient( 'update_themes' ),
1313
		);
1314
		return $update_details;
1315
	}
1316
1317
	public static function refresh_update_data() {
1318
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1319
			/**
1320
			 * Fires whenever the amount of updates needed for a site changes.
1321
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1322
			 *
1323
			 * @since 3.7.0
1324
			 *
1325
			 * @param string jetpack_updates
1326
			 * @param array Update counts calculated by Jetpack::get_updates
1327
			 */
1328
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1329
		}
1330
		/**
1331
		 * Fires whenever the amount of updates needed for a site changes.
1332
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1333
		 *
1334
		 * @since 3.7.0
1335
		 *
1336
		 * @param string jetpack_update_details
1337
		 * @param array Update details calculated by Jetpack::get_update_details
1338
		 */
1339
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1340
	}
1341
1342
	public static function refresh_theme_data() {
1343
		/**
1344
		 * Fires whenever a theme change is made.
1345
		 *
1346
		 * @since 3.8.1
1347
		 *
1348
		 * @param string featured_images_enabled
1349
		 * @param boolean Whether featured images are enabled or not
1350
		 */
1351
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1352
	}
1353
1354
	/**
1355
	 * Invalides the transient as well as triggers the update of the mock option.
1356
	 *
1357
	 * @return null
1358
	 */
1359
	function is_single_user_site_invalidate() {
1360
		/**
1361
		 * Fires when a user is added or removed from a site.
1362
		 * Determines if the site is a single user site.
1363
		 *
1364
		 * @since 3.4.0
1365
		 *
1366
		 * @param string jetpack_single_user_site.
1367
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1368
		 */
1369
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1370
	}
1371
1372
	/**
1373
	 * Is Jetpack active?
1374
	 */
1375
	public static function is_active() {
1376
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1377
	}
1378
1379
	/**
1380
	 * Is Jetpack in development (offline) mode?
1381
	 */
1382
	public static function is_development_mode() {
1383
		$development_mode = false;
1384
1385
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1386
			$development_mode = JETPACK_DEV_DEBUG;
1387
		}
1388
1389
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1390
			$development_mode = true;
1391
		}
1392
		/**
1393
		 * Filters Jetpack's development mode.
1394
		 *
1395
		 * @see http://jetpack.com/support/development-mode/
1396
		 *
1397
		 * @since 2.2.1
1398
		 *
1399
		 * @param bool $development_mode Is Jetpack's development mode active.
1400
		 */
1401
		return apply_filters( 'jetpack_development_mode', $development_mode );
1402
	}
1403
1404
	/**
1405
	* Get Jetpack development mode notice text and notice class.
1406
	*
1407
	* Mirrors the checks made in Jetpack::is_development_mode
1408
	*
1409
	*/
1410
	public static function show_development_mode_notice() {
1411
		if ( Jetpack::is_development_mode() ) {
1412
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1413
				$notice = sprintf(
1414
					/* translators: %s is a URL */
1415
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1416
					'http://jetpack.com/support/development-mode/'
1417
				);
1418
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1419
				$notice = sprintf(
1420
					/* translators: %s is a URL */
1421
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1422
					'http://jetpack.com/support/development-mode/'
1423
				);
1424
			} else {
1425
				$notice = sprintf(
1426
					/* translators: %s is a URL */
1427
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1428
					'http://jetpack.com/support/development-mode/'
1429
				);
1430
			}
1431
1432
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1433
		}
1434
1435
		// Throw up a notice if using a development version and as for feedback.
1436
		if ( Jetpack::is_development_version() ) {
1437
			/* translators: %s is a URL */
1438
			$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/' );
1439
1440
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1441
		}
1442
		// Throw up a notice if using staging mode
1443
		if ( Jetpack::is_staging_site() ) {
1444
			/* translators: %s is a URL */
1445
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1446
1447
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1448
		}
1449
	}
1450
1451
	/**
1452
	 * Whether Jetpack's version maps to a public release, or a development version.
1453
	 */
1454
	public static function is_development_version() {
1455
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1456
	}
1457
1458
	/**
1459
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1460
	 */
1461
	public static function is_user_connected( $user_id = false ) {
1462
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1463
		if ( ! $user_id ) {
1464
			return false;
1465
		}
1466
		return (bool) Jetpack_Data::get_access_token( $user_id );
1467
	}
1468
1469
	/**
1470
	 * Get the wpcom user data of the current|specified connected user.
1471
	 */
1472 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1473
		if ( ! $user_id ) {
1474
			$user_id = get_current_user_id();
1475
		}
1476
		Jetpack::load_xml_rpc_client();
1477
		$xml = new Jetpack_IXR_Client( array(
1478
			'user_id' => $user_id,
1479
		) );
1480
		$xml->query( 'wpcom.getUser' );
1481
		if ( ! $xml->isError() ) {
1482
			return $xml->getResponse();
1483
		}
1484
		return false;
1485
	}
1486
1487
	/**
1488
	 * Get the wpcom email of the current|specified connected user.
1489
	 */
1490 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1491
		if ( ! $user_id ) {
1492
			$user_id = get_current_user_id();
1493
		}
1494
		Jetpack::load_xml_rpc_client();
1495
		$xml = new Jetpack_IXR_Client( array(
1496
			'user_id' => $user_id,
1497
		) );
1498
		$xml->query( 'wpcom.getUserEmail' );
1499
		if ( ! $xml->isError() ) {
1500
			return $xml->getResponse();
1501
		}
1502
		return false;
1503
	}
1504
1505
	/**
1506
	 * Get the wpcom email of the master user.
1507
	 */
1508
	public static function get_master_user_email() {
1509
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1510
		if ( $master_user_id ) {
1511
			return self::get_connected_user_email( $master_user_id );
1512
		}
1513
		return '';
1514
	}
1515
1516
	function current_user_is_connection_owner() {
1517
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1518
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1519
	}
1520
1521
	/**
1522
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1523
	 */
1524
	function extra_oembed_providers() {
1525
		// Cloudup: https://dev.cloudup.com/#oembed
1526
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1527
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1528
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1529
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1530
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1531
	}
1532
1533
	/**
1534
	 * Synchronize connected user role changes
1535
	 */
1536
	function user_role_change( $user_id ) {
1537
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1538
			$current_user_id = get_current_user_id();
1539
			wp_set_current_user( $user_id );
1540
			$role = $this->translate_current_user_to_role();
1541
			$signed_role = $this->sign_role( $role );
1542
			wp_set_current_user( $current_user_id );
1543
1544
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1545
			$master_user_id = absint( $master_token->external_user_id );
1546
1547
			if ( ! $master_user_id )
1548
				return; // this shouldn't happen
1549
1550
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1551
			//@todo retry on failure
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...
1552
1553
			//try to choose a new master if we're demoting the current one
1554
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1555
				$query = new WP_User_Query(
1556
					array(
1557
						'fields'  => array( 'id' ),
1558
						'role'    => 'administrator',
1559
						'orderby' => 'id',
1560
						'exclude' => array( $master_user_id ),
1561
					)
1562
				);
1563
				$new_master = false;
1564
				foreach ( $query->results as $result ) {
1565
					$uid = absint( $result->id );
1566
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1567
						$new_master = $uid;
1568
						break;
1569
					}
1570
				}
1571
1572
				if ( $new_master ) {
1573
					Jetpack_Options::update_option( 'master_user', $new_master );
1574
				}
1575
				// else disconnect..?
1576
			}
1577
		}
1578
	}
1579
1580
	/**
1581
	 * Loads the currently active modules.
1582
	 */
1583
	public static function load_modules() {
1584
		if ( ! self::is_active() && !self::is_development_mode() ) {
1585
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1586
				return;
1587
			}
1588
		}
1589
1590
		$version = Jetpack_Options::get_option( 'version' );
1591 View Code Duplication
		if ( ! $version ) {
1592
			$version = $old_version = JETPACK__VERSION . ':' . time();
1593
			/** This action is documented in class.jetpack.php */
1594
			do_action( 'updating_jetpack_version', $version, false );
1595
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1596
		}
1597
		list( $version ) = explode( ':', $version );
1598
1599
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1600
1601
		$modules_data = array();
1602
1603
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1604
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1605
			$updated_modules = array();
1606
			foreach ( $modules as $module ) {
1607
				$modules_data[ $module ] = Jetpack::get_module( $module );
1608
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1609
					continue;
1610
				}
1611
1612
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1613
					continue;
1614
				}
1615
1616
				$updated_modules[] = $module;
1617
			}
1618
1619
			$modules = array_diff( $modules, $updated_modules );
1620
		}
1621
1622
		$is_development_mode = Jetpack::is_development_mode();
1623
1624
		foreach ( $modules as $index => $module ) {
1625
			// If we're in dev mode, disable modules requiring a connection
1626
			if ( $is_development_mode ) {
1627
				// Prime the pump if we need to
1628
				if ( empty( $modules_data[ $module ] ) ) {
1629
					$modules_data[ $module ] = Jetpack::get_module( $module );
1630
				}
1631
				// If the module requires a connection, but we're in local mode, don't include it.
1632
				if ( $modules_data[ $module ]['requires_connection'] ) {
1633
					continue;
1634
				}
1635
			}
1636
1637
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1638
				continue;
1639
			}
1640
1641
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1642
				unset( $modules[ $index ] );
1643
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1644
				continue;
1645
			}
1646
1647
			/**
1648
			 * Fires when a specific module is loaded.
1649
			 * The dynamic part of the hook, $module, is the module slug.
1650
			 *
1651
			 * @since 1.1.0
1652
			 */
1653
			do_action( 'jetpack_module_loaded_' . $module );
1654
		}
1655
1656
		/**
1657
		 * Fires when all the modules are loaded.
1658
		 *
1659
		 * @since 1.1.0
1660
		 */
1661
		do_action( 'jetpack_modules_loaded' );
1662
1663
		// 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.
1664
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1665
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1666
	}
1667
1668
	/**
1669
	 * Check if Jetpack's REST API compat file should be included
1670
	 * @action plugins_loaded
1671
	 * @return null
1672
	 */
1673
	public function check_rest_api_compat() {
1674
		/**
1675
		 * Filters the list of REST API compat files to be included.
1676
		 *
1677
		 * @since 2.2.5
1678
		 *
1679
		 * @param array $args Array of REST API compat files to include.
1680
		 */
1681
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1682
1683
		if ( function_exists( 'bbpress' ) )
1684
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1685
1686
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1687
			require_once $_jetpack_rest_api_compat_include;
1688
	}
1689
1690
	/**
1691
	 * Gets all plugins currently active in values, regardless of whether they're
1692
	 * traditionally activated or network activated.
1693
	 *
1694
	 * @todo Store the result in core's object cache maybe?
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

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

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

Loading history...
1695
	 */
1696
	public static function get_active_plugins() {
1697
		$active_plugins = (array) get_option( 'active_plugins', array() );
1698
1699
		if ( is_multisite() ) {
1700
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1701
			// whereas active_plugins stores them in the values.
1702
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1703
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1704
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1705
			}
1706
		}
1707
1708
		sort( $active_plugins );
1709
1710
		return array_unique( $active_plugins );
1711
	}
1712
1713
	/**
1714
	 * Gets and parses additional plugin data to send with the heartbeat data
1715
	 *
1716
	 * @since 3.8.1
1717
	 *
1718
	 * @return array Array of plugin data
1719
	 */
1720
	public static function get_parsed_plugin_data() {
1721
		if ( ! function_exists( 'get_plugins' ) ) {
1722
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1723
		}
1724
		$all_plugins    = get_plugins();
1725
		$active_plugins = Jetpack::get_active_plugins();
1726
1727
		$plugins = array();
1728
		foreach ( $all_plugins as $path => $plugin_data ) {
1729
			$plugins[ $path ] = array(
1730
					'is_active' => in_array( $path, $active_plugins ),
1731
					'file'      => $path,
1732
					'name'      => $plugin_data['Name'],
1733
					'version'   => $plugin_data['Version'],
1734
					'author'    => $plugin_data['Author'],
1735
			);
1736
		}
1737
1738
		return $plugins;
1739
	}
1740
1741
	/**
1742
	 * Gets and parses theme data to send with the heartbeat data
1743
	 *
1744
	 * @since 3.8.1
1745
	 *
1746
	 * @return array Array of theme data
1747
	 */
1748
	public static function get_parsed_theme_data() {
1749
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1750
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1751
1752
		$themes = array();
1753
		foreach ( $all_themes as $slug => $theme_data ) {
1754
			$theme_headers = array();
1755
			foreach ( $header_keys as $header_key ) {
1756
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1757
			}
1758
1759
			$themes[ $slug ] = array(
1760
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1761
					'slug' => $slug,
1762
					'theme_root' => $theme_data->get_theme_root_uri(),
1763
					'parent' => $theme_data->parent(),
1764
					'headers' => $theme_headers
1765
			);
1766
		}
1767
1768
		return $themes;
1769
	}
1770
1771
	/**
1772
	 * Checks whether a specific plugin is active.
1773
	 *
1774
	 * We don't want to store these in a static variable, in case
1775
	 * there are switch_to_blog() calls involved.
1776
	 */
1777
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1778
		return in_array( $plugin, self::get_active_plugins() );
1779
	}
1780
1781
	/**
1782
	 * Check if Jetpack's Open Graph tags should be used.
1783
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1784
	 *
1785
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1786
	 * @action plugins_loaded
1787
	 * @return null
1788
	 */
1789
	public function check_open_graph() {
1790
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1791
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1792
		}
1793
1794
		$active_plugins = self::get_active_plugins();
1795
1796
		if ( ! empty( $active_plugins ) ) {
1797
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1798
				if ( in_array( $plugin, $active_plugins ) ) {
1799
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1800
					break;
1801
				}
1802
			}
1803
		}
1804
1805
		/**
1806
		 * Allow the addition of Open Graph Meta Tags to all pages.
1807
		 *
1808
		 * @since 2.0.3
1809
		 *
1810
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1811
		 */
1812
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1813
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1814
		}
1815
	}
1816
1817
	/**
1818
	 * Check if Jetpack's Twitter tags should be used.
1819
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1820
	 *
1821
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1822
	 * @action plugins_loaded
1823
	 * @return null
1824
	 */
1825
	public function check_twitter_tags() {
1826
1827
		$active_plugins = self::get_active_plugins();
1828
1829
		if ( ! empty( $active_plugins ) ) {
1830
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1831
				if ( in_array( $plugin, $active_plugins ) ) {
1832
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1833
					break;
1834
				}
1835
			}
1836
		}
1837
1838
		/**
1839
		 * Allow Twitter Card Meta tags to be disabled.
1840
		 *
1841
		 * @since 2.6.0
1842
		 *
1843
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1844
		 */
1845
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1846
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1847
		}
1848
	}
1849
1850
1851
1852
1853
	/*
1854
	 *
1855
	 * Jetpack Security Reports
1856
	 *
1857
	 * Allowed types: login_form, backup, file_scanning, spam
1858
	 *
1859
	 * Args for login_form and spam: 'blocked'=>(int)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1860
	 *
1861
	 * Args for backup and file_scanning: 'last'=>(timestamp)(optional), 'next'=>(timestamp)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1862
	 *
1863
	 *
1864
	 * Example code to submit a security report:
1865
	 *
1866
	 *  function akismet_submit_jetpack_security_report() {
1867
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1868
	 *  }
1869
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1870
	 *
1871
	 */
1872
1873
1874
	/**
1875
	 * Calls for security report submissions.
1876
	 *
1877
	 * @return null
1878
	 */
1879
	public static function perform_security_reporting() {
1880
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1881
1882
		if ( $no_check_needed ) {
1883
			return;
1884
		}
1885
1886
		/**
1887
		 * Fires before a security report is created.
1888
		 *
1889
		 * @since 3.4.0
1890
		 */
1891
		do_action( 'jetpack_security_report' );
1892
1893
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1894
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1895
	}
1896
1897
	/**
1898
	 * Allows plugins to submit security reports.
1899
 	 *
1900
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1901
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1902
	 * @param array   $args         See definitions above
1903
	 */
1904
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1905
1906
		if( !doing_action( 'jetpack_security_report' ) ) {
1907
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1908
		}
1909
1910
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1911
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1912
		}
1913
1914
		if( !function_exists( 'get_plugin_data' ) ) {
1915
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1916
		}
1917
1918
		//Get rid of any non-allowed args
1919
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1920
1921
		$plugin = get_plugin_data( $plugin_file );
1922
1923
		if ( !$plugin['Name'] ) {
1924
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1925
		}
1926
1927
		// Sanitize everything to make sure we're not syncing something wonky
1928
		$type = sanitize_key( $type );
1929
1930
		$args['plugin'] = $plugin;
1931
1932
		// Cast blocked, last and next as integers.
1933
		// Last and next should be in unix timestamp format
1934
		if ( isset( $args['blocked'] ) ) {
1935
			$args['blocked'] = (int) $args['blocked'];
1936
		}
1937
		if ( isset( $args['last'] ) ) {
1938
			$args['last'] = (int) $args['last'];
1939
		}
1940
		if ( isset( $args['next'] ) ) {
1941
			$args['next'] = (int) $args['next'];
1942
		}
1943
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1944
			$args['status'] = 'ok';
1945
		}
1946
		if ( isset( $args['message'] ) ) {
1947
1948
			if( $args['status'] == 'ok' ) {
1949
				unset( $args['message'] );
1950
			}
1951
1952
			$allowed_html = array(
1953
			    'a' => array(
1954
			        'href' => array(),
1955
			        'title' => array()
1956
			    ),
1957
			    'em' => array(),
1958
			    'strong' => array(),
1959
			);
1960
1961
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1962
		}
1963
1964
		$plugin_name = $plugin[ 'Name' ];
1965
1966
		self::$security_report[ $type ][ $plugin_name ] = $args;
1967
	}
1968
1969
	/**
1970
	 * Collects a new report if needed, then returns it.
1971
	 */
1972
	public function get_security_report() {
1973
		self::perform_security_reporting();
1974
		return Jetpack_Options::get_option( 'security_report' );
1975
	}
1976
1977
1978
/* Jetpack Options API */
1979
1980
	public static function get_option_names( $type = 'compact' ) {
1981
		return Jetpack_Options::get_option_names( $type );
1982
	}
1983
1984
	/**
1985
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1986
 	 *
1987
	 * @param string $name    Option name
1988
	 * @param mixed  $default (optional)
1989
	 */
1990
	public static function get_option( $name, $default = false ) {
1991
		return Jetpack_Options::get_option( $name, $default );
1992
	}
1993
1994
	/**
1995
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1996
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1997
	* $name must be a registered option name.
1998
	*/
1999
	public static function create_nonce( $name ) {
2000
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
2001
2002
		Jetpack_Options::update_option( $name, $secret );
2003
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2004
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2005
			return new Jetpack_Error( 'missing_secrets' );
2006
2007
		return array(
2008
			'secret_1' => $secret_1,
2009
			'secret_2' => $secret_2,
2010
			'eol'      => $eol,
2011
		);
2012
	}
2013
2014
	/**
2015
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2016
 	 *
2017
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2018
	 * @param string $name  Option name
2019
	 * @param mixed  $value Option value
2020
	 */
2021
	public static function update_option( $name, $value ) {
2022
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2023
		return Jetpack_Options::update_option( $name, $value );
2024
	}
2025
2026
	/**
2027
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2028
 	 *
2029
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2030
	 * @param array $array array( option name => option value, ... )
2031
	 */
2032
	public static function update_options( $array ) {
2033
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2034
		return Jetpack_Options::update_options( $array );
2035
	}
2036
2037
	/**
2038
	 * Deletes the given option.  May be passed multiple option names as an array.
2039
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2040
	 *
2041
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2042
	 * @param string|array $names
2043
	 */
2044
	public static function delete_option( $names ) {
2045
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2046
		return Jetpack_Options::delete_option( $names );
2047
	}
2048
2049
	/**
2050
	 * Enters a user token into the user_tokens option
2051
	 *
2052
	 * @param int $user_id
2053
	 * @param string $token
2054
	 * return bool
2055
	 */
2056
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2057
		// not designed for concurrent updates
2058
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2059
		if ( ! is_array( $user_tokens ) )
2060
			$user_tokens = array();
2061
		$user_tokens[$user_id] = $token;
2062
		if ( $is_master_user ) {
2063
			$master_user = $user_id;
2064
			$options     = compact( 'user_tokens', 'master_user' );
2065
		} else {
2066
			$options = compact( 'user_tokens' );
2067
		}
2068
		return Jetpack_Options::update_options( $options );
2069
	}
2070
2071
	/**
2072
	 * Returns an array of all PHP files in the specified absolute path.
2073
	 * Equivalent to glob( "$absolute_path/*.php" ).
2074
	 *
2075
	 * @param string $absolute_path The absolute path of the directory to search.
2076
	 * @return array Array of absolute paths to the PHP files.
2077
	 */
2078
	public static function glob_php( $absolute_path ) {
2079
		if ( function_exists( 'glob' ) ) {
2080
			return glob( "$absolute_path/*.php" );
2081
		}
2082
2083
		$absolute_path = untrailingslashit( $absolute_path );
2084
		$files = array();
2085
		if ( ! $dir = @opendir( $absolute_path ) ) {
2086
			return $files;
2087
		}
2088
2089
		while ( false !== $file = readdir( $dir ) ) {
2090
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2091
				continue;
2092
			}
2093
2094
			$file = "$absolute_path/$file";
2095
2096
			if ( ! is_file( $file ) ) {
2097
				continue;
2098
			}
2099
2100
			$files[] = $file;
2101
		}
2102
2103
		closedir( $dir );
2104
2105
		return $files;
2106
	}
2107
2108
	public static function activate_new_modules( $redirect = false ) {
2109
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2110
			return;
2111
		}
2112
2113
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2114 View Code Duplication
		if ( ! $jetpack_old_version ) {
2115
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2116
			/** This action is documented in class.jetpack.php */
2117
			do_action( 'updating_jetpack_version', $version, false );
2118
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2119
		}
2120
2121
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2122
2123
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2124
			return;
2125
		}
2126
2127
		$active_modules     = Jetpack::get_active_modules();
2128
		$reactivate_modules = array();
2129
		foreach ( $active_modules as $active_module ) {
2130
			$module = Jetpack::get_module( $active_module );
2131
			if ( ! isset( $module['changed'] ) ) {
2132
				continue;
2133
			}
2134
2135
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2136
				continue;
2137
			}
2138
2139
			$reactivate_modules[] = $active_module;
2140
			Jetpack::deactivate_module( $active_module );
2141
		}
2142
2143
		$new_version = JETPACK__VERSION . ':' . time();
2144
		/** This action is documented in class.jetpack.php */
2145
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2146
		Jetpack_Options::update_options(
2147
			array(
2148
				'version'     => $new_version,
2149
				'old_version' => $jetpack_old_version,
2150
			)
2151
		);
2152
2153
		Jetpack::state( 'message', 'modules_activated' );
2154
		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...
2155
2156
		if ( $redirect ) {
2157
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2158
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2159
				$page = $_GET['page'];
2160
			}
2161
2162
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2163
			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...
2164
		}
2165
	}
2166
2167
	/**
2168
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2169
	 * Make sure to tuck away module "library" files in a sub-directory.
2170
	 */
2171
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2172
		static $modules = null;
2173
2174
		if ( ! isset( $modules ) ) {
2175
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2176
			// Use the cache if we're on the front-end and it's available...
2177
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2178
				$modules = $available_modules_option[ JETPACK__VERSION ];
2179
			} else {
2180
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2181
2182
				$modules = array();
2183
2184
				foreach ( $files as $file ) {
2185
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2186
						continue;
2187
					}
2188
2189
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2190
				}
2191
2192
				Jetpack_Options::update_option( 'available_modules', array(
2193
					JETPACK__VERSION => $modules,
2194
				) );
2195
			}
2196
		}
2197
2198
		/**
2199
		 * Filters the array of modules available to be activated.
2200
		 *
2201
		 * @since 2.4.0
2202
		 *
2203
		 * @param array $modules Array of available modules.
2204
		 * @param string $min_version Minimum version number required to use modules.
2205
		 * @param string $max_version Maximum version number required to use modules.
2206
		 */
2207
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2208
2209
		if ( ! $min_version && ! $max_version ) {
2210
			return array_keys( $mods );
2211
		}
2212
2213
		$r = array();
2214
		foreach ( $mods as $slug => $introduced ) {
2215
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2216
				continue;
2217
			}
2218
2219
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2220
				continue;
2221
			}
2222
2223
			$r[] = $slug;
2224
		}
2225
2226
		return $r;
2227
	}
2228
2229
	/**
2230
	 * Default modules loaded on activation.
2231
	 */
2232
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2233
		$return = array();
2234
2235
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2236
			$module_data = Jetpack::get_module( $module );
2237
2238
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2239
				case 'yes' :
2240
					$return[] = $module;
2241
					break;
2242
				case 'public' :
2243
					if ( Jetpack_Options::get_option( 'public' ) ) {
2244
						$return[] = $module;
2245
					}
2246
					break;
2247
				case 'no' :
2248
				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...
2249
					break;
2250
			}
2251
		}
2252
		/**
2253
		 * Filters the array of default modules.
2254
		 *
2255
		 * @since 2.5.0
2256
		 *
2257
		 * @param array $return Array of default modules.
2258
		 * @param string $min_version Minimum version number required to use modules.
2259
		 * @param string $max_version Maximum version number required to use modules.
2260
		 */
2261
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2262
	}
2263
2264
	/**
2265
	 * Checks activated modules during auto-activation to determine
2266
	 * if any of those modules are being deprecated.  If so, close
2267
	 * them out, and add any replacement modules.
2268
	 *
2269
	 * Runs at priority 99 by default.
2270
	 *
2271
	 * This is run late, so that it can still activate a module if
2272
	 * the new module is a replacement for another that the user
2273
	 * currently has active, even if something at the normal priority
2274
	 * would kibosh everything.
2275
	 *
2276
	 * @since 2.6
2277
	 * @uses jetpack_get_default_modules filter
2278
	 * @param array $modules
2279
	 * @return array
2280
	 */
2281
	function handle_deprecated_modules( $modules ) {
2282
		$deprecated_modules = array(
2283
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2284
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2285
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2286
		);
2287
2288
		// Don't activate SSO if they never completed activating WPCC.
2289
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2290
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2291
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2292
				$deprecated_modules['wpcc'] = null;
2293
			}
2294
		}
2295
2296
		foreach ( $deprecated_modules as $module => $replacement ) {
2297
			if ( Jetpack::is_module_active( $module ) ) {
2298
				self::deactivate_module( $module );
2299
				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...
2300
					$modules[] = $replacement;
2301
				}
2302
			}
2303
		}
2304
2305
		return array_unique( $modules );
2306
	}
2307
2308
	/**
2309
	 * Checks activated plugins during auto-activation to determine
2310
	 * if any of those plugins are in the list with a corresponding module
2311
	 * that is not compatible with the plugin. The module will not be allowed
2312
	 * to auto-activate.
2313
	 *
2314
	 * @since 2.6
2315
	 * @uses jetpack_get_default_modules filter
2316
	 * @param array $modules
2317
	 * @return array
2318
	 */
2319
	function filter_default_modules( $modules ) {
2320
2321
		$active_plugins = self::get_active_plugins();
2322
2323
		if ( ! empty( $active_plugins ) ) {
2324
2325
			// For each module we'd like to auto-activate...
2326
			foreach ( $modules as $key => $module ) {
2327
				// If there are potential conflicts for it...
2328
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2329
					// For each potential conflict...
2330
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2331
						// If that conflicting plugin is active...
2332
						if ( in_array( $plugin, $active_plugins ) ) {
2333
							// Remove that item from being auto-activated.
2334
							unset( $modules[ $key ] );
2335
						}
2336
					}
2337
				}
2338
			}
2339
		}
2340
2341
		return $modules;
2342
	}
2343
2344
	/**
2345
	 * Extract a module's slug from its full path.
2346
	 */
2347
	public static function get_module_slug( $file ) {
2348
		return str_replace( '.php', '', basename( $file ) );
2349
	}
2350
2351
	/**
2352
	 * Generate a module's path from its slug.
2353
	 */
2354
	public static function get_module_path( $slug ) {
2355
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2356
	}
2357
2358
	/**
2359
	 * Load module data from module file. Headers differ from WordPress
2360
	 * plugin headers to avoid them being identified as standalone
2361
	 * plugins on the WordPress plugins page.
2362
	 */
2363
	public static function get_module( $module ) {
2364
		$headers = array(
2365
			'name'                      => 'Module Name',
2366
			'description'               => 'Module Description',
2367
			'jumpstart_desc'            => 'Jumpstart Description',
2368
			'sort'                      => 'Sort Order',
2369
			'recommendation_order'      => 'Recommendation Order',
2370
			'introduced'                => 'First Introduced',
2371
			'changed'                   => 'Major Changes In',
2372
			'deactivate'                => 'Deactivate',
2373
			'free'                      => 'Free',
2374
			'requires_connection'       => 'Requires Connection',
2375
			'auto_activate'             => 'Auto Activate',
2376
			'module_tags'               => 'Module Tags',
2377
			'feature'                   => 'Feature',
2378
			'additional_search_queries' => 'Additional Search Queries',
2379
		);
2380
2381
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2382
2383
		$mod = Jetpack::get_file_data( $file, $headers );
2384
		if ( empty( $mod['name'] ) ) {
2385
			return false;
2386
		}
2387
2388
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2389
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2390
		$mod['deactivate']              = empty( $mod['deactivate'] );
2391
		$mod['free']                    = empty( $mod['free'] );
2392
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2393
2394
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2395
			$mod['auto_activate'] = 'No';
2396
		} else {
2397
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2398
		}
2399
2400
		if ( $mod['module_tags'] ) {
2401
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2402
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2403
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2404
		} else {
2405
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2406
		}
2407
2408
		if ( $mod['feature'] ) {
2409
			$mod['feature'] = explode( ',', $mod['feature'] );
2410
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2411
		} else {
2412
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2413
		}
2414
2415
		/**
2416
		 * Filters the feature array on a module.
2417
		 *
2418
		 * This filter allows you to control where each module is filtered: Recommended,
2419
		 * Jumpstart, and the default "Other" listing.
2420
		 *
2421
		 * @since 3.5.0
2422
		 *
2423
		 * @param array   $mod['feature'] The areas to feature this module:
2424
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2425
		 *     'Recommended' shows on the main Jetpack admin screen.
2426
		 *     'Other' should be the default if no other value is in the array.
2427
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2428
		 * @param array   $mod All the currently assembled module data.
2429
		 */
2430
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2431
2432
		/**
2433
		 * Filter the returned data about a module.
2434
		 *
2435
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2436
		 * so please be careful.
2437
		 *
2438
		 * @since 3.6.0
2439
		 *
2440
		 * @param array   $mod    The details of the requested module.
2441
		 * @param string  $module The slug of the module, e.g. sharedaddy
2442
		 * @param string  $file   The path to the module source file.
2443
		 */
2444
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2445
	}
2446
2447
	/**
2448
	 * Like core's get_file_data implementation, but caches the result.
2449
	 */
2450
	public static function get_file_data( $file, $headers ) {
2451
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2452
		$file_name = basename( $file );
2453
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2454
		$key              = md5( $file_name . serialize( $headers ) );
2455
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2456
2457
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2458
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2459
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2460
		}
2461
2462
		$data = get_file_data( $file, $headers );
2463
2464
		// Strip out any old Jetpack versions that are cluttering the option.
2465
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2466
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2467
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2468
2469
		return $data;
2470
	}
2471
2472
	/**
2473
	 * Return translated module tag.
2474
	 *
2475
	 * @param string $tag Tag as it appears in each module heading.
2476
	 *
2477
	 * @return mixed
2478
	 */
2479
	public static function translate_module_tag( $tag ) {
2480
		return jetpack_get_module_i18n_tag( $tag );
2481
	}
2482
2483
	/**
2484
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2485
	 *
2486
	 * @since 3.9.2
2487
	 *
2488
	 * @param array $modules
2489
	 *
2490
	 * @return string|void
2491
	 */
2492
	public static function get_translated_modules( $modules ) {
2493
		foreach ( $modules as $index => $module ) {
2494
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2495
			if ( isset( $module['name'] ) ) {
2496
				$modules[ $index ]['name'] = $i18n_module['name'];
2497
			}
2498
			if ( isset( $module['description'] ) ) {
2499
				$modules[ $index ]['description'] = $i18n_module['description'];
2500
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2501
			}
2502
		}
2503
		return $modules;
2504
	}
2505
2506
	/**
2507
	 * Get a list of activated modules as an array of module slugs.
2508
	 */
2509
	public static function get_active_modules() {
2510
		$active = Jetpack_Options::get_option( 'active_modules' );
2511
		if ( ! is_array( $active ) )
2512
			$active = array();
2513
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2514
			$active[] = 'vaultpress';
2515
		} else {
2516
			$active = array_diff( $active, array( 'vaultpress' ) );
2517
		}
2518
2519
		//If protect is active on the main site of a multisite, it should be active on all sites.
2520
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2521
			$active[] = 'protect';
2522
		}
2523
2524
		return array_unique( $active );
2525
	}
2526
2527
	/**
2528
	 * Check whether or not a Jetpack module is active.
2529
	 *
2530
	 * @param string $module The slug of a Jetpack module.
2531
	 * @return bool
2532
	 *
2533
	 * @static
2534
	 */
2535
	public static function is_module_active( $module ) {
2536
		return in_array( $module, self::get_active_modules() );
2537
	}
2538
2539
	public static function is_module( $module ) {
2540
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2541
	}
2542
2543
	/**
2544
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2545
	 *
2546
	 * @param bool $catch True to start catching, False to stop.
2547
	 *
2548
	 * @static
2549
	 */
2550
	public static function catch_errors( $catch ) {
2551
		static $display_errors, $error_reporting;
2552
2553
		if ( $catch ) {
2554
			$display_errors  = @ini_set( 'display_errors', 1 );
2555
			$error_reporting = @error_reporting( E_ALL );
2556
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2557
		} else {
2558
			@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...
2559
			@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...
2560
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2561
		}
2562
	}
2563
2564
	/**
2565
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2566
	 */
2567
	public static function catch_errors_on_shutdown() {
2568
		Jetpack::state( 'php_errors', ob_get_clean() );
2569
	}
2570
2571
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2572
		$jetpack = Jetpack::init();
2573
2574
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2575
		$modules = array_merge( $other_modules, $modules );
2576
2577
		// Look for standalone plugins and disable if active.
2578
2579
		$to_deactivate = array();
2580
		foreach ( $modules as $module ) {
2581
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2582
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2583
			}
2584
		}
2585
2586
		$deactivated = array();
2587
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2588
			list( $probable_file, $probable_title ) = $deactivate_me;
2589
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2590
				$deactivated[] = $module;
2591
			}
2592
		}
2593
2594
		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...
2595
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2596
2597
			$url = add_query_arg(
2598
				array(
2599
					'action'   => 'activate_default_modules',
2600
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2601
				),
2602
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2603
			);
2604
			wp_safe_redirect( $url );
2605
			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...
2606
		}
2607
2608
		/**
2609
		 * Fires before default modules are activated.
2610
		 *
2611
		 * @since 1.9.0
2612
		 *
2613
		 * @param string $min_version Minimum version number required to use modules.
2614
		 * @param string $max_version Maximum version number required to use modules.
2615
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2616
		 */
2617
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2618
2619
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2620
		Jetpack::restate();
2621
		Jetpack::catch_errors( true );
2622
2623
		$active = Jetpack::get_active_modules();
2624
2625
		foreach ( $modules as $module ) {
2626
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2627
				$active[] = $module;
2628
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2629
				continue;
2630
			}
2631
2632
			if ( in_array( $module, $active ) ) {
2633
				$module_info = Jetpack::get_module( $module );
2634
				if ( ! $module_info['deactivate'] ) {
2635
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2636 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2637
						$active_state = explode( ',', $active_state );
2638
					} else {
2639
						$active_state = array();
2640
					}
2641
					$active_state[] = $module;
2642
					Jetpack::state( $state, implode( ',', $active_state ) );
2643
				}
2644
				continue;
2645
			}
2646
2647
			$file = Jetpack::get_module_path( $module );
2648
			if ( ! file_exists( $file ) ) {
2649
				continue;
2650
			}
2651
2652
			// we'll override this later if the plugin can be included without fatal error
2653
			if ( $redirect ) {
2654
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2655
			}
2656
			Jetpack::state( 'error', 'module_activation_failed' );
2657
			Jetpack::state( 'module', $module );
2658
			ob_start();
2659
			require $file;
2660
			/**
2661
			 * Fires when a specific module is activated.
2662
			 *
2663
			 * @since 1.9.0
2664
			 *
2665
			 * @param string $module Module slug.
2666
			 */
2667
			do_action( 'jetpack_activate_module', $module );
2668
			$active[] = $module;
2669
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2670 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2671
				$active_state = explode( ',', $active_state );
2672
			} else {
2673
				$active_state = array();
2674
			}
2675
			$active_state[] = $module;
2676
			Jetpack::state( $state, implode( ',', $active_state ) );
2677
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2678
			ob_end_clean();
2679
		}
2680
		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...
2681
		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...
2682
		Jetpack::catch_errors( false );
2683
		/**
2684
		 * Fires when default modules are activated.
2685
		 *
2686
		 * @since 1.9.0
2687
		 *
2688
		 * @param string $min_version Minimum version number required to use modules.
2689
		 * @param string $max_version Maximum version number required to use modules.
2690
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2691
		 */
2692
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2693
	}
2694
2695
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2696
		/**
2697
		 * Fires before a module is activated.
2698
		 *
2699
		 * @since 2.6.0
2700
		 *
2701
		 * @param string $module Module slug.
2702
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2703
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2704
		 */
2705
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2706
2707
		$jetpack = Jetpack::init();
2708
2709
		if ( ! strlen( $module ) )
2710
			return false;
2711
2712
		if ( ! Jetpack::is_module( $module ) )
2713
			return false;
2714
2715
		// If it's already active, then don't do it again
2716
		$active = Jetpack::get_active_modules();
2717
		foreach ( $active as $act ) {
2718
			if ( $act == $module )
2719
				return true;
2720
		}
2721
2722
		$module_data = Jetpack::get_module( $module );
2723
2724
		if ( ! Jetpack::is_active() ) {
2725
			if ( !Jetpack::is_development_mode() )
2726
				return false;
2727
2728
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2729
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2730
				return false;
2731
		}
2732
2733
		// Check and see if the old plugin is active
2734
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2735
			// Deactivate the old plugin
2736
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2737
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2738
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2739
				Jetpack::state( 'deactivated_plugins', $module );
2740
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2741
				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...
2742
			}
2743
		}
2744
2745
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2746
		Jetpack::state( 'module', $module );
2747
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2748
2749
		Jetpack::catch_errors( true );
2750
		ob_start();
2751
		require Jetpack::get_module_path( $module );
2752
		/** This action is documented in class.jetpack.php */
2753
		do_action( 'jetpack_activate_module', $module );
2754
		$active[] = $module;
2755
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2756
		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...
2757
		Jetpack::state( 'message', 'module_activated' );
2758
		Jetpack::state( 'module', $module );
2759
		ob_end_clean();
2760
		Jetpack::catch_errors( false );
2761
2762
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2763 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2764
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2765
2766
			//Jump start is being dismissed send data to MC Stats
2767
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2768
2769
			$jetpack->do_stats( 'server_side' );
2770
		}
2771
2772
		if ( $redirect ) {
2773
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2774
		}
2775
		if ( $exit ) {
2776
			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...
2777
		}
2778
		return true;
2779
	}
2780
2781
	function activate_module_actions( $module ) {
2782
		/**
2783
		 * Fires when a module is activated.
2784
		 * The dynamic part of the filter, $module, is the module slug.
2785
		 *
2786
		 * @since 1.9.0
2787
		 *
2788
		 * @param string $module Module slug.
2789
		 */
2790
		do_action( "jetpack_activate_module_$module", $module );
2791
2792
		$this->sync->sync_all_module_options( $module );
2793
	}
2794
2795
	public static function deactivate_module( $module ) {
2796
		/**
2797
		 * Fires when a module is deactivated.
2798
		 *
2799
		 * @since 1.9.0
2800
		 *
2801
		 * @param string $module Module slug.
2802
		 */
2803
		do_action( 'jetpack_pre_deactivate_module', $module );
2804
2805
		$jetpack = Jetpack::init();
2806
2807
		$active = Jetpack::get_active_modules();
2808
		$new    = array_filter( array_diff( $active, (array) $module ) );
2809
2810
		/**
2811
		 * Fires when a module is deactivated.
2812
		 * The dynamic part of the filter, $module, is the module slug.
2813
		 *
2814
		 * @since 1.9.0
2815
		 *
2816
		 * @param string $module Module slug.
2817
		 */
2818
		do_action( "jetpack_deactivate_module_$module", $module );
2819
2820
		// A flag for Jump Start so it's not shown again.
2821 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2822
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2823
2824
			//Jump start is being dismissed send data to MC Stats
2825
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2826
2827
			$jetpack->do_stats( 'server_side' );
2828
		}
2829
2830
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2831
	}
2832
2833
	public static function enable_module_configurable( $module ) {
2834
		$module = Jetpack::get_module_slug( $module );
2835
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2836
	}
2837
2838
	public static function module_configuration_url( $module ) {
2839
		$module = Jetpack::get_module_slug( $module );
2840
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2841
	}
2842
2843
	public static function module_configuration_load( $module, $method ) {
2844
		$module = Jetpack::get_module_slug( $module );
2845
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2846
	}
2847
2848
	public static function module_configuration_head( $module, $method ) {
2849
		$module = Jetpack::get_module_slug( $module );
2850
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2851
	}
2852
2853
	public static function module_configuration_screen( $module, $method ) {
2854
		$module = Jetpack::get_module_slug( $module );
2855
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2856
	}
2857
2858
	public static function module_configuration_activation_screen( $module, $method ) {
2859
		$module = Jetpack::get_module_slug( $module );
2860
		add_action( 'display_activate_module_setting_' . $module, $method );
2861
	}
2862
2863
/* Installation */
2864
2865
	public static function bail_on_activation( $message, $deactivate = true ) {
2866
?>
2867
<!doctype html>
2868
<html>
2869
<head>
2870
<meta charset="<?php bloginfo( 'charset' ); ?>">
2871
<style>
2872
* {
2873
	text-align: center;
2874
	margin: 0;
2875
	padding: 0;
2876
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2877
}
2878
p {
2879
	margin-top: 1em;
2880
	font-size: 18px;
2881
}
2882
</style>
2883
<body>
2884
<p><?php echo esc_html( $message ); ?></p>
2885
</body>
2886
</html>
2887
<?php
2888
		if ( $deactivate ) {
2889
			$plugins = get_option( 'active_plugins' );
2890
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2891
			$update  = false;
2892
			foreach ( $plugins as $i => $plugin ) {
2893
				if ( $plugin === $jetpack ) {
2894
					$plugins[$i] = false;
2895
					$update = true;
2896
				}
2897
			}
2898
2899
			if ( $update ) {
2900
				update_option( 'active_plugins', array_filter( $plugins ) );
2901
			}
2902
		}
2903
		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...
2904
	}
2905
2906
	/**
2907
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2908
	 * @static
2909
	 */
2910
	public static function plugin_activation( $network_wide ) {
2911
		Jetpack_Options::update_option( 'activated', 1 );
2912
2913
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2914
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2915
		}
2916
2917
		if ( $network_wide )
2918
			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...
2919
2920
		Jetpack::plugin_initialize();
2921
	}
2922
	/**
2923
	 * Runs before bumping version numbers up to a new version
2924
	 * @param  (string) $version    Version:timestamp
2925
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2926
	 * @return null              [description]
2927
	 */
2928
	public static function do_version_bump( $version, $old_version ) {
2929
2930
		if ( ! $old_version ) { // For new sites
2931
			// Setting up jetpack manage
2932
			Jetpack::activate_manage();
2933
		}
2934
	}
2935
2936
	/**
2937
	 * Sets the internal version number and activation state.
2938
	 * @static
2939
	 */
2940
	public static function plugin_initialize() {
2941
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2942
			Jetpack_Options::update_option( 'activated', 2 );
2943
		}
2944
2945 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2946
			$version = $old_version = JETPACK__VERSION . ':' . time();
2947
			/** This action is documented in class.jetpack.php */
2948
			do_action( 'updating_jetpack_version', $version, false );
2949
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2950
		}
2951
2952
		Jetpack::load_modules();
2953
2954
		Jetpack_Options::delete_option( 'do_activate' );
2955
	}
2956
2957
	/**
2958
	 * Removes all connection options
2959
	 * @static
2960
	 */
2961
	public static function plugin_deactivation( ) {
2962
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2963
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2964
			Jetpack_Network::init()->deactivate();
2965
		} else {
2966
			Jetpack::disconnect( false );
2967
			//Jetpack_Heartbeat::init()->deactivate();
2968
		}
2969
	}
2970
2971
	/**
2972
	 * Disconnects from the Jetpack servers.
2973
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2974
	 * @static
2975
	 */
2976
	public static function disconnect( $update_activated_state = true ) {
2977
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2978
		Jetpack::clean_nonces( true );
2979
2980
		Jetpack::load_xml_rpc_client();
2981
		$xml = new Jetpack_IXR_Client();
2982
		$xml->query( 'jetpack.deregister' );
2983
2984
		Jetpack_Options::delete_option(
2985
			array(
2986
				'register',
2987
				'blog_token',
2988
				'user_token',
2989
				'user_tokens',
2990
				'master_user',
2991
				'time_diff',
2992
				'fallback_no_verify_ssl_certs',
2993
			)
2994
		);
2995
2996
		if ( $update_activated_state ) {
2997
			Jetpack_Options::update_option( 'activated', 4 );
2998
		}
2999
3000
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
3001
		// Check then record unique disconnection if site has never been disconnected previously
3002
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
3003
			$jetpack_unique_connection['disconnected'] = 1;
3004
		}
3005
		else {
3006
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3007
				//track unique disconnect
3008
				$jetpack = Jetpack::init();
3009
3010
				$jetpack->stat( 'connections', 'unique-disconnect' );
3011
				$jetpack->do_stats( 'server_side' );
3012
			}
3013
			// increment number of times disconnected
3014
			$jetpack_unique_connection['disconnected'] += 1;
3015
		}
3016
3017
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3018
3019
		// Disable the Heartbeat cron
3020
		Jetpack_Heartbeat::init()->deactivate();
3021
	}
3022
3023
	/**
3024
	 * Unlinks the current user from the linked WordPress.com user
3025
	 */
3026
	public static function unlink_user( $user_id = null ) {
3027
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3028
			return false;
3029
3030
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3031
3032
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3033
			return false;
3034
3035
		if ( ! isset( $tokens[ $user_id ] ) )
3036
			return false;
3037
3038
		Jetpack::load_xml_rpc_client();
3039
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3040
		$xml->query( 'jetpack.unlink_user', $user_id );
3041
3042
		unset( $tokens[ $user_id ] );
3043
3044
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3045
3046
		return true;
3047
	}
3048
3049
	/**
3050
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3051
	 */
3052
	public static function try_registration() {
3053
		// Let's get some testing in beta versions and such.
3054
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3055
			// Before attempting to connect, let's make sure that the domains are viable.
3056
			$domains_to_check = array_unique( array(
3057
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3058
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3059
			) );
3060
			foreach ( $domains_to_check as $domain ) {
3061
				$result = Jetpack_Data::is_usable_domain( $domain );
3062
				if ( is_wp_error( $result ) ) {
3063
					return $result;
3064
				}
3065
			}
3066
		}
3067
3068
		$result = Jetpack::register();
3069
3070
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3071
		if ( ! $result || is_wp_error( $result ) ) {
3072
			return $result;
3073
		} else {
3074
			return true;
3075
		}
3076
	}
3077
3078
	/**
3079
	 * Tracking an internal event log. Try not to put too much chaff in here.
3080
	 *
3081
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3082
	 */
3083
	public static function log( $code, $data = null ) {
3084
		// only grab the latest 200 entries
3085
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3086
3087
		// Append our event to the log
3088
		$log_entry = array(
3089
			'time'    => time(),
3090
			'user_id' => get_current_user_id(),
3091
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3092
			'code'    => $code,
3093
		);
3094
		// Don't bother storing it unless we've got some.
3095
		if ( ! is_null( $data ) ) {
3096
			$log_entry['data'] = $data;
3097
		}
3098
		$log[] = $log_entry;
3099
3100
		// Try add_option first, to make sure it's not autoloaded.
3101
		// @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...
3102
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3103
			Jetpack_Options::update_option( 'log', $log );
3104
		}
3105
3106
		/**
3107
		 * Fires when Jetpack logs an internal event.
3108
		 *
3109
		 * @since 3.0.0
3110
		 *
3111
		 * @param array $log_entry {
3112
		 *	Array of details about the log entry.
3113
		 *
3114
		 *	@param string time Time of the event.
3115
		 *	@param int user_id ID of the user who trigerred the event.
3116
		 *	@param int blog_id Jetpack Blog ID.
3117
		 *	@param string code Unique name for the event.
3118
		 *	@param string data Data about the event.
3119
		 * }
3120
		 */
3121
		do_action( 'jetpack_log_entry', $log_entry );
3122
	}
3123
3124
	/**
3125
	 * Get the internal event log.
3126
	 *
3127
	 * @param $event (string) - only return the specific log events
3128
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3129
	 *
3130
	 * @return array of log events || WP_Error for invalid params
3131
	 */
3132
	public static function get_log( $event = false, $num = false ) {
3133
		if ( $event && ! is_string( $event ) ) {
3134
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3135
		}
3136
3137
		if ( $num && ! is_numeric( $num ) ) {
3138
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3139
		}
3140
3141
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3142
3143
		// If nothing set - act as it did before, otherwise let's start customizing the output
3144
		if ( ! $num && ! $event ) {
3145
			return $entire_log;
3146
		} else {
3147
			$entire_log = array_reverse( $entire_log );
3148
		}
3149
3150
		$custom_log_output = array();
3151
3152
		if ( $event ) {
3153
			foreach ( $entire_log as $log_event ) {
3154
				if ( $event == $log_event[ 'code' ] ) {
3155
					$custom_log_output[] = $log_event;
3156
				}
3157
			}
3158
		} else {
3159
			$custom_log_output = $entire_log;
3160
		}
3161
3162
		if ( $num ) {
3163
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3164
		}
3165
3166
		return $custom_log_output;
3167
	}
3168
3169
	/**
3170
	 * Log modification of important settings.
3171
	 */
3172
	public static function log_settings_change( $option, $old_value, $value ) {
3173
		switch( $option ) {
3174
			case 'jetpack_sync_non_public_post_stati':
3175
				self::log( $option, $value );
3176
				break;
3177
		}
3178
	}
3179
3180
	/**
3181
	 * Return stat data for WPCOM sync
3182
	 */
3183
	function get_stat_data() {
3184
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3185
		$additional_data = $this->get_additional_stat_data();
3186
3187
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3188
	}
3189
3190
	/**
3191
	 * Get additional stat data to sync to WPCOM
3192
	 */
3193
	function get_additional_stat_data( $prefix = '' ) {
3194
		$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...
3195
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3196
		$return["{$prefix}users"]          = count_users();
3197
		$return["{$prefix}site-count"]     = 0;
3198
		if ( function_exists( 'get_blog_count' ) ) {
3199
			$return["{$prefix}site-count"] = get_blog_count();
3200
		}
3201
		return $return;
3202
	}
3203
3204
	/* Admin Pages */
3205
3206
	function admin_init() {
3207
		// If the plugin is not connected, display a connect message.
3208
		if (
3209
			// the plugin was auto-activated and needs its candy
3210
			Jetpack_Options::get_option( 'do_activate' )
3211
		||
3212
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3213
			! Jetpack_Options::get_option( 'activated' )
3214
		) {
3215
			Jetpack::plugin_initialize();
3216
		}
3217
3218
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3219
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3220
				// Show connect notice on dashboard and plugins pages
3221
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3222
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3223
			}
3224
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3225
			// Upgrade: 1.1 -> 1.1.1
3226
			// Check and see if host can verify the Jetpack servers' SSL certificate
3227
			$args = array();
3228
			Jetpack_Client::_wp_remote_request(
3229
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3230
				$args,
3231
				true
3232
			);
3233
		} else {
3234
			// Show the notice on the Dashboard only for now
3235
3236
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3237
3238
			// Identity crisis notices
3239
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3240
		}
3241
3242
		// If the plugin has just been disconnected from WP.com, show the survey notice
3243
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3244
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3245
		}
3246
3247
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3248
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3249
		}
3250
3251
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3252
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3253
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3254
3255
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3256
			// Artificially throw errors in certain whitelisted cases during plugin activation
3257
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3258
3259
			// Kick off synchronization of user role when it changes
3260
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3261
		}
3262
3263
		// Jetpack Manage Activation Screen from .com
3264
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3265
	}
3266
3267
	function admin_body_class( $admin_body_class = '' ) {
3268
		$classes = explode( ' ', trim( $admin_body_class ) );
3269
3270
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3271
3272
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3273
		return " $admin_body_class ";
3274
	}
3275
3276
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3277
		return $admin_body_class . ' jetpack-pagestyles ';
3278
	}
3279
3280
	function prepare_connect_notice() {
3281
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3282
3283
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3284
3285
		if ( Jetpack::state( 'network_nag' ) )
3286
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3287
	}
3288
	/**
3289
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3290
	 *
3291
	 * @return null
3292
	 */
3293
	function prepare_manage_jetpack_notice() {
3294
3295
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3296
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3297
	}
3298
3299
	function manage_activate_screen() {
3300
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3301
	}
3302
	/**
3303
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3304
	 * This function artificially throws errors for such cases (whitelisted).
3305
	 *
3306
	 * @param string $plugin The activated plugin.
3307
	 */
3308
	function throw_error_on_activate_plugin( $plugin ) {
3309
		$active_modules = Jetpack::get_active_modules();
3310
3311
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3312
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3313
			$throw = false;
3314
3315
			// Try and make sure it really was the stats plugin
3316
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3317
				if ( 'stats.php' == basename( $plugin ) ) {
3318
					$throw = true;
3319
				}
3320
			} else {
3321
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3322
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3323
					$throw = true;
3324
				}
3325
			}
3326
3327
			if ( $throw ) {
3328
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3329
			}
3330
		}
3331
	}
3332
3333
	function intercept_plugin_error_scrape_init() {
3334
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3335
	}
3336
3337
	function intercept_plugin_error_scrape( $action, $result ) {
3338
		if ( ! $result ) {
3339
			return;
3340
		}
3341
3342
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3343
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3344
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3345
			}
3346
		}
3347
	}
3348
3349
	function add_remote_request_handlers() {
3350
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3351
	}
3352
3353
	function remote_request_handlers() {
3354
		switch ( current_filter() ) {
3355
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3356
			$response = $this->upload_handler();
3357
			break;
3358
		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...
3359
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3360
			break;
3361
		}
3362
3363
		if ( ! $response ) {
3364
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3365
		}
3366
3367
		if ( is_wp_error( $response ) ) {
3368
			$status_code       = $response->get_error_data();
3369
			$error             = $response->get_error_code();
3370
			$error_description = $response->get_error_message();
3371
3372
			if ( ! is_int( $status_code ) ) {
3373
				$status_code = 400;
3374
			}
3375
3376
			status_header( $status_code );
3377
			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...
3378
		}
3379
3380
		status_header( 200 );
3381
		if ( true === $response ) {
3382
			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...
3383
		}
3384
3385
		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...
3386
	}
3387
3388
	function upload_handler() {
3389
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3390
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3391
		}
3392
3393
		$user = wp_authenticate( '', '' );
3394
		if ( ! $user || is_wp_error( $user ) ) {
3395
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3396
		}
3397
3398
		wp_set_current_user( $user->ID );
3399
3400
		if ( ! current_user_can( 'upload_files' ) ) {
3401
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3402
		}
3403
3404
		if ( empty( $_FILES ) ) {
3405
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3406
		}
3407
3408
		foreach ( array_keys( $_FILES ) as $files_key ) {
3409
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3410
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3411
			}
3412
		}
3413
3414
		$media_keys = array_keys( $_FILES['media'] );
3415
3416
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3417
		if ( ! $token || is_wp_error( $token ) ) {
3418
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3419
		}
3420
3421
		$uploaded_files = array();
3422
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3423
		unset( $GLOBALS['post'] );
3424
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3425
			$file = array();
3426
			foreach ( $media_keys as $media_key ) {
3427
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3428
			}
3429
3430
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3431
3432
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3433
			if ( $hmac_provided !== $hmac_file ) {
3434
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3435
				continue;
3436
			}
3437
3438
			$_FILES['.jetpack.upload.'] = $file;
3439
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3440
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3441
				$post_id = 0;
3442
			}
3443
			$attachment_id = media_handle_upload(
3444
				'.jetpack.upload.',
3445
				$post_id,
3446
				array(),
3447
				array(
3448
					'action' => 'jetpack_upload_file',
3449
				)
3450
			);
3451
3452
			if ( ! $attachment_id ) {
3453
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3454
			} elseif ( is_wp_error( $attachment_id ) ) {
3455
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3456
			} else {
3457
				$attachment = get_post( $attachment_id );
3458
				$uploaded_files[$index] = (object) array(
3459
					'id'   => (string) $attachment_id,
3460
					'file' => $attachment->post_title,
3461
					'url'  => wp_get_attachment_url( $attachment_id ),
3462
					'type' => $attachment->post_mime_type,
3463
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3464
				);
3465
			}
3466
		}
3467
		if ( ! is_null( $global_post ) ) {
3468
			$GLOBALS['post'] = $global_post;
3469
		}
3470
3471
		return $uploaded_files;
3472
	}
3473
3474
	/**
3475
	 * Add help to the Jetpack page
3476
	 *
3477
	 * @since Jetpack (1.2.3)
3478
	 * @return false if not the Jetpack page
3479
	 */
3480
	function admin_help() {
3481
		$current_screen = get_current_screen();
3482
3483
		// Overview
3484
		$current_screen->add_help_tab(
3485
			array(
3486
				'id'		=> 'home',
3487
				'title'		=> __( 'Home', 'jetpack' ),
3488
				'content'	=>
3489
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3490
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3491
					'<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>',
3492
			)
3493
		);
3494
3495
		// Screen Content
3496
		if ( current_user_can( 'manage_options' ) ) {
3497
			$current_screen->add_help_tab(
3498
				array(
3499
					'id'		=> 'settings',
3500
					'title'		=> __( 'Settings', 'jetpack' ),
3501
					'content'	=>
3502
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3503
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3504
						'<ol>' .
3505
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3506
							'<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>' .
3507
						'</ol>' .
3508
						'<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>'
3509
				)
3510
			);
3511
		}
3512
3513
		// Help Sidebar
3514
		$current_screen->set_help_sidebar(
3515
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3516
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3517
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3518
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3519
		);
3520
	}
3521
3522
	function admin_menu_css() {
3523
		wp_enqueue_style( 'jetpack-icons' );
3524
	}
3525
3526
	function admin_menu_order() {
3527
		return true;
3528
	}
3529
3530 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3531
		$jp_menu_order = array();
3532
3533
		foreach ( $menu_order as $index => $item ) {
3534
			if ( $item != 'jetpack' ) {
3535
				$jp_menu_order[] = $item;
3536
			}
3537
3538
			if ( $index == 0 ) {
3539
				$jp_menu_order[] = 'jetpack';
3540
			}
3541
		}
3542
3543
		return $jp_menu_order;
3544
	}
3545
3546
	function admin_head() {
3547 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3548
			/** This action is documented in class.jetpack-admin-page.php */
3549
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3550
	}
3551
3552
	function admin_banner_styles() {
3553
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3554
3555
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3556
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3557
		wp_style_add_data( 'jetpack', 'suffix', $min );
3558
	}
3559
3560
	function admin_scripts() {
3561
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3562
		wp_localize_script(
3563
			'jetpack-js',
3564
			'jetpackL10n',
3565
			array(
3566
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3567
				'ays_unlink'     => "This will prevent user-specific modules such as Publicize, Notifications and Post By Email from working.\nAre you sure you want to unlink?",
3568
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3569
			)
3570
		);
3571
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3572
	}
3573
3574
	function plugin_action_links( $actions ) {
3575
3576
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3577
3578
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3579
			return array_merge(
3580
				$jetpack_home,
3581
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3582
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3583
				$actions
3584
				);
3585
			}
3586
3587
		return array_merge( $jetpack_home, $actions );
3588
	}
3589
3590
	function admin_connect_notice() {
3591
		// Don't show the connect notice anywhere but the plugins.php after activating
3592
		$current = get_current_screen();
3593
		if ( 'plugins' !== $current->parent_base )
3594
			return;
3595
3596
		if ( ! current_user_can( 'jetpack_connect' ) )
3597
			return;
3598
3599
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3600
		?>
3601
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3602
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"></a>
3603
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3604
				<div class="jp-banner__content is-connection">
3605
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3606
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3607
				</div>
3608
				<div class="jp-banner__action-container is-connection">
3609
						<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3610
				</div>
3611 View Code Duplication
			<?php else : ?>
3612
				<div class="jp-banner__content">
3613
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3614
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3615
				</div>
3616
				<div class="jp-banner__action-container">
3617
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3618
				</div>
3619
			<?php endif; ?>
3620
		</div>
3621
3622
		<?php
3623
	}
3624
3625
	/**
3626
	 * This is the first banner
3627
	 * It should be visible only to user that can update the option
3628
	 * Are not connected
3629
	 *
3630
	 * @return null
3631
	 */
3632
	function admin_jetpack_manage_notice() {
3633
		$screen = get_current_screen();
3634
3635
		// Don't show the connect notice on the jetpack settings page.
3636
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3637
			return;
3638
3639
		// Only show it if don't have the managment option set.
3640
		// And not dismissed it already.
3641
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3642
			return;
3643
		}
3644
3645
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3646
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3647
		/**
3648
		 * I think it would be great to have different wordsing depending on where you are
3649
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3650
		 * etc..
3651
		 */
3652
3653
		?>
3654
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3655
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $opt_out_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice for now.', 'jetpack' ); ?>"></a>
3656
			<div class="jp-banner__content">
3657
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3658
				<p><?php printf( __( 'Manage multiple sites from one dashboard at wordpress.com/sites. Enabling allows all existing, connected Administrators to modify your site from WordPress.com. <a href="%s" target="_blank">Learn More</a>.', 'jetpack' ), 'http://jetpack.com/support/site-management' ); ?></p>
3659
			</div>
3660
			<div class="jp-banner__action-container is-opt-in">
3661
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3662
			</div>
3663
		</div>
3664
		<?php
3665
	}
3666
3667
	/**
3668
	 * Returns the url that the user clicks to remove the notice for the big banner
3669
	 * @return (string)
3670
	 */
3671
	function opt_out_jetpack_manage_url() {
3672
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3673
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3674
	}
3675
	/**
3676
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3677
	 * @return (string)
3678
	 */
3679
	function opt_in_jetpack_manage_url() {
3680
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3681
	}
3682
3683
	function opt_in_jetpack_manage_notice() {
3684
		?>
3685
		<div class="wrap">
3686
			<div id="message" class="jetpack-message is-opt-in">
3687
				<?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(), 'http://jetpack.com/support/site-management' ); ?>
3688
			</div>
3689
		</div>
3690
		<?php
3691
3692
	}
3693
	/**
3694
	 * Determines whether to show the notice of not true = display notice
3695
	 * @return (bool)
3696
	 */
3697
	function can_display_jetpack_manage_notice() {
3698
		// never display the notice to users that can't do anything about it anyways
3699
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3700
			return false;
3701
3702
		// don't display if we are in development more
3703
		if( Jetpack::is_development_mode() ) {
3704
			return false;
3705
		}
3706
		// don't display if the site is private
3707
		if(  ! Jetpack_Options::get_option( 'public' ) )
3708
			return false;
3709
3710
		/**
3711
		 * Should the Jetpack Remote Site Management notice be displayed.
3712
		 *
3713
		 * @since 3.3.0
3714
		 *
3715
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3716
		 */
3717
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3718
	}
3719
3720
	function network_connect_notice() {
3721
		?>
3722
		<div id="message" class="updated jetpack-message">
3723
			<div class="squeezer">
3724
				<h2><?php _e( '<strong>Jetpack is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'jetpack' ) ?></h2>
3725
			</div>
3726
		</div>
3727
		<?php
3728
	}
3729
3730
	public static function jetpack_comment_notice() {
3731
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3732
			return '';
3733
		}
3734
3735
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3736
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3737
3738
		if ( $jetpack_old_version ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $jetpack_old_version 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...
3739
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3740
				return '';
3741
			}
3742
		}
3743
3744
		if ( $jetpack_new_version ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $jetpack_new_version 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...
3745
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3746
				return '';
3747
			}
3748
		}
3749
3750
		return '<br /><br />' . sprintf(
3751
			__( 'Jetpack now includes Comments, which enables your visitors to use their WordPress.com, Twitter, or Facebook accounts when commenting on your site. To activate Comments, <a href="%s">%s</a>.', 'jetpack' ),
3752
			wp_nonce_url(
3753
				Jetpack::admin_url(
3754
					array(
3755
						'page'   => 'jetpack',
3756
						'action' => 'activate',
3757
						'module' => 'comments',
3758
					)
3759
				),
3760
				'jetpack_activate-comments'
3761
			),
3762
			__( 'click here', 'jetpack' )
3763
		);
3764
	}
3765
3766
	/**
3767
	 * Show the survey link when the user has just disconnected Jetpack.
3768
	 */
3769
	function disconnect_survey_notice() {
3770
		?>
3771
		<div class="wrap">
3772
			<div id="message" class="jetpack-message stay-visible">
3773
				<div class="squeezer">
3774
					<h2>
3775
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3776
						<br />
3777
						<?php echo sprintf(
3778
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3779
							'https://jetpack.com/survey-disconnected/',
3780
							'_blank'
3781
						); ?>
3782
					</h2>
3783
				</div>
3784
			</div>
3785
		</div>
3786
		<?php
3787
	}
3788
3789
	/*
3790
	 * Registration flow:
3791
	 * 1 - ::admin_page_load() action=register
3792
	 * 2 - ::try_registration()
3793
	 * 3 - ::register()
3794
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3795
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3796
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3797
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3798
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3799
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3800
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3801
	 *       jetpack_id, jetpack_secret, jetpack_public
3802
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3803
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3804
	 * 5 - user logs in with WP.com account
3805
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3806
	 *		- Jetpack_Client_Server::authorize()
3807
	 *		- Jetpack_Client_Server::get_token()
3808
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3809
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3810
	 *			- which responds with access_token, token_type, scope
3811
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3812
	 *		- Jetpack::activate_default_modules()
3813
	 *     		- Deactivates deprecated plugins
3814
	 *     		- Activates all default modules
3815
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3816
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3817
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3818
	 *     Done!
3819
	 */
3820
3821
	/**
3822
	 * Handles the page load events for the Jetpack admin page
3823
	 */
3824
	function admin_page_load() {
3825
		$error = false;
3826
3827
		// Make sure we have the right body class to hook stylings for subpages off of.
3828
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3829
3830
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3831
			// Should only be used in intermediate redirects to preserve state across redirects
3832
			Jetpack::restate();
3833
		}
3834
3835
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3836
			// User clicked in the iframe to link their accounts
3837
			if ( ! Jetpack::is_user_connected() ) {
3838
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3839
				if ( isset( $_GET['notes_iframe'] ) )
3840
					$connect_url .= '&notes_iframe';
3841
				wp_redirect( $connect_url );
3842
				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...
3843
			} else {
3844
				Jetpack::state( 'message', 'already_authorized' );
3845
				wp_safe_redirect( Jetpack::admin_url() );
3846
				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...
3847
			}
3848
		}
3849
3850
3851
		if ( isset( $_GET['action'] ) ) {
3852
			switch ( $_GET['action'] ) {
3853
			case 'authorize':
3854
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3855
					Jetpack::state( 'message', 'already_authorized' );
3856
					wp_safe_redirect( Jetpack::admin_url() );
3857
					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...
3858
				}
3859
				Jetpack::log( 'authorize' );
3860
				$client_server = new Jetpack_Client_Server;
3861
				$client_server->client_authorize();
3862
				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...
3863
			case 'register' :
3864
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3865
					$error = 'cheatin';
3866
					break;
3867
				}
3868
				check_admin_referer( 'jetpack-register' );
3869
				Jetpack::log( 'register' );
3870
				Jetpack::maybe_set_version_option();
3871
				$registered = Jetpack::try_registration();
3872
				if ( is_wp_error( $registered ) ) {
3873
					$error = $registered->get_error_code();
3874
					Jetpack::state( 'error_description', $registered->get_error_message() );
3875
					break;
3876
				}
3877
3878
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3879
3880
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3881
				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...
3882
			case 'activate' :
3883
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3884
					$error = 'cheatin';
3885
					break;
3886
				}
3887
3888
				$module = stripslashes( $_GET['module'] );
3889
				check_admin_referer( "jetpack_activate-$module" );
3890
				Jetpack::log( 'activate', $module );
3891
				Jetpack::activate_module( $module );
3892
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3893
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3894
				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...
3895
			case 'activate_default_modules' :
3896
				check_admin_referer( 'activate_default_modules' );
3897
				Jetpack::log( 'activate_default_modules' );
3898
				Jetpack::restate();
3899
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3900
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3901
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3902
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3903
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3904
				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...
3905
			case 'disconnect' :
3906
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3907
					$error = 'cheatin';
3908
					break;
3909
				}
3910
3911
				check_admin_referer( 'jetpack-disconnect' );
3912
				Jetpack::log( 'disconnect' );
3913
				Jetpack::disconnect();
3914
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3915
				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...
3916
			case 'reconnect' :
3917
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3918
					$error = 'cheatin';
3919
					break;
3920
				}
3921
3922
				check_admin_referer( 'jetpack-reconnect' );
3923
				Jetpack::log( 'reconnect' );
3924
				$this->disconnect();
3925
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3926
				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...
3927 View Code Duplication
			case 'deactivate' :
3928
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3929
					$error = 'cheatin';
3930
					break;
3931
				}
3932
3933
				$modules = stripslashes( $_GET['module'] );
3934
				check_admin_referer( "jetpack_deactivate-$modules" );
3935
				foreach ( explode( ',', $modules ) as $module ) {
3936
					Jetpack::log( 'deactivate', $module );
3937
					Jetpack::deactivate_module( $module );
3938
					Jetpack::state( 'message', 'module_deactivated' );
3939
				}
3940
				Jetpack::state( 'module', $modules );
3941
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3942
				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...
3943
			case 'unlink' :
3944
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3945
				check_admin_referer( 'jetpack-unlink' );
3946
				Jetpack::log( 'unlink' );
3947
				$this->unlink_user();
3948
				Jetpack::state( 'message', 'unlinked' );
3949
				if ( 'sub-unlink' == $redirect ) {
3950
					wp_safe_redirect( admin_url() );
3951
				} else {
3952
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3953
				}
3954
				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...
3955
			default:
3956
				/**
3957
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3958
				 *
3959
				 * @since 2.6.0
3960
				 *
3961
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3962
				 */
3963
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3964
			}
3965
		}
3966
3967
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3968
			self::activate_new_modules( true );
3969
		}
3970
3971
		switch ( $error ) {
3972
		case 'cheatin' :
3973
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3974
			break;
3975
		case 'access_denied' :
3976
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'http://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
3977
			break;
3978
		case 'wrong_state' :
3979
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3980
			break;
3981
		case 'invalid_client' :
3982
			// @todo re-register instead of deactivate/reactivate
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...
3983
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3984
			break;
3985
		case 'invalid_grant' :
3986
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3987
			break;
3988
		case 'site_inaccessible' :
3989
		case 'site_requires_authorization' :
3990
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3991
			break;
3992
		case 'module_activation_failed' :
3993
			$module = Jetpack::state( 'module' );
3994
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3995
				$this->error = sprintf( __( '%s could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' ), $mod['name'] );
3996
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3997
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3998
				}
3999
			} else {
4000
				$this->error = __( 'Module could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' );
4001
			}
4002
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
4003
				$this->error .= "<br />\n";
4004
				$this->error .= $php_errors;
4005
			}
4006
			break;
4007
		case 'master_user_required' :
4008
			$module = Jetpack::state( 'module' );
4009
			$module_name = '';
4010
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4011
				$module_name = $mod['name'];
4012
			}
4013
4014
			$master_user = Jetpack_Options::get_option( 'master_user' );
4015
			$master_userdata = get_userdata( $master_user ) ;
4016
			if ( $master_userdata ) {
4017
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
4018
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
4019
				} else {
4020
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
4021
				}
4022
				$this->error .= '  ' . sprintf( __( 'This module can only be altered by %s, the user who initiated the Jetpack connection on this site.' , 'jetpack' ), esc_html( $master_userdata->display_name ) );
4023
4024
			} else {
4025
				$this->error = sprintf( __( 'Only the user who initiated the Jetpack connection on this site can toggle %s, but that user no longer exists. This should not happen.', 'jetpack' ), $module_name );
4026
			}
4027
			break;
4028
		case 'not_public' :
4029
			$this->error = __( '<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. This usually means your site is not publicly accessible (localhost).', 'jetpack' );
4030
			break;
4031
		case 'wpcom_408' :
4032
		case 'wpcom_5??' :
4033
		case 'wpcom_bad_response' :
4034
		case 'wpcom_outage' :
4035
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
4036
			break;
4037
		case 'register_http_request_failed' :
4038
		case 'token_http_request_failed' :
4039
			$this->error = sprintf( __( 'Jetpack could not contact WordPress.com: %s.  This usually means something is incorrectly configured on your web host.', 'jetpack' ), "<code>$error</code>" );
4040
			break;
4041
		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...
4042
			if ( empty( $error ) ) {
4043
				break;
4044
			}
4045
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
4046
			// no break: fall through
4047
		case 'no_role' :
0 ignored issues
show
Unused Code introduced by
// no break: fall through case 'no_role': does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
4048
		case 'no_cap' :
4049
		case 'no_code' :
4050
		case 'no_state' :
4051
		case 'invalid_state' :
4052
		case 'invalid_request' :
4053
		case 'invalid_scope' :
4054
		case 'unsupported_response_type' :
4055
		case 'invalid_token' :
4056
		case 'no_token' :
4057
		case 'missing_secrets' :
4058
		case 'home_missing' :
4059
		case 'siteurl_missing' :
4060
		case 'gmt_offset_missing' :
4061
		case 'site_name_missing' :
4062
		case 'secret_1_missing' :
4063
		case 'secret_2_missing' :
4064
		case 'site_lang_missing' :
4065
		case 'home_malformed' :
4066
		case 'siteurl_malformed' :
4067
		case 'gmt_offset_malformed' :
4068
		case 'timezone_string_malformed' :
4069
		case 'site_name_malformed' :
4070
		case 'secret_1_malformed' :
4071
		case 'secret_2_malformed' :
4072
		case 'site_lang_malformed' :
4073
		case 'secrets_mismatch' :
4074
		case 'verify_secret_1_missing' :
4075
		case 'verify_secret_1_malformed' :
4076
		case 'verify_secrets_missing' :
4077
		case 'verify_secrets_mismatch' :
4078
			$error = esc_html( $error );
4079
			$this->error = sprintf( __( '<strong>Your Jetpack has a glitch.</strong>  We&#8217;re sorry for the inconvenience. Please try again later, if the issue continues please contact support with this message: %s', 'jetpack' ), "<code>$error</code>" );
4080
			if ( ! Jetpack::is_active() ) {
4081
				$this->error .= '<br />';
4082
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4083
			}
4084
			break;
4085
		}
4086
4087
		$message_code = Jetpack::state( 'message' );
4088
4089
		$active_state = Jetpack::state( 'activated_modules' );
4090
		if ( ! empty( $active_state ) ) {
4091
			$available    = Jetpack::get_available_modules();
4092
			$active_state = explode( ',', $active_state );
4093
			$active_state = array_intersect( $active_state, $available );
4094
			if ( count( $active_state ) ) {
4095
				foreach ( $active_state as $mod ) {
4096
					$this->stat( 'module-activated', $mod );
4097
				}
4098
			} else {
4099
				$active_state = false;
4100
			}
4101
		}
4102
		if( Jetpack::state( 'optin-manage' ) ) {
4103
			$activated_manage = $message_code;
4104
			$message_code = 'jetpack-manage';
4105
4106
		}
4107
		switch ( $message_code ) {
4108
		case 'modules_activated' :
4109
			$this->message = sprintf(
4110
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4111
				JETPACK__VERSION
4112
			);
4113
4114
			if ( $active_state ) {
4115
				$titles = array();
4116 View Code Duplication
				foreach ( $active_state as $mod ) {
4117
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4118
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4119
					}
4120
				}
4121
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $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...
4122
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4123
				}
4124
			}
4125
4126
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4127
				$titles = array();
4128 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4129
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4130
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4131
					}
4132
				}
4133
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $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...
4134
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4135
				}
4136
			}
4137
4138
			$this->message .= Jetpack::jetpack_comment_notice();
4139
			break;
4140
		case 'jetpack-manage':
4141
			$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>';
4142
			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...
4143
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4144
			}
4145
			break;
4146
		case 'module_activated' :
4147
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4148
				$this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking the Deactivate link next to each module.', 'jetpack' ), $module['name'] );
4149
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4150
			}
4151
			break;
4152
4153
		case 'module_deactivated' :
4154
			$modules = Jetpack::state( 'module' );
4155
			if ( ! $modules ) {
4156
				break;
4157
			}
4158
4159
			$module_names = array();
4160
			foreach ( explode( ',', $modules ) as $module_slug ) {
4161
				$module = Jetpack::get_module( $module_slug );
4162
				if ( $module ) {
4163
					$module_names[] = $module['name'];
4164
				}
4165
4166
				$this->stat( 'module-deactivated', $module_slug );
4167
			}
4168
4169
			if ( ! $module_names ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $module_names 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...
4170
				break;
4171
			}
4172
4173
			$this->message = wp_sprintf(
4174
				_nx(
4175
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4176
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4177
					count( $module_names ),
4178
					'%l = list of Jetpack module/feature names',
4179
					'jetpack'
4180
				),
4181
				$module_names
4182
			);
4183
			break;
4184
4185
		case 'module_configured' :
4186
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4187
			break;
4188
4189
		case 'already_authorized' :
4190
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4191
			break;
4192
4193
		case 'authorized' :
4194
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4195
			$this->message .= Jetpack::jetpack_comment_notice();
4196
			break;
4197
4198
		case 'linked' :
4199
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4200
			$this->message .= Jetpack::jetpack_comment_notice();
4201
			break;
4202
4203
		case 'unlinked' :
4204
			$user = wp_get_current_user();
4205
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4206
			break;
4207
4208
		case 'switch_master' :
4209
			global $current_user;
4210
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4211
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4212
			if ( $is_master_user ) {
4213
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4214
			} else {
4215
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4216
			}
4217
			break;
4218
		}
4219
4220
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4221
4222
		if ( ! empty( $deactivated_plugins ) ) {
4223
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4224
			$deactivated_titles  = array();
4225
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4226
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4227
					continue;
4228
				}
4229
4230
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4231
			}
4232
4233
			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...
4234
				if ( $this->message ) {
4235
					$this->message .= "<br /><br />\n";
4236
				}
4237
4238
				$this->message .= wp_sprintf(
4239
					_n(
4240
						'Jetpack contains the most recent version of the old %l plugin.',
4241
						'Jetpack contains the most recent versions of the old %l plugins.',
4242
						count( $deactivated_titles ),
4243
						'jetpack'
4244
					),
4245
					$deactivated_titles
4246
				);
4247
4248
				$this->message .= "<br />\n";
4249
4250
				$this->message .= _n(
4251
					'The old version has been deactivated and can be removed from your site.',
4252
					'The old versions have been deactivated and can be removed from your site.',
4253
					count( $deactivated_titles ),
4254
					'jetpack'
4255
				);
4256
			}
4257
		}
4258
4259
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4260
4261
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4262
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4263
		}
4264
4265 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4266
			/**
4267
			 * Fires when a module configuration page is loaded.
4268
			 * The dynamic part of the hook is the configure parameter from the URL.
4269
			 *
4270
			 * @since 1.1.0
4271
			 */
4272
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4273
		}
4274
4275
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4276
	}
4277
4278
	function admin_notices() {
4279
4280
		if ( $this->error ) {
4281
?>
4282
<div id="message" class="jetpack-message jetpack-err">
4283
	<div class="squeezer">
4284
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4285
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4286
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4287
<?php	endif; ?>
4288
	</div>
4289
</div>
4290
<?php
4291
		}
4292
4293
		if ( $this->message ) {
4294
?>
4295
<div id="message" class="jetpack-message">
4296
	<div class="squeezer">
4297
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4298
	</div>
4299
</div>
4300
<?php
4301
		}
4302
4303
		if ( $this->privacy_checks ) :
4304
			$module_names = $module_slugs = array();
4305
4306
			$privacy_checks = explode( ',', $this->privacy_checks );
4307
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4308
			foreach ( $privacy_checks as $module_slug ) {
4309
				$module = Jetpack::get_module( $module_slug );
4310
				if ( ! $module ) {
4311
					continue;
4312
				}
4313
4314
				$module_slugs[] = $module_slug;
4315
				$module_names[] = "<strong>{$module['name']}</strong>";
4316
			}
4317
4318
			$module_slugs = join( ',', $module_slugs );
4319
?>
4320
<div id="message" class="jetpack-message jetpack-err">
4321
	<div class="squeezer">
4322
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4323
		<p><?php
4324
			echo wp_kses(
4325
				wptexturize(
4326
					wp_sprintf(
4327
						_nx(
4328
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4329
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4330
							count( $privacy_checks ),
4331
							'%l = list of Jetpack module/feature names',
4332
							'jetpack'
4333
						),
4334
						$module_names
4335
					)
4336
				),
4337
				array( 'strong' => true )
4338
			);
4339
4340
			echo "\n<br />\n";
4341
4342
			echo wp_kses(
4343
				sprintf(
4344
					_nx(
4345
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4346
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4347
						count( $privacy_checks ),
4348
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4349
						'jetpack'
4350
					),
4351
					wp_nonce_url(
4352
						Jetpack::admin_url(
4353
							array(
4354
								'page'   => 'jetpack',
4355
								'action' => 'deactivate',
4356
								'module' => urlencode( $module_slugs ),
4357
							)
4358
						),
4359
						"jetpack_deactivate-$module_slugs"
4360
					),
4361
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4362
				),
4363
				array( 'a' => array( 'href' => true, 'title' => true ) )
4364
			);
4365
		?></p>
4366
	</div>
4367
</div>
4368
<?php endif;
4369
	// only display the notice if the other stuff is not there
4370
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4371
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4372
			$this->opt_in_jetpack_manage_notice();
4373
		}
4374
	}
4375
4376
	/**
4377
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4378
	 */
4379
	function stat( $group, $detail ) {
4380
		if ( ! isset( $this->stats[ $group ] ) )
4381
			$this->stats[ $group ] = array();
4382
		$this->stats[ $group ][] = $detail;
4383
	}
4384
4385
	/**
4386
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4387
	 */
4388
	function do_stats( $method = '' ) {
4389
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4390
			foreach ( $this->stats as $group => $stats ) {
4391
				if ( is_array( $stats ) && count( $stats ) ) {
4392
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4393
					if ( 'server_side' === $method ) {
4394
						self::do_server_side_stat( $args );
4395
					} else {
4396
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4397
					}
4398
				}
4399
				unset( $this->stats[ $group ] );
4400
			}
4401
		}
4402
	}
4403
4404
	/**
4405
	 * Runs stats code for a one-off, server-side.
4406
	 *
4407
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4408
	 *
4409
	 * @return bool If it worked.
4410
	 */
4411
	static function do_server_side_stat( $args ) {
4412
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4413
		if ( is_wp_error( $response ) )
4414
			return false;
4415
4416
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4417
			return false;
4418
4419
		return true;
4420
	}
4421
4422
	/**
4423
	 * Builds the stats url.
4424
	 *
4425
	 * @param $args array|string The arguments to append to the URL.
4426
	 *
4427
	 * @return string The URL to be pinged.
4428
	 */
4429
	static function build_stats_url( $args ) {
4430
		$defaults = array(
4431
			'v'    => 'wpcom2',
4432
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4433
		);
4434
		$args     = wp_parse_args( $args, $defaults );
4435
		/**
4436
		 * Filter the URL used as the Stats tracking pixel.
4437
		 *
4438
		 * @since 2.3.2
4439
		 *
4440
		 * @param string $url Base URL used as the Stats tracking pixel.
4441
		 */
4442
		$base_url = apply_filters(
4443
			'jetpack_stats_base_url',
4444
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4445
		);
4446
		$url      = add_query_arg( $args, $base_url );
4447
		return $url;
4448
	}
4449
4450
	function translate_current_user_to_role() {
4451
		foreach ( $this->capability_translations as $role => $cap ) {
4452
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4453
				return $role;
4454
			}
4455
		}
4456
4457
		return false;
4458
	}
4459
4460
	function translate_role_to_cap( $role ) {
4461
		if ( ! isset( $this->capability_translations[$role] ) ) {
4462
			return false;
4463
		}
4464
4465
		return $this->capability_translations[$role];
4466
	}
4467
4468
	function sign_role( $role ) {
4469
		if ( ! $user_id = (int) get_current_user_id() ) {
4470
			return false;
4471
		}
4472
4473
		$token = Jetpack_Data::get_access_token();
4474
		if ( ! $token || is_wp_error( $token ) ) {
4475
			return false;
4476
		}
4477
4478
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4479
	}
4480
4481
4482
	/**
4483
	 * Builds a URL to the Jetpack connection auth page
4484
	 *
4485
	 * @since 3.9.5
4486
	 *
4487
	 * @param bool $raw If true, URL will not be escaped.
4488
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4489
	 *                              If string, will be a custom redirect.
4490
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4491
	 *
4492
	 * @return string Connect URL
4493
	 */
4494
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4495
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4496
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4497
			if( is_network_admin() ) {
4498
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4499
			    'admin.php?page=jetpack-settings' ), $url );
4500
			}
4501
		} else {
4502
			$role = $this->translate_current_user_to_role();
4503
			$signed_role = $this->sign_role( $role );
4504
4505
			$user = wp_get_current_user();
4506
4507
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4508
4509
			if( isset( $_REQUEST['is_multisite'] ) ) {
4510
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4511
			}
4512
4513
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4514
			@list( $secret ) = explode( ':', $secrets );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
4515
4516
			$args = urlencode_deep(
4517
				array(
4518
					'response_type' => 'code',
4519
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4520
					'redirect_uri'  => add_query_arg(
4521
						array(
4522
							'action'   => 'authorize',
4523
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4524
							'redirect' => urlencode( $redirect ),
4525
						),
4526
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4527
					),
4528
					'state'         => $user->ID,
4529
					'scope'         => $signed_role,
4530
					'user_email'    => $user->user_email,
4531
					'user_login'    => $user->user_login,
4532
					'is_active'     => Jetpack::is_active(),
4533
					'jp_version'    => JETPACK__VERSION,
4534
					'auth_type'     => 'calypso',
4535
					'secret'		=> $secret,
4536
				)
4537
			);
4538
4539
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4540
		}
4541
4542
		if ( $from ) {
4543
			$url = add_query_arg( 'from', $from, $url );
4544
		}
4545
4546
		if ( isset( $_GET['calypso_env'] ) ) {
4547
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4548
		}
4549
4550
		return $raw ? $url : esc_url( $url );
4551
	}
4552
4553
	function build_reconnect_url( $raw = false ) {
4554
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4555
		return $raw ? $url : esc_url( $url );
4556
	}
4557
4558
	public static function admin_url( $args = null ) {
4559
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4560
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4561
		return $url;
4562
	}
4563
4564
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4565
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4566
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4567
	}
4568
4569
	function dismiss_jetpack_notice() {
4570
4571
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4572
			return;
4573
		}
4574
4575
		switch( $_GET['jetpack-notice'] ) {
4576
			case 'dismiss':
4577
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4578
4579
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4580
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4581
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4582
				}
4583
				break;
4584 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...
4585
4586
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4587
					// Don't show the banner again
4588
4589
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4590
					// redirect back to the page that had the notice
4591
					if ( wp_get_referer() ) {
4592
						wp_safe_redirect( wp_get_referer() );
4593
					} else {
4594
						// Take me to Jetpack
4595
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4596
					}
4597
				}
4598
				break;
4599 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...
4600
4601
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4602
					// Don't show the banner again
4603
4604
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4605
					// redirect back to the page that had the notice
4606
					if ( wp_get_referer() ) {
4607
						wp_safe_redirect( wp_get_referer() );
4608
					} else {
4609
						// Take me to Jetpack
4610
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4611
					}
4612
				}
4613
				break;
4614
			case 'jetpack-manage-opt-in':
4615
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4616
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4617
4618
					$redirection_url = Jetpack::admin_url();
4619
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4620
4621
					// Don't redirect form the Jetpack Setting Page
4622
					$referer_parsed = parse_url ( wp_get_referer() );
4623
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4624
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4625
						// Take the user to Jetpack home except when on the setting page
4626
						$redirection_url = wp_get_referer();
4627
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4628
					}
4629
					// Also update the JSON API FULL MANAGEMENT Option
4630
					Jetpack::activate_module( 'manage', false, false );
4631
4632
					// Special Message when option in.
4633
					Jetpack::state( 'optin-manage', 'true' );
4634
					// Activate the Module if not activated already
4635
4636
					// Redirect properly
4637
					wp_safe_redirect( $redirection_url );
4638
4639
				}
4640
				break;
4641
		}
4642
	}
4643
4644
	function debugger_page() {
4645
		nocache_headers();
4646
		if ( ! current_user_can( 'manage_options' ) ) {
4647
			die( '-1' );
0 ignored issues
show
Coding Style Compatibility introduced by
The method debugger_page() contains an exit expression.

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

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

Loading history...
4648
		}
4649
		Jetpack_Debugger::jetpack_debug_display_handler();
4650
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method debugger_page() contains an exit expression.

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

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

Loading history...
4651
	}
4652
4653
	public static function admin_screen_configure_module( $module_id ) {
4654
4655
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4656
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4657
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4658
				/**
4659
				 * Fires to diplay a custom module activation screen.
4660
				 *
4661
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4662
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4663
				 *
4664
				 * @module manage
4665
				 *
4666
				 * @since 3.8.0
4667
				 *
4668
				 * @param int $module_id Module ID.
4669
				 */
4670
				do_action( 'display_activate_module_setting_' . $module_id );
4671
			} else {
4672
				self::display_activate_module_link( $module_id );
4673
			}
4674
4675
			return false;
4676
		} ?>
4677
4678
		<div id="jp-settings-screen" style="position: relative">
4679
			<h3>
4680
			<?php
4681
				$module = Jetpack::get_module( $module_id );
4682
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4683
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4684
			?>
4685
			</h3>
4686
			<?php
4687
				/**
4688
				 * Fires within the displayed message when a feature configuation is updated.
4689
				 *
4690
				 * @since 3.4.0
4691
				 *
4692
				 * @param int $module_id Module ID.
4693
				 */
4694
				do_action( 'jetpack_notices_update_settings', $module_id );
4695
				/**
4696
				 * Fires when a feature configuation screen is loaded.
4697
				 * The dynamic part of the hook, $module_id, is the module ID.
4698
				 *
4699
				 * @since 1.1.0
4700
				 */
4701
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4702
			?>
4703
		</div><?php
4704
	}
4705
4706
	/**
4707
	 * Display link to activate the module to see the settings screen.
4708
	 * @param  string $module_id
4709
	 * @return null
4710
	 */
4711
	public static function display_activate_module_link( $module_id ) {
4712
4713
		$info =  Jetpack::get_module( $module_id );
4714
		$extra = '';
4715
		$activate_url = wp_nonce_url(
4716
				Jetpack::admin_url(
4717
					array(
4718
						'page'   => 'jetpack',
4719
						'action' => 'activate',
4720
						'module' => $module_id,
4721
					)
4722
				),
4723
				"jetpack_activate-$module_id"
4724
			);
4725
4726
		?>
4727
4728
		<div class="wrap configure-module">
4729
			<div id="jp-settings-screen">
4730
				<?php
4731
				if ( $module_id == 'json-api' ) {
4732
4733
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4734
4735
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4736
4737
					$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' ), 'http://jetpack.com/support/site-management' );
4738
4739
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4740
				} ?>
4741
4742
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4743
				<div class="narrow">
4744
					<p><?php echo  $info['description']; ?></p>
4745
					<?php if( $extra ) { ?>
4746
					<p><?php echo esc_html( $extra ); ?></p>
4747
					<?php } ?>
4748
					<p>
4749
						<?php
4750
						if( wp_get_referer() ) {
4751
							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() );
4752
						} else {
4753
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4754
						} ?>
4755
					</p>
4756
				</div>
4757
4758
			</div>
4759
		</div>
4760
4761
		<?php
4762
	}
4763
4764
	public static function sort_modules( $a, $b ) {
4765
		if ( $a['sort'] == $b['sort'] )
4766
			return 0;
4767
4768
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4769
	}
4770
4771 View Code Duplication
	function sync_reindex_trigger() {
4772
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4773
			echo json_encode( $this->sync->reindex_trigger() );
4774
		} else {
4775
			echo '{"status":"ERROR"}';
4776
		}
4777
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method sync_reindex_trigger() 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...
4778
	}
4779
4780 View Code Duplication
	function sync_reindex_status(){
4781
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4782
			echo json_encode( $this->sync->reindex_status() );
4783
		} else {
4784
			echo '{"status":"ERROR"}';
4785
		}
4786
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method sync_reindex_status() 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...
4787
	}
4788
4789
/* Client API */
4790
4791
	/**
4792
	 * Returns the requested Jetpack API URL
4793
	 *
4794
	 * @return string
4795
	 */
4796
	public static function api_url( $relative_url ) {
4797
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4798
	}
4799
4800
	/**
4801
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4802
	 */
4803
	public static function fix_url_for_bad_hosts( $url ) {
4804
		if ( 0 !== strpos( $url, 'https://' ) ) {
4805
			return $url;
4806
		}
4807
4808
		switch ( JETPACK_CLIENT__HTTPS ) {
4809
			case 'ALWAYS' :
4810
				return $url;
4811
			case 'NEVER' :
4812
				return set_url_scheme( $url, 'http' );
4813
			// default : case 'AUTO' :
4814
		}
4815
4816
		// we now return the unmodified SSL URL by default, as a security precaution
4817
		return $url;
4818
	}
4819
4820
	/**
4821
	 * Checks to see if the URL is using SSL to connect with Jetpack
4822
	 *
4823
	 * @since 2.3.3
4824
	 * @return boolean
4825
	 */
4826
	public static function permit_ssl( $force_recheck = false ) {
4827
		// Do some fancy tests to see if ssl is being supported
4828
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4829
			$message = '';
4830
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4831
				$ssl = 0;
4832
			} else {
4833
				switch ( JETPACK_CLIENT__HTTPS ) {
4834
					case 'NEVER':
4835
						$ssl = 0;
4836
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4837
						break;
4838
					case 'ALWAYS':
4839
					case 'AUTO':
4840
					default:
4841
						$ssl = 1;
4842
						break;
4843
				}
4844
4845
				// If it's not 'NEVER', test to see
4846
				if ( $ssl ) {
4847
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4848
						$ssl = 0;
4849
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4850
					} else {
4851
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4852
						if ( is_wp_error( $response ) ) {
4853
							$ssl = 0;
4854
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4855
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4856
							$ssl = 0;
4857
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4858
						}
4859
					}
4860
				}
4861
			}
4862
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4863
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4864
		}
4865
4866
		return (bool) $ssl;
4867
	}
4868
4869
	/*
4870
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4871
	 */
4872
	public function alert_auto_ssl_fail() {
4873
		if ( ! current_user_can( 'manage_options' ) )
4874
			return;
4875
		?>
4876
4877
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4878
			<div class="jp-banner__content">
4879
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4880
				<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>
4881
				<p>
4882
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4883
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4884
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4885
				</p>
4886
				<p>
4887
					<?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' ), 
4888
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4889
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4890
				</p>
4891
			</div>
4892
		</div>
4893
		<style>
4894
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4895
		</style>
4896
		<script type="text/javascript">
4897
			jQuery( document ).ready( function( $ ) {
4898
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4899
					var $this = $( this );
4900
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4901
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4902
					e.preventDefault();
4903
					$.post( '/wp-json/jetpack/v4/recheck-ssl' )
4904
					  .done( function( response ) {
4905
					  	if ( response.enabled ) {
4906
					  		$( '#jetpack-ssl-warning' ).hide();
4907
					  	} else {
4908
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4909
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4910
					  	}
4911
					  }.bind( $this ) );
4912
				} );
4913
			} );
4914
		</script>
4915
4916
		<?php
4917
	}
4918
4919
	/**
4920
	 * Returns the Jetpack XML-RPC API
4921
	 *
4922
	 * @return string
4923
	 */
4924
	public static function xmlrpc_api_url() {
4925
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4926
		return untrailingslashit( $base ) . '/xmlrpc.php';
4927
	}
4928
4929
	/**
4930
	 * Creates two secret tokens and the end of life timestamp for them.
4931
	 *
4932
	 * Note these tokens are unique per call, NOT static per site for connecting.
4933
	 *
4934
	 * @since 2.6
4935
	 * @return array
4936
	 */
4937
	public function generate_secrets( $action ) {
4938
	    $secret = wp_generate_password( 32, false ) // secret_1
4939
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4940
	    		. ':' . ( time() + 600 ) // eol ( End of Life )
4941
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4942
		Jetpack_Options::update_option( $action, $secret );
4943
4944
	    return Jetpack_Options::get_option( $action );
4945
	}
4946
4947
	/**
4948
	 * Builds the timeout limit for queries talking with the wpcom servers.
4949
	 *
4950
	 * Based on local php max_execution_time in php.ini
4951
	 *
4952
	 * @since 2.6
4953
	 * @return int
4954
	 **/
4955
	public function get_remote_query_timeout_limit() {
4956
	    $timeout = (int) ini_get( 'max_execution_time' );
4957
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4958
		$timeout = 30;
4959
	    return intval( $timeout / 2 );
4960
	}
4961
4962
4963
	/**
4964
	 * Takes the response from the Jetpack register new site endpoint and
4965
	 * verifies it worked properly.
4966
	 *
4967
	 * @since 2.6
4968
	 * @return true or Jetpack_Error
4969
	 **/
4970
	public function validate_remote_register_response( $response ) {
4971
	    	if ( is_wp_error( $response ) ) {
4972
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4973
		}
4974
4975
		$code   = wp_remote_retrieve_response_code( $response );
4976
		$entity = wp_remote_retrieve_body( $response );
4977
		if ( $entity )
4978
			$json = json_decode( $entity );
4979
		else
4980
			$json = false;
4981
4982
		$code_type = intval( $code / 100 );
4983
		if ( 5 == $code_type ) {
4984
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4985
		} elseif ( 408 == $code ) {
4986
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4987
		} elseif ( ! empty( $json->error ) ) {
4988
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4989
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4990
		} elseif ( 200 != $code ) {
4991
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4992
		}
4993
4994
		// Jetpack ID error block
4995
		if ( empty( $json->jetpack_id ) ) {
4996
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4997
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4998
			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 );
4999
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
5000
			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 );
5001
		}
5002
5003
	    return true;
5004
	}
5005
	/**
5006
	 * @return bool|WP_Error
5007
	 */
5008
	public static function register() {
5009
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5010
		$secrets = Jetpack::init()->generate_secrets( 'register' );
5011
5012
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5013 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
5014
			return new Jetpack_Error( 'missing_secrets' );
5015
		}
5016
5017
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
5018
5019
		$gmt_offset = get_option( 'gmt_offset' );
5020
		if ( ! $gmt_offset ) {
5021
			$gmt_offset = 0;
5022
		}
5023
5024
		$stats_options = get_option( 'stats_options' );
5025
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5026
5027
		$args = array(
5028
			'method'  => 'POST',
5029
			'body'    => array(
5030
				'siteurl'         => site_url(),
5031
				'home'            => home_url(),
5032
				'gmt_offset'      => $gmt_offset,
5033
				'timezone_string' => (string) get_option( 'timezone_string' ),
5034
				'site_name'       => (string) get_option( 'blogname' ),
5035
				'secret_1'        => $secret_1,
5036
				'secret_2'        => $secret_2,
5037
				'site_lang'       => get_locale(),
5038
				'timeout'         => $timeout,
5039
				'stats_id'        => $stats_id,
5040
				'state'           => get_current_user_id(),
5041
			),
5042
			'headers' => array(
5043
				'Accept' => 'application/json',
5044
			),
5045
			'timeout' => $timeout,
5046
		);
5047
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5048
5049
5050
		// Make sure the response is valid and does not contain any Jetpack errors
5051
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
5052
		if( is_wp_error( $valid_response ) || !$valid_response ) {
5053
		    return $valid_response;
5054
		}
5055
5056
		// Grab the response values to work with
5057
		$code   = wp_remote_retrieve_response_code( $response );
5058
		$entity = wp_remote_retrieve_body( $response );
5059
5060
		if ( $entity )
5061
			$json = json_decode( $entity );
5062
		else
5063
			$json = false;
5064
5065 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
5066
			return new Jetpack_Error( 'jetpack_secret', '', $code );
5067
5068
		if ( isset( $json->jetpack_public ) ) {
5069
			$jetpack_public = (int) $json->jetpack_public;
5070
		} else {
5071
			$jetpack_public = false;
5072
		}
5073
5074
		Jetpack_Options::update_options(
5075
			array(
5076
				'id'         => (int)    $json->jetpack_id,
5077
				'blog_token' => (string) $json->jetpack_secret,
5078
				'public'     => $jetpack_public,
5079
			)
5080
		);
5081
5082
		/**
5083
		 * Fires when a site is registered on WordPress.com.
5084
		 *
5085
		 * @since 3.7.0
5086
		 *
5087
		 * @param int $json->jetpack_id Jetpack Blog ID.
5088
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5089
		 * @param int|bool $jetpack_public Is the site public.
5090
		 */
5091
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
5092
5093
		// Initialize Jump Start for the first and only time.
5094
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5095
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5096
5097
			$jetpack = Jetpack::init();
5098
5099
			$jetpack->stat( 'jumpstart', 'unique-views' );
5100
			$jetpack->do_stats( 'server_side' );
5101
		};
5102
5103
		return true;
5104
	}
5105
5106
	/**
5107
	 * If the db version is showing something other that what we've got now, bump it to current.
5108
	 *
5109
	 * @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...
5110
	 */
5111
	public static function maybe_set_version_option() {
5112
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5113
		if ( JETPACK__VERSION != $version ) {
5114
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5115
			return true;
5116
		}
5117
		return false;
5118
	}
5119
5120
/* Client Server API */
5121
5122
	/**
5123
	 * Loads the Jetpack XML-RPC client
5124
	 */
5125
	public static function load_xml_rpc_client() {
5126
		require_once ABSPATH . WPINC . '/class-IXR.php';
5127
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5128
	}
5129
5130
	function verify_xml_rpc_signature() {
5131
		if ( $this->xmlrpc_verification ) {
5132
			return $this->xmlrpc_verification;
5133
		}
5134
5135
		// It's not for us
5136
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5137
			return false;
5138
		}
5139
5140
		@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...
5141
		if (
5142
			empty( $token_key )
5143
		||
5144
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5145
		) {
5146
			return false;
5147
		}
5148
5149
		if ( '0' === $user_id ) {
5150
			$token_type = 'blog';
5151
			$user_id = 0;
5152
		} else {
5153
			$token_type = 'user';
5154
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5155
				return false;
5156
			}
5157
			$user_id = (int) $user_id;
5158
5159
			$user = new WP_User( $user_id );
5160
			if ( ! $user || ! $user->exists() ) {
5161
				return false;
5162
			}
5163
		}
5164
5165
		$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...
5166
		if ( ! $token ) {
5167
			return false;
5168
		}
5169
5170
		$token_check = "$token_key.";
5171
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5172
			return false;
5173
		}
5174
5175
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5176
5177
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5178
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5179
			$post_data   = $_POST;
5180
			$file_hashes = array();
5181
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5182
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5183
					continue;
5184
				}
5185
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5186
				$file_hashes[$post_data_key] = $post_data_value;
5187
			}
5188
5189
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5190
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5191
				$post_data[$post_data_key] = $post_data_value;
5192
			}
5193
5194
			ksort( $post_data );
5195
5196
			$body = http_build_query( stripslashes_deep( $post_data ) );
5197
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5198
			$body = file_get_contents( 'php://input' );
5199
		} else {
5200
			$body = null;
5201
		}
5202
		$signature = $jetpack_signature->sign_current_request(
5203
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5204
		);
5205
5206
		if ( ! $signature ) {
5207
			return false;
5208
		} else if ( is_wp_error( $signature ) ) {
5209
			return $signature;
5210
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5211
			return false;
5212
		}
5213
5214
		$timestamp = (int) $_GET['timestamp'];
5215
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5216
5217
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5218
			return false;
5219
		}
5220
5221
		$this->xmlrpc_verification = array(
5222
			'type'    => $token_type,
5223
			'user_id' => $token->external_user_id,
5224
		);
5225
5226
		return $this->xmlrpc_verification;
5227
	}
5228
5229
	/**
5230
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5231
	 */
5232
	function authenticate_jetpack( $user, $username, $password ) {
0 ignored issues
show
Unused Code introduced by
The parameter $username is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $password is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5233
		if ( is_a( $user, 'WP_User' ) ) {
5234
			return $user;
5235
		}
5236
5237
		$token_details = $this->verify_xml_rpc_signature();
5238
5239
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5240
			return $user;
5241
		}
5242
5243
		if ( 'user' !== $token_details['type'] ) {
5244
			return $user;
5245
		}
5246
5247
		if ( ! $token_details['user_id'] ) {
5248
			return $user;
5249
		}
5250
5251
		nocache_headers();
5252
5253
		return new WP_User( $token_details['user_id'] );
5254
	}
5255
5256
	function add_nonce( $timestamp, $nonce ) {
5257
		global $wpdb;
5258
		static $nonces_used_this_request = array();
5259
5260
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5261
			return $nonces_used_this_request["$timestamp:$nonce"];
5262
		}
5263
5264
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5265
		$timestamp = (int) $timestamp;
5266
		$nonce     = esc_sql( $nonce );
5267
5268
		// Raw query so we can avoid races: add_option will also update
5269
		$show_errors = $wpdb->show_errors( false );
5270
5271
		$old_nonce = $wpdb->get_row(
5272
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5273
		);
5274
5275
		if ( is_null( $old_nonce ) ) {
5276
			$return = $wpdb->query(
5277
				$wpdb->prepare(
5278
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5279
					"jetpack_nonce_{$timestamp}_{$nonce}",
5280
					time(),
5281
					'no'
5282
				)
5283
			);
5284
		} else {
5285
			$return = false;
5286
		}
5287
5288
		$wpdb->show_errors( $show_errors );
5289
5290
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5291
5292
		return $return;
5293
	}
5294
5295
	/**
5296
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5297
	 * Capture it here so we can verify the signature later.
5298
	 */
5299
	function xmlrpc_methods( $methods ) {
5300
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5301
		return $methods;
5302
	}
5303
5304
	function public_xmlrpc_methods( $methods ) {
5305
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5306
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5307
		}
5308
		return $methods;
5309
	}
5310
5311
	function jetpack_getOptions( $args ) {
5312
		global $wp_xmlrpc_server;
5313
5314
		$wp_xmlrpc_server->escape( $args );
5315
5316
		$username	= $args[1];
5317
		$password	= $args[2];
5318
5319
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5320
			return $wp_xmlrpc_server->error;
5321
		}
5322
5323
		$options = array();
5324
		$user_data = $this->get_connected_user_data();
5325
		if ( is_array( $user_data ) ) {
5326
			$options['jetpack_user_id'] = array(
5327
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5328
				'readonly'      => true,
5329
				'value'         => $user_data['ID'],
5330
			);
5331
			$options['jetpack_user_login'] = array(
5332
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5333
				'readonly'      => true,
5334
				'value'         => $user_data['login'],
5335
			);
5336
			$options['jetpack_user_email'] = array(
5337
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5338
				'readonly'      => true,
5339
				'value'         => $user_data['email'],
5340
			);
5341
			$options['jetpack_user_site_count'] = array(
5342
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5343
				'readonly'      => true,
5344
				'value'         => $user_data['site_count'],
5345
			);
5346
		}
5347
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5348
		$args = stripslashes_deep( $args );
5349
		return $wp_xmlrpc_server->wp_getOptions( $args );
5350
	}
5351
5352
	function xmlrpc_options( $options ) {
5353
		$jetpack_client_id = false;
5354
		if ( self::is_active() ) {
5355
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5356
		}
5357
		$options['jetpack_version'] = array(
5358
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5359
				'readonly'      => true,
5360
				'value'         => JETPACK__VERSION,
5361
		);
5362
5363
		$options['jetpack_client_id'] = array(
5364
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5365
				'readonly'      => true,
5366
				'value'         => $jetpack_client_id,
5367
		);
5368
		return $options;
5369
	}
5370
5371
	public static function clean_nonces( $all = false ) {
5372
		global $wpdb;
5373
5374
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5375
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
5376
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5377
		} else {
5378
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
5379
		}
5380
5381
		if ( true !== $all ) {
5382
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5383
			$sql_args[] = time() - 3600;
5384
		}
5385
5386
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5387
5388
		$sql = $wpdb->prepare( $sql, $sql_args );
5389
5390
		for ( $i = 0; $i < 1000; $i++ ) {
5391
			if ( ! $wpdb->query( $sql ) ) {
5392
				break;
5393
			}
5394
		}
5395
	}
5396
5397
	/**
5398
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5399
	 * SET: state( $key, $value );
5400
	 * GET: $value = state( $key );
5401
	 *
5402
	 * @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...
5403
	 * @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...
5404
	 * @param bool $restate private
5405
	 */
5406
	public static function state( $key = null, $value = null, $restate = false ) {
5407
		static $state = array();
5408
		static $path, $domain;
5409
		if ( ! isset( $path ) ) {
5410
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5411
			$admin_url = Jetpack::admin_url();
5412
			$bits      = parse_url( $admin_url );
5413
5414
			if ( is_array( $bits ) ) {
5415
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5416
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5417
			} else {
5418
				$path = $domain = null;
5419
			}
5420
		}
5421
5422
		// Extract state from cookies and delete cookies
5423
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5424
			$yum = $_COOKIE[ 'jetpackState' ];
5425
			unset( $_COOKIE[ 'jetpackState' ] );
5426
			foreach ( $yum as $k => $v ) {
5427
				if ( strlen( $v ) )
5428
					$state[ $k ] = $v;
5429
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5430
			}
5431
		}
5432
5433
		if ( $restate ) {
5434
			foreach ( $state as $k => $v ) {
5435
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5436
			}
5437
			return;
5438
		}
5439
5440
		// Get a state variable
5441
		if ( isset( $key ) && ! isset( $value ) ) {
5442
			if ( array_key_exists( $key, $state ) )
5443
				return $state[ $key ];
5444
			return null;
5445
		}
5446
5447
		// Set a state variable
5448
		if ( isset ( $key ) && isset( $value ) ) {
5449
			if( is_array( $value ) && isset( $value[0] ) ) {
5450
				$value = $value[0];
5451
			}
5452
			$state[ $key ] = $value;
5453
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5454
		}
5455
	}
5456
5457
	public static function restate() {
5458
		Jetpack::state( null, null, true );
5459
	}
5460
5461
	public static function check_privacy( $file ) {
5462
		static $is_site_publicly_accessible = null;
5463
5464
		if ( is_null( $is_site_publicly_accessible ) ) {
5465
			$is_site_publicly_accessible = false;
5466
5467
			Jetpack::load_xml_rpc_client();
5468
			$rpc = new Jetpack_IXR_Client();
5469
5470
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5471
			if ( $success ) {
5472
				$response = $rpc->getResponse();
5473
				if ( $response ) {
5474
					$is_site_publicly_accessible = true;
5475
				}
5476
			}
5477
5478
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5479
		}
5480
5481
		if ( $is_site_publicly_accessible ) {
5482
			return;
5483
		}
5484
5485
		$module_slug = self::get_module_slug( $file );
5486
5487
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5488
		if ( ! $privacy_checks ) {
5489
			$privacy_checks = $module_slug;
5490
		} else {
5491
			$privacy_checks .= ",$module_slug";
5492
		}
5493
5494
		Jetpack::state( 'privacy_checks', $privacy_checks );
5495
	}
5496
5497
	/**
5498
	 * Helper method for multicall XMLRPC.
5499
	 */
5500
	public static function xmlrpc_async_call() {
5501
		global $blog_id;
5502
		static $clients = array();
5503
5504
		$client_blog_id = is_multisite() ? $blog_id : 0;
5505
5506
		if ( ! isset( $clients[$client_blog_id] ) ) {
5507
			Jetpack::load_xml_rpc_client();
5508
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5509
			if ( function_exists( 'ignore_user_abort' ) ) {
5510
				ignore_user_abort( true );
5511
			}
5512
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5513
		}
5514
5515
		$args = func_get_args();
5516
5517
		if ( ! empty( $args[0] ) ) {
5518
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5519
		} elseif ( is_multisite() ) {
5520
			foreach ( $clients as $client_blog_id => $client ) {
5521
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5522
					continue;
5523
				}
5524
5525
				$switch_success = switch_to_blog( $client_blog_id, true );
5526
				if ( ! $switch_success ) {
5527
					continue;
5528
				}
5529
5530
				flush();
5531
				$client->query();
5532
5533
				restore_current_blog();
5534
			}
5535
		} else {
5536
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5537
				flush();
5538
				$clients[0]->query();
5539
			}
5540
		}
5541
	}
5542
5543
	public static function staticize_subdomain( $url ) {
5544
5545
		// Extract hostname from URL
5546
		$host = parse_url( $url, PHP_URL_HOST );
5547
5548
		// Explode hostname on '.'
5549
		$exploded_host = explode( '.', $host );
5550
5551
		// Retrieve the name and TLD
5552
		if ( count( $exploded_host ) > 1 ) {
5553
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5554
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5555
			// Rebuild domain excluding subdomains
5556
			$domain = $name . '.' . $tld;
5557
		} else {
5558
			$domain = $host;
5559
		}
5560
		// Array of Automattic domains
5561
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5562
5563
		// Return $url if not an Automattic domain
5564
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5565
			return $url;
5566
		}
5567
5568
		if ( is_ssl() ) {
5569
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5570
		}
5571
5572
		srand( crc32( basename( $url ) ) );
5573
		$static_counter = rand( 0, 2 );
5574
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5575
5576
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5577
	}
5578
5579
/* JSON API Authorization */
5580
5581
	/**
5582
	 * Handles the login action for Authorizing the JSON API
5583
	 */
5584
	function login_form_json_api_authorization() {
5585
		$this->verify_json_api_authorization_request();
5586
5587
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5588
5589
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5590
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5591
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5592
	}
5593
5594
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5595
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5596
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5597
			return $url;
5598
		}
5599
5600
		$parsed_url = parse_url( $url );
5601
		$url = strtok( $url, '?' );
5602
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5603
		if ( ! empty( $parsed_url['query'] ) )
5604
			$url .= "&{$parsed_url['query']}";
5605
5606
		return $url;
5607
	}
5608
5609
	// Make sure the POSTed request is handled by the same action
5610
	function preserve_action_in_login_form_for_json_api_authorization() {
5611
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5612
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5613
	}
5614
5615
	// If someone logs in to approve API access, store the Access Code in usermeta
5616
	function store_json_api_authorization_token( $user_login, $user ) {
5617
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5618
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5619
		$token = wp_generate_password( 32, false );
5620
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5621
	}
5622
5623
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5624
	function allow_wpcom_public_api_domain( $domains ) {
5625
		$domains[] = 'public-api.wordpress.com';
5626
		return $domains;
5627
	}
5628
5629
	// Add the Access Code details to the public-api.wordpress.com redirect
5630
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5631
		return add_query_arg(
5632
			urlencode_deep(
5633
				array(
5634
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5635
					'jetpack-user-id' => (int) $user->ID,
5636
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5637
				)
5638
			),
5639
			$redirect_to
5640
		);
5641
	}
5642
5643
	// Verifies the request by checking the signature
5644
	function verify_json_api_authorization_request() {
5645
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5646
5647
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5648
		if ( ! $token || empty( $token->secret ) ) {
5649
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5650
		}
5651
5652
		$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' );
5653
5654
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5655
5656
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5657
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5658
		} else {
5659
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5660
		}
5661
5662
		if ( ! $signature ) {
5663
			wp_die( $die_error );
5664
		} else if ( is_wp_error( $signature ) ) {
5665
			wp_die( $die_error );
5666
		} else if ( $signature !== $_GET['signature'] ) {
5667
			if ( is_ssl() ) {
5668
				// 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
5669
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5670
				if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5671
					wp_die( $die_error );
5672
				}
5673
			} else {
5674
				wp_die( $die_error );
5675
			}
5676
		}
5677
5678
		$timestamp = (int) $_GET['timestamp'];
5679
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5680
5681
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5682
			// De-nonce the nonce, at least for 5 minutes.
5683
			// 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)
5684
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5685
			if ( $old_nonce_time < time() - 300 ) {
5686
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5687
			}
5688
		}
5689
5690
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5691
		$data_filters = array(
5692
			'state'        => 'opaque',
5693
			'client_id'    => 'int',
5694
			'client_title' => 'string',
5695
			'client_image' => 'url',
5696
		);
5697
5698
		foreach ( $data_filters as $key => $sanitation ) {
5699
			if ( ! isset( $data->$key ) ) {
5700
				wp_die( $die_error );
5701
			}
5702
5703
			switch ( $sanitation ) {
5704
			case 'int' :
5705
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5706
				break;
5707
			case 'opaque' :
5708
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5709
				break;
5710
			case 'string' :
5711
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5712
				break;
5713
			case 'url' :
5714
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5715
				break;
5716
			}
5717
		}
5718
5719
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5720
			wp_die( $die_error );
5721
		}
5722
	}
5723
5724
	function login_message_json_api_authorization( $message ) {
0 ignored issues
show
Unused Code introduced by
The parameter $message is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
5725
		return '<p class="message">' . sprintf(
5726
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5727
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5728
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5729
	}
5730
5731
	/**
5732
	 * Get $content_width, but with a <s>twist</s> filter.
5733
	 */
5734
	public static function get_content_width() {
5735
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5736
		/**
5737
		 * Filter the Content Width value.
5738
		 *
5739
		 * @since 2.2.3
5740
		 *
5741
		 * @param string $content_width Content Width value.
5742
		 */
5743
		return apply_filters( 'jetpack_content_width', $content_width );
5744
	}
5745
5746
	/**
5747
	 * Centralize the function here until it gets added to core.
5748
	 *
5749
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5750
	 * @param int $size Size of the avatar image
5751
	 * @param string $default URL to a default image to use if no avatar is available
5752
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5753
	 *
5754
	 * @return array First element is the URL, second is the class.
5755
	 */
5756
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5757
		// Don't bother adding the __return_true filter if it's already there.
5758
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5759
5760
		if ( $force_display && ! $has_filter )
5761
			add_filter( 'pre_option_show_avatars', '__return_true' );
5762
5763
		$avatar = get_avatar( $id_or_email, $size, $default );
5764
5765
		if ( $force_display && ! $has_filter )
5766
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5767
5768
		// If no data, fail out.
5769
		if ( is_wp_error( $avatar ) || ! $avatar )
5770
			return array( null, null );
5771
5772
		// Pull out the URL.  If it's not there, fail out.
5773
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5774
			return array( null, null );
5775
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5776
5777
		// Pull out the class, but it's not a big deal if it's missing.
5778
		$class = '';
5779
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5780
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5781
5782
		return array( $url, $class );
5783
	}
5784
5785
	/**
5786
	 * Pings the WordPress.com Mirror Site for the specified options.
5787
	 *
5788
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5789
	 *
5790
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5791
	 */
5792
	public function get_cloud_site_options( $option_names ) {
5793
		$option_names = array_filter( (array) $option_names, 'is_string' );
5794
5795
		Jetpack::load_xml_rpc_client();
5796
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5797
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5798
		if ( $xml->isError() ) {
5799
			return array(
5800
				'error_code' => $xml->getErrorCode(),
5801
				'error_msg'  => $xml->getErrorMessage(),
5802
			);
5803
		}
5804
		$cloud_site_options = $xml->getResponse();
5805
5806
		return $cloud_site_options;
5807
	}
5808
5809
	/**
5810
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5811
	 *
5812
	 * @return array An array of options to check.
5813
	 */
5814
	public static function identity_crisis_options_to_check() {
5815
		return array(
5816
			'siteurl',
5817
			'home',
5818
		);
5819
	}
5820
5821
	/**
5822
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5823
	 *
5824
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5825
	 *
5826
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5827
	 */
5828
	public static function check_identity_crisis( $force_recheck = false ) {
5829
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5830
			return false;
5831
5832
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5833
			$options_to_check = self::identity_crisis_options_to_check();
5834
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5835
			$errors        = array();
5836
5837
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5838
5839
				// If it's not the same as the local value...
5840
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5841
5842
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5843
					if ( 'error_code' == $cloud_key ) {
5844
						$errors[ $cloud_key ] = $cloud_value;
5845
						break;
5846
					}
5847
5848
					$parsed_cloud_value = parse_url( $cloud_value );
5849
					// If the current options is an IP address
5850
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5851
						// Give the new value a Jetpack to fly in to the clouds
5852
						Jetpack::resolve_identity_crisis( $cloud_key );
5853
						continue;
5854
					}
5855
5856
					// And it's not been added to the whitelist...
5857
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5858
						/*
5859
						 * This should be a temporary hack until a cleaner solution is found.
5860
						 *
5861
						 * The siteurl and home can be set to use http in General > Settings
5862
						 * however some constants can be defined that can force https in wp-admin
5863
						 * when this happens wpcom can confuse wporg with a fake identity
5864
						 * crisis with a mismatch of http vs https when it should be allowed.
5865
						 * we need to check that here.
5866
						 *
5867
						 * @see https://github.com/Automattic/jetpack/issues/1006
5868
						 */
5869
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5870
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5871
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5872
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5873
							continue;
5874
						}
5875
5876
5877
						// Then kick an error!
5878
						$errors[ $cloud_key ] = $cloud_value;
5879
					}
5880
				}
5881
			}
5882
		}
5883
5884
		/**
5885
		 * Filters the errors returned when checking for an Identity Crisis.
5886
		 *
5887
		 * @since 2.3.2
5888
		 *
5889
		 * @param array $errors Array of Identity Crisis errors.
5890
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5891
		 */
5892
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5893
	}
5894
5895
	/*
5896
	 * Resolve ID crisis
5897
	 *
5898
	 * If the URL has changed, but the rest of the options are the same (i.e. blog/user tokens)
5899
	 * The user has the option to update the shadow site with the new URL before a new
5900
	 * token is created.
5901
	 *
5902
	 * @param $key : Which option to sync.  null defautlts to home and siteurl
5903
	 */
5904
	public static function resolve_identity_crisis( $key = null ) {
5905
		if ( $key ) {
5906
			$identity_options = array( $key );
5907
		} else {
5908
			$identity_options = self::identity_crisis_options_to_check();
5909
		}
5910
5911
		if ( is_array( $identity_options ) ) {
5912
			foreach( $identity_options as $identity_option ) {
5913
				Jetpack_Sync::sync_options( __FILE__, $identity_option );
5914
5915
				/**
5916
				 * Fires when a shadow site option is updated.
5917
				 * These options are updated via the Identity Crisis UI.
5918
				 * $identity_option is the option that gets updated.
5919
				 *
5920
				 * @since 3.7.0
5921
				 */
5922
				do_action( "update_option_{$identity_option}" );
5923
			}
5924
		}
5925
	}
5926
5927
	/*
5928
	 * Whitelist URL
5929
	 *
5930
	 * Ignore the URL differences between the blog and the shadow site.
5931
	 */
5932
	public static function whitelist_current_url() {
5933
		$options_to_check = Jetpack::identity_crisis_options_to_check();
5934
		$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5935
5936
		foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5937
			Jetpack::whitelist_identity_crisis_value( $cloud_key, $cloud_value );
5938
		}
5939
	}
5940
5941
	/*
5942
	 * Ajax callbacks for ID crisis resolutions
5943
	 *
5944
	 * Things that could happen here:
5945
	 *  - site_migrated : Update the URL on the shadow blog to match new domain
5946
	 *  - whitelist     : Ignore the URL difference
5947
	 *  - default       : Error message
5948
	 */
5949
	public static function resolve_identity_crisis_ajax_callback() {
5950
		check_ajax_referer( 'resolve-identity-crisis', 'ajax-nonce' );
5951
5952
		switch ( $_POST[ 'crisis_resolution_action' ] ) {
5953
			case 'site_migrated':
5954
				Jetpack::resolve_identity_crisis();
5955
				echo 'resolved';
5956
				break;
5957
5958
			case 'whitelist':
5959
				Jetpack::whitelist_current_url();
5960
				echo 'whitelisted';
5961
				break;
5962
5963
			case 'reset_connection':
5964
				// Delete the options first so it doesn't get confused which site to disconnect dotcom-side
5965
				Jetpack_Options::delete_option(
5966
					array(
5967
						'register',
5968
						'blog_token',
5969
						'user_token',
5970
						'user_tokens',
5971
						'master_user',
5972
						'time_diff',
5973
						'fallback_no_verify_ssl_certs',
5974
						'id',
5975
					)
5976
				);
5977
				delete_transient( 'jetpack_has_identity_crisis' );
5978
5979
				echo 'reset-connection-success';
5980
				break;
5981
5982
			default:
5983
				echo 'missing action';
5984
				break;
5985
		}
5986
5987
		wp_die();
5988
	}
5989
5990
	/**
5991
	 * Adds a value to the whitelist for the specified key.
5992
	 *
5993
	 * @param string $key The option name that we're whitelisting the value for.
5994
	 * @param string $value The value that we're intending to add to the whitelist.
5995
	 *
5996
	 * @return bool Whether the value was added to the whitelist, or false if it was already there.
5997
	 */
5998
	public static function whitelist_identity_crisis_value( $key, $value ) {
5999
		if ( Jetpack::is_identity_crisis_value_whitelisted( $key, $value ) ) {
6000
			return false;
6001
		}
6002
6003
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6004
		if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
6005
			$whitelist[ $key ] = array();
6006
		}
6007
		array_push( $whitelist[ $key ], $value );
6008
6009
		Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
6010
		return true;
6011
	}
6012
6013
	/**
6014
	 * Checks whether a value is already whitelisted.
6015
	 *
6016
	 * @param string $key The option name that we're checking the value for.
6017
	 * @param string $value The value that we're curious to see if it's on the whitelist.
6018
	 *
6019
	 * @return bool Whether the value is whitelisted.
6020
	 */
6021
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
6022
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6023
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
6024
			return true;
6025
		}
6026
		return false;
6027
	}
6028
6029
	/**
6030
	 * Checks whether the home and siteurl specifically are whitelisted
6031
	 * Written so that we don't have re-check $key and $value params every time
6032
	 * we want to check if this site is whitelisted, for example in footer.php
6033
	 *
6034
	 * @return bool True = already whitelsisted False = not whitelisted
6035
	 */
6036
	public static function is_staging_site() {
6037
		$is_staging = false;
6038
6039
		$current_whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist' );
6040
		if ( $current_whitelist ) {
6041
			$options_to_check  = Jetpack::identity_crisis_options_to_check();
6042
			$cloud_options     = Jetpack::init()->get_cloud_site_options( $options_to_check );
6043
6044
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6045
				if ( self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
6046
					$is_staging = true;
6047
					break;
6048
				}
6049
			}
6050
		}
6051
		$known_staging = array(
6052
			'urls' => array(
6053
				'#\.staging\.wpengine\.com$#i',
6054
				),
6055
			'constants' => array(
6056
				'IS_WPE_SNAPSHOT',
6057
				'KINSTA_DEV_ENV',
6058
				'JETPACK_STAGING_MODE',
6059
				)
6060
			);
6061
		/**
6062
		 * Filters the flags of known staging sites.
6063
		 *
6064
		 * @since 3.9.0
6065
		 *
6066
		 * @param array $known_staging {
6067
		 *     An array of arrays that each are used to check if the current site is staging.
6068
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6069
		 *     @type array $cosntants PHP constants of known staging/developement environments.
6070
		 *  }
6071
		 */
6072
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6073
6074
		if ( isset( $known_staging['urls'] ) ) {
6075
			foreach ( $known_staging['urls'] as $url ){
6076
				if ( preg_match( $url, site_url() ) ) {
6077
					$is_staging = true;
6078
					break;
6079
				}
6080
			}
6081
		}
6082
6083
		if ( isset( $known_staging['constants'] ) ) {
6084
			foreach ( $known_staging['constants'] as $constant ) {
6085
				if ( defined( $constant ) && constant( $constant ) ) {
6086
					$is_staging = true;
6087
				}
6088
			}
6089
		}
6090
6091
		/**
6092
		 * Filters is_staging_site check.
6093
		 *
6094
		 * @since 3.9.0
6095
		 *
6096
		 * @param bool $is_staging If the current site is a staging site.
6097
		 */
6098
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6099
	}
6100
6101
	public function identity_crisis_js( $nonce ) {
6102
?>
6103
<script>
6104
(function( $ ) {
6105
	var SECOND_IN_MS = 1000;
6106
6107
	function contactSupport( e ) {
6108
		e.preventDefault();
6109
		$( '.jp-id-crisis-question' ).hide();
6110
		$( '#jp-id-crisis-contact-support' ).show();
6111
	}
6112
6113
	function autodismissSuccessBanner() {
6114
		$( '.jp-identity-crisis' ).fadeOut(600); //.addClass( 'dismiss' );
6115
	}
6116
6117
	var data = { action: 'jetpack_resolve_identity_crisis', 'ajax-nonce': '<?php echo $nonce; ?>' };
6118
6119
	$( document ).ready(function() {
6120
6121
		// Site moved: Update the URL on the shadow blog
6122
		$( '.site-moved' ).click(function( e ) {
6123
			e.preventDefault();
6124
			data.crisis_resolution_action = 'site_migrated';
6125
			$( '#jp-id-crisis-question-1 .spinner' ).show();
6126
			$.post( ajaxurl, data, function() {
6127
				$( '.jp-id-crisis-question' ).hide();
6128
				$( '.banner-title' ).hide();
6129
				$( '#jp-id-crisis-success' ).show();
6130
				setTimeout( autodismissSuccessBanner, 6 * SECOND_IN_MS );
6131
			});
6132
6133
		});
6134
6135
		// URL hasn't changed, next question please.
6136
		$( '.site-not-moved' ).click(function( e ) {
6137
			e.preventDefault();
6138
			$( '.jp-id-crisis-question' ).hide();
6139
			$( '#jp-id-crisis-question-2' ).show();
6140
		});
6141
6142
		// Reset connection: two separate sites.
6143
		$( '.reset-connection' ).click(function( e ) {
6144
			data.crisis_resolution_action = 'reset_connection';
6145
			$.post( ajaxurl, data, function( response ) {
6146
				if ( 'reset-connection-success' === response ) {
6147
					window.location.replace( '<?php echo Jetpack::admin_url(); ?>' );
6148
				}
6149
			});
6150
		});
6151
6152
		// It's a dev environment.  Ignore.
6153
		$( '.is-dev-env' ).click(function( e ) {
6154
			data.crisis_resolution_action = 'whitelist';
6155
			$( '#jp-id-crisis-question-2 .spinner' ).show();
6156
			$.post( ajaxurl, data, function() {
6157
				$( '.jp-id-crisis-question' ).hide();
6158
				$( '.banner-title' ).hide();
6159
				$( '#jp-id-crisis-success' ).show();
6160
				setTimeout( autodismissSuccessBanner, 4 * SECOND_IN_MS );
6161
			});
6162
		});
6163
6164
		$( '.not-reconnecting' ).click(contactSupport);
6165
		$( '.not-staging-or-dev' ).click(contactSupport);
6166
	});
6167
})( jQuery );
6168
</script>
6169
<?php
6170
	}
6171
6172
	/**
6173
	 * Displays an admin_notice, alerting the user to an identity crisis.
6174
	 */
6175
	public function alert_identity_crisis() {
6176
		// @todo temporary killing of feature in 3.8.1 as it revealed a number of scenarios not foreseen.
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...
6177
		if ( ! Jetpack::is_development_version() ) {
6178
			return;
6179
		}
6180
6181
		// @todo temporary copout for dealing with domain mapping
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...
6182
		// @see https://github.com/Automattic/jetpack/issues/2702
6183
		if ( is_multisite() && defined( 'SUNRISE' ) && ! Jetpack::is_development_version() ) {
6184
			return;
6185
		}
6186
6187
		if ( ! current_user_can( 'jetpack_disconnect' ) ) {
6188
			return;
6189
		}
6190
6191
		if ( ! $errors = self::check_identity_crisis() ) {
6192
			return;
6193
		}
6194
6195
		// Only show on dashboard and jetpack pages
6196
		$screen = get_current_screen();
6197
		if ( 'dashboard' !== $screen->base && ! did_action( 'jetpack_notices' ) ) {
6198
			return;
6199
		}
6200
6201
		// Include the js!
6202
		$ajax_nonce = wp_create_nonce( 'resolve-identity-crisis' );
6203
		$this->identity_crisis_js( $ajax_nonce );
6204
6205
		// Include the CSS!
6206
		if ( ! wp_script_is( 'jetpack', 'done' ) ) {
6207
			$this->admin_banner_styles();
6208
		}
6209
6210
		if ( ! array_key_exists( 'error_code', $errors ) ) {
6211
			$key = 'siteurl';
6212
			if ( ! $errors[ $key ] ) {
6213
				$key = 'home';
6214
			}
6215
		} else {
6216
			$key = 'error_code';
6217
			// 401 is the only error we care about.  Any other errors should not trigger the alert.
6218
			if ( 401 !== $errors[ $key ] ) {
6219
				return;
6220
			}
6221
		}
6222
6223
		?>
6224
6225
		<style>
6226
			.jp-identity-crisis .jp-btn-group {
6227
					margin: 15px 0;
6228
				}
6229
			.jp-identity-crisis strong {
6230
					color: #518d2a;
6231
				}
6232
			.jp-identity-crisis.dismiss {
6233
				display: none;
6234
			}
6235
			.jp-identity-crisis .button {
6236
				margin-right: 4px;
6237
			}
6238
		</style>
6239
6240
		<div id="message" class="error jetpack-message jp-identity-crisis stay-visible">
6241
			<div class="service-mark"></div>
6242
			<div class="jp-id-banner__content">
6243
				<!-- <h3 class="banner-title"><?php _e( 'Something\'s not quite right with your Jetpack connection! Let\'s fix that.', 'jetpack' ); ?></h3> -->
6244
6245
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-1">
6246
					<?php
6247
					// 401 means that this site has been disconnected from wpcom, but the remote site still thinks it's connected.
6248
					if ( 'error_code' == $key && '401' == $errors[ $key ] ) : ?>
6249
						<div class="banner-content">
6250
							<p><?php
6251
								/* translators: %s is a URL */
6252
								printf( __( 'Our records show that this site does not have a valid connection to WordPress.com. Please reset your connection to fix this. <a href="%s" target="_blank">What caused this?</a>', 'jetpack' ), 'https://jetpack.com/support/no-valid-wordpress-com-connection/' );
6253
							?></p>
6254
						</div>
6255
						<div class="jp-btn-group">
6256
							<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a>
6257
							<span class="idc-separator">|</span>
6258
							<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>"><?php _e( 'Deactivate Jetpack', 'jetpack' ); ?></a>
6259
						</div>
6260
					<?php else : ?>
6261
							<div class="banner-content">
6262
							<p><?php printf( __( 'It looks like you may have changed your domain. Is <strong>%1$s</strong> still your site\'s domain, or have you updated it to <strong> %2$s </strong>?', 'jetpack' ), $errors[ $key ], (string) get_option( $key ) ); ?></p>
6263
							</div>
6264
						<div class="jp-btn-group">
6265
							<a href="#" class="regular site-moved"><?php printf( __( '%s is now my domain.', 'jetpack' ), $errors[ $key ] ); ?></a> <span class="idc-separator">|</span> <a href="#" class="site-not-moved" ><?php printf( __( '%s is still my domain.', 'jetpack' ), (string) get_option( $key ) ); ?></a>
6266
							<span class="spinner"></span>
6267
						</div>
6268
					<?php endif ; ?>
6269
				</div>
6270
6271
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-2" style="display: none;">
6272
					<div class="banner-content">
6273
						<p><?php printf(
6274
							/* translators: %1$s, %2$s and %3$s are URLs */
6275
							__(
6276
								'Are <strong> %2$s </strong> and <strong> %1$s </strong> two completely separate websites? If so we should create a new connection, which will reset your followers and linked services. <a href="%3$s"><em>What does this mean?</em></a>',
6277
								'jetpack'
6278
							),
6279
							$errors[ $key ],
6280
							(string) get_option( $key ),
6281
							'https://jetpack.com/support/what-does-resetting-the-connection-mean/'
6282
						); ?></p>
6283
					</div>
6284
					<div class="jp-btn-group">
6285
						<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6286
						<a href="#" class="is-dev-env"><?php _e( 'This is a development environment', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6287
						<a href="https://jetpack.com/contact-support/" class="contact-support"><?php _e( 'Submit a support ticket', 'jetpack' ); ?></a>
6288
						<span class="spinner"></span>
6289
					</div>
6290
				</div>
6291
6292
				<div class="jp-id-crisis-success" id="jp-id-crisis-success" style="display: none;">
6293
					<h3 class="success-notice"><?php printf( __( 'Thanks for taking the time to sort things out. We&#039;ve updated our records accordingly!', 'jetpack' ) ); ?></h3>
6294
				</div>
6295
			</div>
6296
		</div>
6297
6298
		<?php
6299
	}
6300
6301
	/**
6302
	 * Maybe Use a .min.css stylesheet, maybe not.
6303
	 *
6304
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6305
	 */
6306
	public static function maybe_min_asset( $url, $path, $plugin ) {
6307
		// Short out on things trying to find actual paths.
6308
		if ( ! $path || empty( $plugin ) ) {
6309
			return $url;
6310
		}
6311
6312
		// Strip out the abspath.
6313
		$base = dirname( plugin_basename( $plugin ) );
6314
6315
		// Short out on non-Jetpack assets.
6316
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6317
			return $url;
6318
		}
6319
6320
		// File name parsing.
6321
		$file              = "{$base}/{$path}";
6322
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6323
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6324
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6325
		$extension         = array_shift( $file_name_parts_r );
6326
6327
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6328
			// Already pointing at the minified version.
6329
			if ( 'min' === $file_name_parts_r[0] ) {
6330
				return $url;
6331
			}
6332
6333
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6334
			if ( file_exists( $min_full_path ) ) {
6335
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6336
			}
6337
		}
6338
6339
		return $url;
6340
	}
6341
6342
	/**
6343
	 * Maybe inlines a stylesheet.
6344
	 *
6345
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6346
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6347
	 *
6348
	 * Attached to `style_loader_tag` filter.
6349
	 *
6350
	 * @param string $tag The tag that would link to the external asset.
6351
	 * @param string $handle The registered handle of the script in question.
6352
	 *
6353
	 * @return string
6354
	 */
6355
	public static function maybe_inline_style( $tag, $handle ) {
6356
		global $wp_styles;
6357
		$item = $wp_styles->registered[ $handle ];
6358
6359
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6360
			return $tag;
6361
		}
6362
6363
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6364
			$href = $matches[1];
6365
			// Strip off query string
6366
			if ( $pos = strpos( $href, '?' ) ) {
6367
				$href = substr( $href, 0, $pos );
6368
			}
6369
			// Strip off fragment
6370
			if ( $pos = strpos( $href, '#' ) ) {
6371
				$href = substr( $href, 0, $pos );
6372
			}
6373
		} else {
6374
			return $tag;
6375
		}
6376
6377
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6378
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6379
			return $tag;
6380
		}
6381
6382
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6383
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6384
			// And this isn't the pass that actually deals with the RTL version...
6385
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6386
				// Short out, as the RTL version will deal with it in a moment.
6387
				return $tag;
6388
			}
6389
		}
6390
6391
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6392
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6393
		if ( $css ) {
6394
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6395
			if ( empty( $item->extra['after'] ) ) {
6396
				wp_add_inline_style( $handle, $css );
6397
			} else {
6398
				array_unshift( $item->extra['after'], $css );
6399
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6400
			}
6401
		}
6402
6403
		return $tag;
6404
	}
6405
6406
	/**
6407
	 * Loads a view file from the views
6408
	 *
6409
	 * Data passed in with the $data parameter will be available in the
6410
	 * template file as $data['value']
6411
	 *
6412
	 * @param string $template - Template file to load
6413
	 * @param array $data - Any data to pass along to the template
6414
	 * @return boolean - If template file was found
6415
	 **/
6416
	public function load_view( $template, $data = array() ) {
6417
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6418
6419
		if( file_exists( $views_dir . $template ) ) {
6420
			require_once( $views_dir . $template );
6421
			return true;
6422
		}
6423
6424
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6425
		return false;
6426
	}
6427
6428
	/**
6429
	 * Sends a ping to the Jetpack servers to toggle on/off remote portions
6430
	 * required by some modules.
6431
	 *
6432
	 * @param string $module_slug
6433
	 */
6434
	public function toggle_module_on_wpcom( $module_slug ) {
6435
		Jetpack::init()->sync->register( 'noop' );
6436
6437
		if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
6438
			self::check_privacy( $module_slug );
6439
		}
6440
6441
	}
6442
6443
	/**
6444
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6445
	 */
6446
	public function deprecated_hooks() {
6447
		global $wp_filter;
6448
6449
		/*
6450
		 * Format:
6451
		 * deprecated_filter_name => replacement_name
6452
		 *
6453
		 * If there is no replacement us null for replacement_name
6454
		 */
6455
		$deprecated_list = array(
6456
			'jetpack_bail_on_shortcode'                => 'jetpack_shortcodes_to_include',
6457
			'wpl_sharing_2014_1'                       => null,
6458
			'jetpack-tools-to-include'                 => 'jetpack_tools_to_include',
6459
			'jetpack_identity_crisis_options_to_check' => null,
6460
		);
6461
6462
		// This is a silly loop depth. Better way?
6463
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6464
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
6465
				foreach( $wp_filter[$hook] AS $func => $values ) {
6466
					foreach( $values AS $hooked ) {
6467
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
6468
					}
6469
				}
6470
			}
6471
		}
6472
	}
6473
6474
	/**
6475
	 * Converts any url in a stylesheet, to the correct absolute url.
6476
	 *
6477
	 * Considerations:
6478
	 *  - Normal, relative URLs     `feh.png`
6479
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6480
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6481
	 *  - Absolute URLs             `http://domain.com/feh.png`
6482
	 *  - Domain root relative URLs `/feh.png`
6483
	 *
6484
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6485
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6486
	 *
6487
	 * @return mixed|string
6488
	 */
6489
	public static function absolutize_css_urls( $css, $css_file_url ) {
6490
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6491
		$css_dir = dirname( $css_file_url );
6492
		$p       = parse_url( $css_dir );
6493
		$domain  = sprintf(
6494
					'%1$s//%2$s%3$s%4$s',
6495
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6496
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6497
					$p['host'],
6498
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6499
				);
6500
6501
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6502
			$find = $replace = array();
6503
			foreach ( $matches as $match ) {
6504
				$url = trim( $match['path'], "'\" \t" );
6505
6506
				// If this is a data url, we don't want to mess with it.
6507
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6508
					continue;
6509
				}
6510
6511
				// If this is an absolute or protocol-agnostic url,
6512
				// we don't want to mess with it.
6513
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6514
					continue;
6515
				}
6516
6517
				switch ( substr( $url, 0, 1 ) ) {
6518
					case '/':
6519
						$absolute = $domain . $url;
6520
						break;
6521
					default:
6522
						$absolute = $css_dir . '/' . $url;
6523
				}
6524
6525
				$find[]    = $match[0];
6526
				$replace[] = sprintf( 'url("%s")', $absolute );
6527
			}
6528
			$css = str_replace( $find, $replace, $css );
6529
		}
6530
6531
		return $css;
6532
	}
6533
6534
	/**
6535
	 * This method checks to see if SSL is required by the site in
6536
	 * order to visit it in some way other than only setting the
6537
	 * https value in the home or siteurl values.
6538
	 *
6539
	 * @since 3.2
6540
	 * @return boolean
6541
	 **/
6542
	private function is_ssl_required_to_visit_site() {
6543
		global $wp_version;
6544
		$ssl = is_ssl();
6545
6546
		if ( force_ssl_admin() ) {
6547
			$ssl = true;
6548
		}
6549
		return $ssl;
6550
	}
6551
6552
	/**
6553
	 * This methods removes all of the registered css files on the frontend
6554
	 * from Jetpack in favor of using a single file. In effect "imploding"
6555
	 * all the files into one file.
6556
	 *
6557
	 * Pros:
6558
	 * - Uses only ONE css asset connection instead of 15
6559
	 * - Saves a minimum of 56k
6560
	 * - Reduces server load
6561
	 * - Reduces time to first painted byte
6562
	 *
6563
	 * Cons:
6564
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6565
	 *		should not cause any issues with themes.
6566
	 * - Plugins/themes dequeuing styles no longer do anything. See
6567
	 *		jetpack_implode_frontend_css filter for a workaround
6568
	 *
6569
	 * For some situations developers may wish to disable css imploding and
6570
	 * instead operate in legacy mode where each file loads seperately and
6571
	 * can be edited individually or dequeued. This can be accomplished with
6572
	 * the following line:
6573
	 *
6574
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6575
	 *
6576
	 * @since 3.2
6577
	 **/
6578
	public function implode_frontend_css( $travis_test = false ) {
6579
		$do_implode = true;
6580
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6581
			$do_implode = false;
6582
		}
6583
6584
		/**
6585
		 * Allow CSS to be concatenated into a single jetpack.css file.
6586
		 *
6587
		 * @since 3.2.0
6588
		 *
6589
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6590
		 */
6591
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6592
6593
		// Do not use the imploded file when default behaviour was altered through the filter
6594
		if ( ! $do_implode ) {
6595
			return;
6596
		}
6597
6598
		// We do not want to use the imploded file in dev mode, or if not connected
6599
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6600
			if ( ! $travis_test ) {
6601
				return;
6602
			}
6603
		}
6604
6605
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6606
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6607
			return;
6608
		}
6609
6610
		/*
6611
		 * Now we assume Jetpack is connected and able to serve the single
6612
		 * file.
6613
		 *
6614
		 * In the future there will be a check here to serve the file locally
6615
		 * or potentially from the Jetpack CDN
6616
		 *
6617
		 * For now:
6618
		 * - Enqueue a single imploded css file
6619
		 * - Zero out the style_loader_tag for the bundled ones
6620
		 * - Be happy, drink scotch
6621
		 */
6622
6623
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6624
6625
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6626
6627
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6628
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6629
	}
6630
6631
	function concat_remove_style_loader_tag( $tag, $handle ) {
6632
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6633
			$tag = '';
6634
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6635
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6636
			}
6637
		}
6638
6639
		return $tag;
6640
	}
6641
6642
	/*
6643
	 * Check the heartbeat data
6644
	 *
6645
	 * Organizes the heartbeat data by severity.  For example, if the site
6646
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6647
	 *
6648
	 * Data will be added to "caution" array, if it either:
6649
	 *  - Out of date Jetpack version
6650
	 *  - Out of date WP version
6651
	 *  - Out of date PHP version
6652
	 *
6653
	 * $return array $filtered_data
6654
	 */
6655
	public static function jetpack_check_heartbeat_data() {
6656
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6657
6658
		$good    = array();
6659
		$caution = array();
6660
		$bad     = array();
6661
6662
		foreach ( $raw_data as $stat => $value ) {
6663
6664
			// Check jetpack version
6665
			if ( 'version' == $stat ) {
6666
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6667
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6668
					continue;
6669
				}
6670
			}
6671
6672
			// Check WP version
6673
			if ( 'wp-version' == $stat ) {
6674
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6675
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6676
					continue;
6677
				}
6678
			}
6679
6680
			// Check PHP version
6681
			if ( 'php-version' == $stat ) {
6682
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6683
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6684
					continue;
6685
				}
6686
			}
6687
6688
			// Check ID crisis
6689
			if ( 'identitycrisis' == $stat ) {
6690
				if ( 'yes' == $value ) {
6691
					$bad[ $stat ] = $value;
6692
					continue;
6693
				}
6694
			}
6695
6696
			// The rest are good :)
6697
			$good[ $stat ] = $value;
6698
		}
6699
6700
		$filtered_data = array(
6701
			'good'    => $good,
6702
			'caution' => $caution,
6703
			'bad'     => $bad
6704
		);
6705
6706
		return $filtered_data;
6707
	}
6708
6709
6710
	/*
6711
	 * This method is used to organize all options that can be reset
6712
	 * without disconnecting Jetpack.
6713
	 *
6714
	 * It is used in class.jetpack-cli.php to reset options
6715
	 *
6716
	 * @return array of options to delete.
6717
	 */
6718
	public static function get_jetpack_options_for_reset() {
6719
		$jetpack_options            = Jetpack_Options::get_option_names();
6720
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6721
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6722
6723
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6724
6725
		// A manual build of the wp options
6726
		$wp_options = array(
6727
			'sharing-options',
6728
			'disabled_likes',
6729
			'disabled_reblogs',
6730
			'jetpack_comments_likes_enabled',
6731
			'wp_mobile_excerpt',
6732
			'wp_mobile_featured_images',
6733
			'wp_mobile_app_promos',
6734
			'stats_options',
6735
			'stats_dashboard_widget',
6736
			'safecss_preview_rev',
6737
			'safecss_rev',
6738
			'safecss_revision_migrated',
6739
			'nova_menu_order',
6740
			'jetpack_portfolio',
6741
			'jetpack_portfolio_posts_per_page',
6742
			'jetpack_testimonial',
6743
			'jetpack_testimonial_posts_per_page',
6744
			'wp_mobile_custom_css',
6745
			'sharedaddy_disable_resources',
6746
			'sharing-options',
6747
			'sharing-services',
6748
			'site_icon_temp_data',
6749
			'featured-content',
6750
			'site_logo',
6751
		);
6752
6753
		// Flag some Jetpack options as unsafe
6754
		$unsafe_options = array(
6755
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6756
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6757
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6758
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6759
6760
			// non_compact
6761
			'activated',
6762
6763
			// private
6764
			'register',
6765
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6766
			'user_token',                  // (string) The User Token of this site. (deprecated)
6767
			'user_tokens'
6768
		);
6769
6770
		// Remove the unsafe Jetpack options
6771
		foreach ( $unsafe_options as $unsafe_option ) {
6772
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6773
				unset( $all_jp_options[ $key ] );
6774
			}
6775
		}
6776
6777
		$options = array(
6778
			'jp_options' => $all_jp_options,
6779
			'wp_options' => $wp_options
6780
		);
6781
6782
		return $options;
6783
	}
6784
6785
	/**
6786
	 * Check if an option of a Jetpack module has been updated.
6787
	 *
6788
	 * If any module option has been updated before Jump Start has been dismissed,
6789
	 * update the 'jumpstart' option so we can hide Jump Start.
6790
	 *
6791
	 * @param string $option_name
6792
	 *
6793
	 * @return bool
6794
	 */
6795
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6796
		// Bail if Jump Start has already been dismissed
6797
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6798
			return false;
6799
		}
6800
6801
		$jetpack = Jetpack::init();
6802
6803
		// Manual build of module options
6804
		$option_names = self::get_jetpack_options_for_reset();
6805
6806
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6807
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6808
6809
			//Jump start is being dismissed send data to MC Stats
6810
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6811
6812
			$jetpack->do_stats( 'server_side' );
6813
		}
6814
6815
	}
6816
6817
	/*
6818
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6819
	 * so we can bring them directly to their site in calypso.
6820
	 *
6821
	 * @param string | url
6822
	 * @return string | url without the guff
6823
	 */
6824
	public static function build_raw_urls( $url ) {
6825
		$strip_http = '/.*?:\/\//i';
6826
		$url = preg_replace( $strip_http, '', $url  );
6827
		$url = str_replace( '/', '::', $url );
6828
		return $url;
6829
	}
6830
6831
	/**
6832
	 * Stores and prints out domains to prefetch for page speed optimization.
6833
	 *
6834
	 * @param mixed $new_urls
6835
	 */
6836
	public static function dns_prefetch( $new_urls = null ) {
6837
		static $prefetch_urls = array();
6838
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6839
			echo "\r\n";
6840
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6841
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6842
			}
6843
		} elseif ( ! empty( $new_urls ) ) {
6844
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6845
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6846
			}
6847
			foreach ( (array) $new_urls as $this_new_url ) {
6848
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6849
			}
6850
			$prefetch_urls = array_unique( $prefetch_urls );
6851
		}
6852
	}
6853
6854
	public function wp_dashboard_setup() {
6855
		if ( self::is_active() ) {
6856
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6857
			$widget_title = __( 'Site Stats', 'jetpack' );
6858
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6859
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6860
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6861
		}
6862
6863
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6864
			wp_add_dashboard_widget(
6865
				'jetpack_summary_widget',
6866
				$widget_title,
0 ignored issues
show
Bug introduced by
The variable $widget_title does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
6867
				array( __CLASS__, 'dashboard_widget' )
6868
			);
6869
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6870
6871
			// If we're inactive and not in development mode, sort our box to the top.
6872
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6873
				global $wp_meta_boxes;
6874
6875
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6876
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6877
6878
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6879
			}
6880
		}
6881
	}
6882
6883
	/**
6884
	 * @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...
6885
	 * @return mixed
6886
	 */
6887
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6888
		if ( ! is_array( $sorted ) ) {
6889
			return $sorted;
6890
		}
6891
6892
		foreach ( $sorted as $box_context => $ids ) {
6893
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6894
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6895
				continue;
6896
			}
6897
6898
			$ids_array = explode( ',', $ids );
6899
			$key = array_search( 'dashboard_stats', $ids_array );
6900
6901
			if ( false !== $key ) {
6902
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6903
				$ids_array[ $key ] = 'jetpack_summary_widget';
6904
				$sorted[ $box_context ] = implode( ',', $ids_array );
6905
				// We've found it, stop searching, and just return.
6906
				break;
6907
			}
6908
		}
6909
6910
		return $sorted;
6911
	}
6912
6913
	public static function dashboard_widget() {
6914
		/**
6915
		 * Fires when the dashboard is loaded.
6916
		 *
6917
		 * @since 3.4.0
6918
		 */
6919
		do_action( 'jetpack_dashboard_widget' );
6920
	}
6921
6922
	public static function dashboard_widget_footer() {
6923
		?>
6924
		<footer>
6925
6926
		<div class="protect">
6927
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6928
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6929
				<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>
6930
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6931
				<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' ); ?>">
6932
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6933
				</a>
6934
			<?php else : ?>
6935
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6936
			<?php endif; ?>
6937
		</div>
6938
6939
		<div class="akismet">
6940
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6941
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6942
				<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>
6943 View Code Duplication
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6944
				<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">
6945
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6946
				</a>
6947
			<?php else : ?>
6948
				<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>
6949
			<?php endif; ?>
6950
		</div>
6951
6952
6953 View Code Duplication
		<?php if ( ! current_user_can( 'edit_posts' ) && self::is_user_connected() ) : ?>
6954
			<div style="width: 100%; text-align: center; padding-top: 20px; clear: both;"><a class="button" title="<?php esc_attr_e( 'Unlink your account from WordPress.com', 'jetpack' ); ?>" href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'unlink', 'redirect' => 'sub-unlink' ), admin_url( 'index.php' ) ), 'jetpack-unlink' ) ); ?>"><?php esc_html_e( 'Unlink your account from WordPress.com', 'jetpack' ); ?></a></div>
6955
		<?php endif; ?>
6956
6957
		</footer>
6958
		<?php
6959
	}
6960
6961
	public function dashboard_widget_connect_to_wpcom() {
6962
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6963
			return;
6964
		}
6965
		?>
6966
		<div class="wpcom-connect">
6967
			<div class="jp-emblem">
6968
			<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0" y="0" viewBox="0 0 172.9 172.9" enable-background="new 0 0 172.9 172.9" xml:space="preserve">
6969
				<path d="M86.4 0C38.7 0 0 38.7 0 86.4c0 47.7 38.7 86.4 86.4 86.4s86.4-38.7 86.4-86.4C172.9 38.7 134.2 0 86.4 0zM83.1 106.6l-27.1-6.9C49 98 45.7 90.1 49.3 84l33.8-58.5V106.6zM124.9 88.9l-33.8 58.5V66.3l27.1 6.9C125.1 74.9 128.4 82.8 124.9 88.9z"/>
6970
			</svg>
6971
			</div>
6972
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6973
			<p><?php echo wp_kses( __( 'Connecting Jetpack will show you <strong>stats</strong> about your traffic, <strong>protect</strong> you from brute force attacks, <strong>speed up</strong> your images and photos, and enable other <strong>traffic and security</strong> features.', 'jetpack' ), 'jetpack' ) ?></p>
6974
6975
			<div class="actions">
6976
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6977
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6978
				</a>
6979
			</div>
6980
		</div>
6981
		<?php
6982
	}
6983
6984
	/*
6985
	 * A graceful transition to using Core's site icon.
6986
	 *
6987
	 * All of the hard work has already been done with the image
6988
	 * in all_done_page(). All that needs to be done now is update
6989
	 * the option and display proper messaging.
6990
	 *
6991
	 * @todo remove when WP 4.3 is minimum
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
6992
	 *
6993
	 * @since 3.6.1
6994
	 *
6995
	 * @return bool false = Core's icon not available || true = Core's icon is available
6996
	 */
6997
	public static function jetpack_site_icon_available_in_core() {
6998
		global $wp_version;
6999
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
7000
7001
		if ( ! $core_icon_available ) {
7002
			return false;
7003
		}
7004
7005
		// No need for Jetpack's site icon anymore if core's is already set
7006
		if ( has_site_icon() ) {
7007
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
7008
				Jetpack::log( 'deactivate', 'site-icon' );
7009
				Jetpack::deactivate_module( 'site-icon' );
7010
			}
7011
			return true;
7012
		}
7013
7014
		// Transfer Jetpack's site icon to use core.
7015
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
7016
		if ( $site_icon_id ) {
7017
			// Update core's site icon
7018
			update_option( 'site_icon', $site_icon_id );
7019
7020
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
7021
			delete_option( 'site_icon_id' );
7022
		}
7023
7024
		// No need for Jetpack's site icon anymore
7025
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
7026
			Jetpack::log( 'deactivate', 'site-icon' );
7027
			Jetpack::deactivate_module( 'site-icon' );
7028
		}
7029
7030
		return true;
7031
	}
7032
7033
}
7034