Completed
Push — add/i18n ( eebccc...956613 )
by
unknown
539:47 queued 530:15
created

Jetpack::alert_auto_ssl_fail()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 46
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 1 Features 1
Metric Value
cc 2
eloc 17
c 7
b 1
f 1
nc 2
nop 0
dl 0
loc 46
rs 8.9411
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
			self::$instance = new Jetpack;
311
312
			self::$instance->plugin_upgrade();
313
314
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
315
316
		}
317
318
		return self::$instance;
319
	}
320
321
	/**
322
	 * Must never be called statically
323
	 */
324
	function plugin_upgrade() {
325
		if ( Jetpack::is_active() ) {
326
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
327
			if ( JETPACK__VERSION != $version ) {
328
329
				// Check which active modules actually exist and remove others from active_modules list
330
				$unfiltered_modules = Jetpack::get_active_modules();
331
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
332
				if ( array_diff( $unfiltered_modules, $modules ) ) {
333
					Jetpack_Options::update_option( 'active_modules', $modules );
334
				}
335
336
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
337
				/**
338
				 * Fires when synchronizing all registered options and constants.
339
				 *
340
				 * @since 3.3.0
341
				 */
342
				do_action( 'jetpack_sync_all_registered_options' );
343
			}
344
		}
345
	}
346
347
	static function activate_manage( ) {
348
349
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
350
			self::activate_module( 'manage', false, false );
351
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
352
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
353
		}
354
355
	}
356
357
	/**
358
	 * Constructor.  Initializes WordPress hooks
359
	 */
360
	private function __construct() {
361
		/*
362
		 * Check for and alert any deprecated hooks
363
		 */
364
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
365
366
		/**
367
		 * We need sync object even in Multisite mode
368
		 */
369
		$this->sync = new Jetpack_Sync;
370
371
		/**
372
		 * Trigger a wp_version sync when updating WP versions
373
		 **/
374
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
375
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
376
377
		add_action( 'init', array( $this, 'sync_update_data') );
378
		add_action( 'init', array( $this, 'sync_theme_data' ) );
379
380
		/*
381
		 * Load things that should only be in Network Admin.
382
		 *
383
		 * For now blow away everything else until a more full
384
		 * understanding of what is needed at the network level is
385
		 * available
386
		 */
387
		if( is_multisite() ) {
388
			Jetpack_Network::init();
389
390
			// Only sync this info if we are on a multi site
391
			// @since  3.7
392
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
393
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
394
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
395
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
396
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
397
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
398
399
			if( is_network_admin() ) {
400
				// Sync network site data if it is updated or not.
401
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
402
				return; // End here to prevent single site actions from firing
403
			}
404
		}
405
406
407
		$theme_slug = get_option( 'stylesheet' );
408
409
410
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
411
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
412
		$this->sync->options(
413
			JETPACK__PLUGIN_DIR . 'jetpack.php',
414
			'home',
415
			'siteurl',
416
			'blogname',
417
			'gmt_offset',
418
			'timezone_string',
419
			'security_report',
420
			'stylesheet',
421
			"theme_mods_{$theme_slug}",
422
			'jetpack_sync_non_public_post_stati',
423
			'jetpack_options',
424
			'site_icon', // (int) - ID of core's Site Icon attachment ID
425
			'default_post_format',
426
			'default_category',
427
			'large_size_w',
428
			'large_size_h',
429
			'thumbnail_size_w',
430
			'thumbnail_size_h',
431
			'medium_size_w',
432
			'medium_size_h',
433
			'thumbnail_crop',
434
			'image_default_link_type'
435
		);
436
437
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
438
			$this->sync->options( __FILE__, 'jetpack_' . $option );
439
		}
440
441
		/**
442
		 * Sometimes you want to sync data to .com without adding options to .org sites.
443
		 * The mock option allows you to do just that.
444
		 */
445
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
446
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
447
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
448
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
449
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
450
451
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
452
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
453
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
454
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
455
456
		/**
457
		 * Trigger an update to the main_network_site when we update the blogname of a site.
458
		 *
459
		 */
460
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
461
462
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
463
464
		// Update the settings everytime the we register a new user to the site or we delete a user.
465
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
466
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
467
468
		// Unlink user before deleting the user from .com
469
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
470
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
471
472
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
473
			@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...
474
475
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
476
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
477
478
			$this->require_jetpack_authentication();
479
480
			if ( Jetpack::is_active() ) {
481
				// Hack to preserve $HTTP_RAW_POST_DATA
482
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
483
484
				$signed = $this->verify_xml_rpc_signature();
485
				if ( $signed && ! is_wp_error( $signed ) ) {
486
					// The actual API methods.
487
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
488
				} else {
489
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
490
					// active Jetpack connection, so that additional users can link their account.
491
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
492
				}
493
			} else {
494
				// The bootstrap API methods.
495
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
496
			}
497
498
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
499
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
500
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
501
			$this->require_jetpack_authentication();
502
			$this->add_remote_request_handlers();
503
		} else {
504
			if ( Jetpack::is_active() ) {
505
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
506
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
507
			}
508
		}
509
510
		if ( Jetpack::is_active() ) {
511
			Jetpack_Heartbeat::init();
512
		}
513
514
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
515
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
516
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
517
		}
518
519
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
520
521
		add_action( 'admin_init', array( $this, 'admin_init' ) );
522
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
523
524
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
525
526
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
527
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
528
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
529
530
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
531
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
532
533
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
534
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
535
536
		// Identity Crisis AJAX callback function
537
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
538
539
		// JITM AJAX callback function
540
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
541
542
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
543
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
544
545
		// Universal ajax callback for all tracking events triggered via js
546
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
547
548
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
549
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
550
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
551
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
552
553
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
554
555
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
556
557
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
558
559
		/**
560
		 * These actions run checks to load additional files.
561
		 * They check for external files or plugins, so they need to run as late as possible.
562
		 */
563
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
564
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
565
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
566
567
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
568
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
569
570
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
571
572
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
573
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
574
575
		// A filter to control all just in time messages
576
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
577
578
		/**
579
		 * This is the hack to concatinate all css files into one.
580
		 * For description and reasoning see the implode_frontend_css method
581
		 *
582
		 * Super late priority so we catch all the registered styles
583
		 */
584
		if( !is_admin() ) {
585
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
586
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
587
		}
588
589
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
590
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
591
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
592
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
593
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
594
595
	}
596
597
	/*
598
	 * Make sure any site icon added to core can get
599
	 * synced back to dotcom, so we can display it there.
600
	 */
601
	function jetpack_sync_core_icon() {
602
		if ( function_exists( 'get_site_icon_url' ) ) {
603
			$url = get_site_icon_url();
604
		} else {
605
			return;
606
		}
607
608
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
609
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
610
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
611
			// This is the option that is synced with dotcom
612
			Jetpack_Options::update_option( 'site_icon_url', $url );
613
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
614
			Jetpack_Options::delete_option( 'site_icon_url' );
615
		}
616
	}
617
618
	function jetpack_admin_ajax_tracks_callback() {
619
		// Check for nonce
620
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
621
			wp_die( 'Permissions check failed.' );
622
		}
623
624
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
625
			wp_die( 'No valid event name or type.' );
626
		}
627
628
		$tracks_data = array();
629
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
630
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
631
		}
632
633
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
634
		wp_send_json_success();
635
		wp_die();
636
	}
637
638
	function jetpack_admin_ajax_callback() {
639
		// Check for nonce
640 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
641
			wp_die( 'permissions check failed' );
642
		}
643
644
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
645
			$slug = $_REQUEST['thisModuleSlug'];
646
647
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
648
				wp_die( 'That is not a Jetpack module slug' );
649
			}
650
651
			if ( Jetpack::is_module_active( $slug ) ) {
652
				Jetpack::deactivate_module( $slug );
653
			} else {
654
				Jetpack::activate_module( $slug, false, false );
655
			}
656
657
			$modules = Jetpack_Admin::init()->get_modules();
658
			echo json_encode( $modules[ $slug ] );
659
660
			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...
661
		}
662
663
		wp_die();
664
	}
665
666
	/*
667
	 * Sometimes we need to refresh the data,
668
	 * especially if the page is visited via a 'history'
669
	 * event like back/forward
670
	 */
671
	function jetpack_admin_ajax_refresh_data() {
672
		// Check for nonce
673 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
674
			wp_die( 'permissions check failed' );
675
		}
676
677
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
678
			$modules = Jetpack_Admin::init()->get_modules();
679
			echo json_encode( $modules );
680
			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...
681
		}
682
683
		wp_die();
684
	}
685
686
	/**
687
	 * The callback for the JITM ajax requests.
688
	 */
689
	function jetpack_jitm_ajax_callback() {
690
		// Check for nonce
691
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
692
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
693
		}
694
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
695
			$module_slug = $_REQUEST['jitmModule'];
696
			Jetpack::log( 'activate', $module_slug );
697
			Jetpack::activate_module( $module_slug, false, false );
698
			Jetpack::state( 'message', 'no_message' );
699
700
			//A Jetpack module is being activated through a JITM, track it
701
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
702
			$this->do_stats( 'server_side' );
703
704
			wp_send_json_success();
705
		}
706
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
707
			// get the hide_jitm options array
708
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
709
			$module_slug = $_REQUEST['jitmModule'];
710
711
			if( ! $jetpack_hide_jitm ) {
712
				$jetpack_hide_jitm = array(
713
					$module_slug => 'hide'
714
				);
715
			} else {
716
				$jetpack_hide_jitm[$module_slug] = 'hide';
717
			}
718
719
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
720
721
			//jitm is being dismissed forever, track it
722
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
723
			$this->do_stats( 'server_side' );
724
725
			wp_send_json_success();
726
		}
727 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
728
			$module_slug = $_REQUEST['jitmModule'];
729
730
			// User went to WordPress.com, track this
731
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
732
			$this->do_stats( 'server_side' );
733
734
			wp_send_json_success();
735
		}
736 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
737
			$track = $_REQUEST['jitmModule'];
738
739
			// User is viewing JITM, track it.
740
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
741
			$this->do_stats( 'server_side' );
742
743
			wp_send_json_success();
744
		}
745
	}
746
747
	/**
748
	 * If there are any stats that need to be pushed, but haven't been, push them now.
749
	 */
750
	function __destruct() {
751
		if ( ! empty( $this->stats ) ) {
752
			$this->do_stats( 'server_side' );
753
		}
754
	}
755
756
	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...
757
		switch( $cap ) {
758
			case 'jetpack_connect' :
759
			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...
760
				if ( Jetpack::is_development_mode() ) {
761
					$caps = array( 'do_not_allow' );
762
					break;
763
				}
764
				/**
765
				 * Pass through. If it's not development mode, these should match disconnect.
766
				 * Let users disconnect if it's development mode, just in case things glitch.
767
				 */
768
			case 'jetpack_disconnect' :
769
				/**
770
				 * In multisite, can individual site admins manage their own connection?
771
				 *
772
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
773
				 */
774
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
775
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
776
						/**
777
						 * We need to update the option name -- it's terribly unclear which
778
						 * direction the override goes.
779
						 *
780
						 * @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...
781
						 */
782
						$caps = array( 'do_not_allow' );
783
						break;
784
					}
785
				}
786
787
				$caps = array( 'manage_options' );
788
				break;
789
			case 'jetpack_manage_modules' :
790
			case 'jetpack_activate_modules' :
791
			case 'jetpack_deactivate_modules' :
792
				$caps = array( 'manage_options' );
793
				break;
794
			case 'jetpack_configure_modules' :
795
				$caps = array( 'manage_options' );
796
				break;
797
			case 'jetpack_network_admin_page':
798
			case 'jetpack_network_settings_page':
799
				$caps = array( 'manage_network_plugins' );
800
				break;
801
			case 'jetpack_network_sites_page':
802
				$caps = array( 'manage_sites' );
803
				break;
804
			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...
805
				if ( Jetpack::is_development_mode() ) {
806
					$caps = array( 'manage_options' );
807
					break;
808
				}
809
810
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
811
				if ( ! current_user_can( 'edit_posts' ) ) {
812
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
813
						// We need this in order to unlink the user.
814
						$this->admin_page_load();
815
					}
816
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
817
						$caps = array( 'do_not_allow' );
818
						break;
819
					}
820
				}
821
822
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
823
					$caps = array( 'do_not_allow' );
824
					break;
825
				}
826
				/**
827
				 * Pass through. If it's not development mode, these should match the admin page.
828
				 * Let users disconnect if it's development mode, just in case things glitch.
829
				 */
830
			case 'jetpack_connect_user' :
831
				if ( Jetpack::is_development_mode() ) {
832
					$caps = array( 'do_not_allow' );
833
					break;
834
				}
835
				$caps = array( 'read' );
836
				break;
837
		}
838
		return $caps;
839
	}
840
841
	function require_jetpack_authentication() {
842
		// Don't let anyone authenticate
843
		$_COOKIE = array();
844
		remove_all_filters( 'authenticate' );
845
846
		/**
847
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
848
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
849
		 * generate false-positives.
850
		 */
851
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
852
853
		if ( Jetpack::is_active() ) {
854
			// Allow Jetpack authentication
855
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
856
		}
857
	}
858
859
	/**
860
	 * Load language files
861
	 * @action plugins_loaded
862
	 */
863
	public static function plugin_textdomain() {
864
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
865
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
866
	}
867
868
	/**
869
	 * Register assets for use in various modules and the Jetpack admin page.
870
	 *
871
	 * @uses wp_script_is, wp_register_script, plugins_url
872
	 * @action wp_loaded
873
	 * @return null
874
	 */
875
	public function register_assets() {
876
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
877
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
878
		}
879
880 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
881
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
882
		}
883
884 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
885
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
886
		}
887
888 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
889
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
890
		}
891
892
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
893
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
894
895
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
896
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
897
			if ( ! is_numeric( $fb_app_id ) ) {
898
				$fb_app_id = '';
899
			}
900
			wp_localize_script(
901
				'jetpack-facebook-embed',
902
				'jpfbembed',
903
				array(
904
					'appid' => $fb_app_id,
905
					'locale' => $this->get_locale(),
906
				)
907
			);
908
		}
909
910
		/**
911
		 * As jetpack_register_genericons is by default fired off a hook,
912
		 * the hook may have already fired by this point.
913
		 * So, let's just trigger it manually.
914
		 */
915
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
916
		jetpack_register_genericons();
917
918 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
919
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
920
	}
921
922
	/**
923
	 * Guess locale from language code.
924
	 *
925
	 * @param string $lang Language code.
926
	 * @return string|bool
927
	 */
928 View Code Duplication
	function guess_locale_from_lang( $lang ) {
929
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
930
			return 'en_US';
931
		}
932
933
		if ( ! class_exists( 'GP_Locales' ) ) {
934
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
935
				return false;
936
			}
937
938
			require JETPACK__GLOTPRESS_LOCALES_PATH;
939
		}
940
941
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
942
			// WP.com: get_locale() returns 'it'
943
			$locale = GP_Locales::by_slug( $lang );
944
		} else {
945
			// Jetpack: get_locale() returns 'it_IT';
946
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
947
		}
948
949
		if ( ! $locale ) {
950
			return false;
951
		}
952
953
		if ( empty( $locale->facebook_locale ) ) {
954
			if ( empty( $locale->wp_locale ) ) {
955
				return false;
956
			} else {
957
				// Facebook SDK is smart enough to fall back to en_US if a
958
				// locale isn't supported. Since supported Facebook locales
959
				// can fall out of sync, we'll attempt to use the known
960
				// wp_locale value and rely on said fallback.
961
				return $locale->wp_locale;
962
			}
963
		}
964
965
		return $locale->facebook_locale;
966
	}
967
968
	/**
969
	 * Get the locale.
970
	 *
971
	 * @return string|bool
972
	 */
973
	function get_locale() {
974
		$locale = $this->guess_locale_from_lang( get_locale() );
975
976
		if ( ! $locale ) {
977
			$locale = 'en_US';
978
		}
979
980
		return $locale;
981
	}
982
983
	/**
984
	 * Device Pixels support
985
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
986
	 */
987
	function devicepx() {
988
		if ( Jetpack::is_active() ) {
989
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
990
		}
991
	}
992
993
	/**
994
	 * Return the network_site_url so that .com knows what network this site is a part of.
995
	 * @param  bool $option
996
	 * @return string
997
	 */
998
	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...
999
		return network_site_url();
1000
	}
1001
	/**
1002
	 * Network Name.
1003
	 */
1004
	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...
1005
		global $current_site;
1006
		return $current_site->site_name;
1007
	}
1008
	/**
1009
	 * Does the network allow new user and site registrations.
1010
	 * @return string
1011
	 */
1012
	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...
1013
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1014
	}
1015
	/**
1016
	 * Does the network allow admins to add new users.
1017
	 * @return boolian
1018
	 */
1019
	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...
1020
		return (bool) get_site_option( 'add_new_users' );
1021
	}
1022
	/**
1023
	 * File upload psace left per site in MB.
1024
	 *  -1 means NO LIMIT.
1025
	 * @return number
1026
	 */
1027
	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...
1028
		// value in MB
1029
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1030
	}
1031
1032
	/**
1033
	 * Network allowed file types.
1034
	 * @return string
1035
	 */
1036
	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...
1037
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1038
	}
1039
1040
	/**
1041
	 * Maximum file upload size set by the network.
1042
	 * @return number
1043
	 */
1044
	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...
1045
		// value in KB
1046
		return get_site_option( 'fileupload_maxk', 300 );
1047
	}
1048
1049
	/**
1050
	 * Lets us know if a site allows admins to manage the network.
1051
	 * @return array
1052
	 */
1053
	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...
1054
		return get_site_option( 'menu_items' );
1055
	}
1056
1057
	/**
1058
	 * Return whether we are dealing with a multi network setup or not.
1059
	 * The reason we are type casting this is because we want to avoid the situation where
1060
	 * the result is false since when is_main_network_option return false it cases
1061
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1062
	 * database which could be set to anything as opposed to what this function returns.
1063
	 * @param  bool  $option
1064
	 *
1065
	 * @return boolean
1066
	 */
1067
	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...
1068
		// return '1' or ''
1069
		return (string) (bool) Jetpack::is_multi_network();
1070
	}
1071
1072
	/**
1073
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1074
	 *
1075
	 * @param  string  $option
1076
	 * @return boolean
1077
	 */
1078
	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...
1079
		return (string) (bool) is_multisite();
1080
	}
1081
1082
	/**
1083
	 * Implemented since there is no core is multi network function
1084
	 * Right now there is no way to tell if we which network is the dominant network on the system
1085
	 *
1086
	 * @since  3.3
1087
	 * @return boolean
1088
	 */
1089
	public static function is_multi_network() {
1090
		global  $wpdb;
1091
1092
		// if we don't have a multi site setup no need to do any more
1093
		if ( ! is_multisite() ) {
1094
			return false;
1095
		}
1096
1097
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1098
		if ( $num_sites > 1 ) {
1099
			return true;
1100
		} else {
1101
			return false;
1102
		}
1103
	}
1104
1105
	/**
1106
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1107
	 * @return null
1108
	 */
1109
	function update_jetpack_main_network_site_option() {
1110
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1111
		/**
1112
		 * Fires when the site URL is updated.
1113
		 * Determines if the site is the main site of a Mulitiste network.
1114
		 *
1115
		 * @since 3.3.0
1116
		 *
1117
		 * @param string jetpack_main_network_site.
1118
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1119
		 */
1120
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1121
		/**
1122
		 * Fires when the site URL is updated.
1123
		 * Determines if the is part of a multi network.
1124
		 *
1125
		 * @since 3.3.0
1126
		 *
1127
		 * @param string jetpack_is_main_network.
1128
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1129
		 */
1130
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1131
		/**
1132
		 * Fires when the site URL is updated.
1133
		 * Determines if the site is part of a multisite network.
1134
		 *
1135
		 * @since 3.4.0
1136
		 *
1137
		 * @param string jetpack_is_multi_site.
1138
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1139
		 */
1140
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1141
	}
1142
	/**
1143
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1144
	 *
1145
	 */
1146
	function update_jetpack_network_settings() {
1147
		// Only sync this info for the main network site.
1148
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1149
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1150
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1151
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1152
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1153
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1154
1155
	}
1156
1157
	/**
1158
	 * Get back if the current site is single user site.
1159
	 *
1160
	 * @return bool
1161
	 */
1162
	public static function is_single_user_site() {
1163
1164
		$user_query = new WP_User_Query( array(
1165
			'blog_id' => get_current_blog_id(),
1166
			'fields'  => 'ID',
1167
			'number' => 2
1168
		) );
1169
		return 1 === (int) $user_query->get_total();
1170
	}
1171
1172
	/**
1173
	 * Returns true if the site has file write access false otherwise.
1174
	 * @return string ( '1' | '0' )
1175
	 **/
1176
	public static function file_system_write_access() {
1177
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1178
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1179
		}
1180
1181
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1182
1183
		$filesystem_method = get_filesystem_method();
1184
		if ( $filesystem_method === 'direct' ) {
1185
			return 1;
1186
		}
1187
1188
		ob_start();
1189
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1190
		ob_end_clean();
1191
		if ( $filesystem_credentials_are_stored ) {
1192
			return 1;
1193
		}
1194
		return 0;
1195
	}
1196
1197
	/**
1198
	 * Finds out if a site is using a version control system.
1199
	 * @return string ( '1' | '0' )
1200
	 **/
1201
	public static function is_version_controlled() {
1202
1203
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1204
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1205
		}
1206
		$updater = new WP_Automatic_Updater();
1207
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1208
		// transients should not be empty
1209
		if ( empty( $is_version_controlled ) ) {
1210
			$is_version_controlled = '0';
1211
		}
1212
		return $is_version_controlled;
1213
	}
1214
1215
	/**
1216
	 * Determines whether the current theme supports featured images or not.
1217
	 * @return string ( '1' | '0' )
1218
	 */
1219
	public static function featured_images_enabled() {
1220
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1221
	}
1222
1223
	/*
1224
	 * Sync back wp_version
1225
	 */
1226
	public static function get_wp_version() {
1227
		global $wp_version;
1228
		return $wp_version;
1229
	}
1230
1231
	/**
1232
	 * Keeps wp_version in sync with .com when WordPress core updates
1233
	 **/
1234
	public static function update_get_wp_version( $update, $meta_data ) {
1235
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1236
			/** This action is documented in wp-includes/option.php */
1237
			/**
1238
			 * This triggers the sync for the jetpack version
1239
			 * See Jetpack_Sync options method for more info.
1240
			 */
1241
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1242
		}
1243
	}
1244
1245
	/**
1246
	 * Triggers a sync of update counts and update details
1247
	 */
1248
	function sync_update_data() {
1249
		// Anytime WordPress saves update data, we'll want to sync update data
1250
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1251
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1252
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1253
		// Anytime a connection to jetpack is made, sync the update data
1254
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1255
		// Anytime the Jetpack Version changes, sync the the update data
1256
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1257
1258
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1259
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1260
		}
1261
1262
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1263
	}
1264
1265
	/**
1266
	 * Triggers a sync of information specific to the current theme.
1267
	 */
1268
	function sync_theme_data() {
1269
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1270
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1271
	}
1272
1273
	/**
1274
	 * jetpack_updates is saved in the following schema:
1275
	 *
1276
	 * array (
1277
	 *      'plugins'                       => (int) Number of plugin updates available.
1278
	 *      'themes'                        => (int) Number of theme updates available.
1279
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1280
	 *      'translations'                  => (int) Number of translation updates available.
1281
	 *      'total'                         => (int) Total of all available updates.
1282
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1283
	 * )
1284
	 * @return array
1285
	 */
1286
	public static function get_updates() {
1287
		$update_data = wp_get_update_data();
1288
1289
		// Stores the individual update counts as well as the total count.
1290
		if ( isset( $update_data['counts'] ) ) {
1291
			$updates = $update_data['counts'];
1292
		}
1293
1294
		// If we need to update WordPress core, let's find the latest version number.
1295 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1296
			$cur = get_preferred_from_update_core();
1297
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1298
				$updates['wp_update_version'] = $cur->current;
1299
			}
1300
		}
1301
		return isset( $updates ) ? $updates : array();
1302
	}
1303
1304
	public static function get_update_details() {
1305
		$update_details = array(
1306
			'update_core' => get_site_transient( 'update_core' ),
1307
			'update_plugins' => get_site_transient( 'update_plugins' ),
1308
			'update_themes' => get_site_transient( 'update_themes' ),
1309
		);
1310
		return $update_details;
1311
	}
1312
1313
	public static function refresh_update_data() {
1314
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1315
			/**
1316
			 * Fires whenever the amount of updates needed for a site changes.
1317
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1318
			 *
1319
			 * @since 3.7.0
1320
			 *
1321
			 * @param string jetpack_updates
1322
			 * @param array Update counts calculated by Jetpack::get_updates
1323
			 */
1324
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1325
		}
1326
		/**
1327
		 * Fires whenever the amount of updates needed for a site changes.
1328
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1329
		 *
1330
		 * @since 3.7.0
1331
		 *
1332
		 * @param string jetpack_update_details
1333
		 * @param array Update details calculated by Jetpack::get_update_details
1334
		 */
1335
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1336
	}
1337
1338
	public static function refresh_theme_data() {
1339
		/**
1340
		 * Fires whenever a theme change is made.
1341
		 *
1342
		 * @since 3.8.1
1343
		 *
1344
		 * @param string featured_images_enabled
1345
		 * @param boolean Whether featured images are enabled or not
1346
		 */
1347
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1348
	}
1349
1350
	/**
1351
	 * Invalides the transient as well as triggers the update of the mock option.
1352
	 *
1353
	 * @return null
1354
	 */
1355
	function is_single_user_site_invalidate() {
1356
		/**
1357
		 * Fires when a user is added or removed from a site.
1358
		 * Determines if the site is a single user site.
1359
		 *
1360
		 * @since 3.4.0
1361
		 *
1362
		 * @param string jetpack_single_user_site.
1363
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1364
		 */
1365
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1366
	}
1367
1368
	/**
1369
	 * Is Jetpack active?
1370
	 */
1371
	public static function is_active() {
1372
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1373
	}
1374
1375
	/**
1376
	 * Is Jetpack in development (offline) mode?
1377
	 */
1378
	public static function is_development_mode() {
1379
		$development_mode = false;
1380
1381
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1382
			$development_mode = JETPACK_DEV_DEBUG;
1383
		}
1384
1385
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1386
			$development_mode = true;
1387
		}
1388
		/**
1389
		 * Filters Jetpack's development mode.
1390
		 *
1391
		 * @see http://jetpack.com/support/development-mode/
1392
		 *
1393
		 * @since 2.2.1
1394
		 *
1395
		 * @param bool $development_mode Is Jetpack's development mode active.
1396
		 */
1397
		return apply_filters( 'jetpack_development_mode', $development_mode );
1398
	}
1399
1400
	/**
1401
	* Get Jetpack development mode notice text and notice class.
1402
	*
1403
	* Mirrors the checks made in Jetpack::is_development_mode
1404
	*
1405
	*/
1406
	public static function show_development_mode_notice() {
1407
		if ( Jetpack::is_development_mode() ) {
1408
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1409
				$notice = sprintf(
1410
					/* translators: %s is a URL */
1411
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1412
					'http://jetpack.com/support/development-mode/'
1413
				);
1414
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1415
				$notice = sprintf(
1416
					/* translators: %s is a URL */
1417
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1418
					'http://jetpack.com/support/development-mode/'
1419
				);
1420
			} else {
1421
				$notice = sprintf(
1422
					/* translators: %s is a URL */
1423
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1424
					'http://jetpack.com/support/development-mode/'
1425
				);
1426
			}
1427
1428
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1429
		}
1430
1431
		// Throw up a notice if using a development version and as for feedback.
1432
		if ( Jetpack::is_development_version() ) {
1433
			/* translators: %s is a URL */
1434
			$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/' );
1435
1436
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1437
		}
1438
		// Throw up a notice if using staging mode
1439
		if ( Jetpack::is_staging_site() ) {
1440
			/* translators: %s is a URL */
1441
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1442
1443
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1444
		}
1445
	}
1446
1447
	/**
1448
	 * Whether Jetpack's version maps to a public release, or a development version.
1449
	 */
1450
	public static function is_development_version() {
1451
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1452
	}
1453
1454
	/**
1455
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1456
	 */
1457
	public static function is_user_connected( $user_id = false ) {
1458
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1459
		if ( ! $user_id ) {
1460
			return false;
1461
		}
1462
		return (bool) Jetpack_Data::get_access_token( $user_id );
1463
	}
1464
1465
	/**
1466
	 * Get the wpcom user data of the current|specified connected user.
1467
	 */
1468 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1469
		if ( ! $user_id ) {
1470
			$user_id = get_current_user_id();
1471
		}
1472
		Jetpack::load_xml_rpc_client();
1473
		$xml = new Jetpack_IXR_Client( array(
1474
			'user_id' => $user_id,
1475
		) );
1476
		$xml->query( 'wpcom.getUser' );
1477
		if ( ! $xml->isError() ) {
1478
			return $xml->getResponse();
1479
		}
1480
		return false;
1481
	}
1482
1483
	/**
1484
	 * Get the wpcom email of the current|specified connected user.
1485
	 */
1486 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1487
		if ( ! $user_id ) {
1488
			$user_id = get_current_user_id();
1489
		}
1490
		Jetpack::load_xml_rpc_client();
1491
		$xml = new Jetpack_IXR_Client( array(
1492
			'user_id' => $user_id,
1493
		) );
1494
		$xml->query( 'wpcom.getUserEmail' );
1495
		if ( ! $xml->isError() ) {
1496
			return $xml->getResponse();
1497
		}
1498
		return false;
1499
	}
1500
1501
	/**
1502
	 * Get the wpcom email of the master user.
1503
	 */
1504
	public static function get_master_user_email() {
1505
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1506
		if ( $master_user_id ) {
1507
			return self::get_connected_user_email( $master_user_id );
1508
		}
1509
		return '';
1510
	}
1511
1512
	function current_user_is_connection_owner() {
1513
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1514
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1515
	}
1516
1517
	/**
1518
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1519
	 */
1520
	function extra_oembed_providers() {
1521
		// Cloudup: https://dev.cloudup.com/#oembed
1522
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1523
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1524
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1525
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1526
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1527
	}
1528
1529
	/**
1530
	 * Synchronize connected user role changes
1531
	 */
1532
	function user_role_change( $user_id ) {
1533
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1534
			$current_user_id = get_current_user_id();
1535
			wp_set_current_user( $user_id );
1536
			$role = $this->translate_current_user_to_role();
1537
			$signed_role = $this->sign_role( $role );
1538
			wp_set_current_user( $current_user_id );
1539
1540
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1541
			$master_user_id = absint( $master_token->external_user_id );
1542
1543
			if ( ! $master_user_id )
1544
				return; // this shouldn't happen
1545
1546
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1547
			//@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...
1548
1549
			//try to choose a new master if we're demoting the current one
1550
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1551
				$query = new WP_User_Query(
1552
					array(
1553
						'fields'  => array( 'id' ),
1554
						'role'    => 'administrator',
1555
						'orderby' => 'id',
1556
						'exclude' => array( $master_user_id ),
1557
					)
1558
				);
1559
				$new_master = false;
1560
				foreach ( $query->results as $result ) {
1561
					$uid = absint( $result->id );
1562
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1563
						$new_master = $uid;
1564
						break;
1565
					}
1566
				}
1567
1568
				if ( $new_master ) {
1569
					Jetpack_Options::update_option( 'master_user', $new_master );
1570
				}
1571
				// else disconnect..?
1572
			}
1573
		}
1574
	}
1575
1576
	/**
1577
	 * Loads the currently active modules.
1578
	 */
1579
	public static function load_modules() {
1580
		if ( ! self::is_active() && !self::is_development_mode() ) {
1581
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1582
				return;
1583
			}
1584
		}
1585
1586
		$version = Jetpack_Options::get_option( 'version' );
1587 View Code Duplication
		if ( ! $version ) {
1588
			$version = $old_version = JETPACK__VERSION . ':' . time();
1589
			/** This action is documented in class.jetpack.php */
1590
			do_action( 'updating_jetpack_version', $version, false );
1591
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1592
		}
1593
		list( $version ) = explode( ':', $version );
1594
1595
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1596
1597
		$modules_data = array();
1598
1599
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1600
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1601
			$updated_modules = array();
1602
			foreach ( $modules as $module ) {
1603
				$modules_data[ $module ] = Jetpack::get_module( $module );
1604
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1605
					continue;
1606
				}
1607
1608
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1609
					continue;
1610
				}
1611
1612
				$updated_modules[] = $module;
1613
			}
1614
1615
			$modules = array_diff( $modules, $updated_modules );
1616
		}
1617
1618
		$is_development_mode = Jetpack::is_development_mode();
1619
1620
		foreach ( $modules as $index => $module ) {
1621
			// If we're in dev mode, disable modules requiring a connection
1622
			if ( $is_development_mode ) {
1623
				// Prime the pump if we need to
1624
				if ( empty( $modules_data[ $module ] ) ) {
1625
					$modules_data[ $module ] = Jetpack::get_module( $module );
1626
				}
1627
				// If the module requires a connection, but we're in local mode, don't include it.
1628
				if ( $modules_data[ $module ]['requires_connection'] ) {
1629
					continue;
1630
				}
1631
			}
1632
1633
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1634
				continue;
1635
			}
1636
1637
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1638
				unset( $modules[ $index ] );
1639
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1640
				continue;
1641
			}
1642
1643
			/**
1644
			 * Fires when a specific module is loaded.
1645
			 * The dynamic part of the hook, $module, is the module slug.
1646
			 *
1647
			 * @since 1.1.0
1648
			 */
1649
			do_action( 'jetpack_module_loaded_' . $module );
1650
		}
1651
1652
		/**
1653
		 * Fires when all the modules are loaded.
1654
		 *
1655
		 * @since 1.1.0
1656
		 */
1657
		do_action( 'jetpack_modules_loaded' );
1658
1659
		// 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.
1660
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1661
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1662
	}
1663
1664
	/**
1665
	 * Check if Jetpack's REST API compat file should be included
1666
	 * @action plugins_loaded
1667
	 * @return null
1668
	 */
1669
	public function check_rest_api_compat() {
1670
		/**
1671
		 * Filters the list of REST API compat files to be included.
1672
		 *
1673
		 * @since 2.2.5
1674
		 *
1675
		 * @param array $args Array of REST API compat files to include.
1676
		 */
1677
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1678
1679
		if ( function_exists( 'bbpress' ) )
1680
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1681
1682
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1683
			require_once $_jetpack_rest_api_compat_include;
1684
	}
1685
1686
	/**
1687
	 * Gets all plugins currently active in values, regardless of whether they're
1688
	 * traditionally activated or network activated.
1689
	 *
1690
	 * @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...
1691
	 */
1692
	public static function get_active_plugins() {
1693
		$active_plugins = (array) get_option( 'active_plugins', array() );
1694
1695
		if ( is_multisite() ) {
1696
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1697
			// whereas active_plugins stores them in the values.
1698
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1699
			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...
1700
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1701
			}
1702
		}
1703
1704
		sort( $active_plugins );
1705
1706
		return array_unique( $active_plugins );
1707
	}
1708
1709
	/**
1710
	 * Gets and parses additional plugin data to send with the heartbeat data
1711
	 *
1712
	 * @since 3.8.1
1713
	 *
1714
	 * @return array Array of plugin data
1715
	 */
1716
	public static function get_parsed_plugin_data() {
1717
		if ( ! function_exists( 'get_plugins' ) ) {
1718
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1719
		}
1720
		$all_plugins    = get_plugins();
1721
		$active_plugins = Jetpack::get_active_plugins();
1722
1723
		$plugins = array();
1724
		foreach ( $all_plugins as $path => $plugin_data ) {
1725
			$plugins[ $path ] = array(
1726
					'is_active' => in_array( $path, $active_plugins ),
1727
					'file'      => $path,
1728
					'name'      => $plugin_data['Name'],
1729
					'version'   => $plugin_data['Version'],
1730
					'author'    => $plugin_data['Author'],
1731
			);
1732
		}
1733
1734
		return $plugins;
1735
	}
1736
1737
	/**
1738
	 * Gets and parses theme data to send with the heartbeat data
1739
	 *
1740
	 * @since 3.8.1
1741
	 *
1742
	 * @return array Array of theme data
1743
	 */
1744
	public static function get_parsed_theme_data() {
1745
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1746
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1747
1748
		$themes = array();
1749
		foreach ( $all_themes as $slug => $theme_data ) {
1750
			$theme_headers = array();
1751
			foreach ( $header_keys as $header_key ) {
1752
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1753
			}
1754
1755
			$themes[ $slug ] = array(
1756
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1757
					'slug' => $slug,
1758
					'theme_root' => $theme_data->get_theme_root_uri(),
1759
					'parent' => $theme_data->parent(),
1760
					'headers' => $theme_headers
1761
			);
1762
		}
1763
1764
		return $themes;
1765
	}
1766
1767
	/**
1768
	 * Checks whether a specific plugin is active.
1769
	 *
1770
	 * We don't want to store these in a static variable, in case
1771
	 * there are switch_to_blog() calls involved.
1772
	 */
1773
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1774
		return in_array( $plugin, self::get_active_plugins() );
1775
	}
1776
1777
	/**
1778
	 * Check if Jetpack's Open Graph tags should be used.
1779
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1780
	 *
1781
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1782
	 * @action plugins_loaded
1783
	 * @return null
1784
	 */
1785
	public function check_open_graph() {
1786
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1787
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1788
		}
1789
1790
		$active_plugins = self::get_active_plugins();
1791
1792
		if ( ! empty( $active_plugins ) ) {
1793
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1794
				if ( in_array( $plugin, $active_plugins ) ) {
1795
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1796
					break;
1797
				}
1798
			}
1799
		}
1800
1801
		/**
1802
		 * Allow the addition of Open Graph Meta Tags to all pages.
1803
		 *
1804
		 * @since 2.0.3
1805
		 *
1806
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1807
		 */
1808
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1809
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1810
		}
1811
	}
1812
1813
	/**
1814
	 * Check if Jetpack's Twitter tags should be used.
1815
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1816
	 *
1817
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1818
	 * @action plugins_loaded
1819
	 * @return null
1820
	 */
1821
	public function check_twitter_tags() {
1822
1823
		$active_plugins = self::get_active_plugins();
1824
1825
		if ( ! empty( $active_plugins ) ) {
1826
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1827
				if ( in_array( $plugin, $active_plugins ) ) {
1828
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1829
					break;
1830
				}
1831
			}
1832
		}
1833
1834
		/**
1835
		 * Allow Twitter Card Meta tags to be disabled.
1836
		 *
1837
		 * @since 2.6.0
1838
		 *
1839
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1840
		 */
1841
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1842
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1843
		}
1844
	}
1845
1846
1847
1848
1849
	/*
1850
	 *
1851
	 * Jetpack Security Reports
1852
	 *
1853
	 * Allowed types: login_form, backup, file_scanning, spam
1854
	 *
1855
	 * 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)
1856
	 *
1857
	 * 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)
1858
	 *
1859
	 *
1860
	 * Example code to submit a security report:
1861
	 *
1862
	 *  function akismet_submit_jetpack_security_report() {
1863
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1864
	 *  }
1865
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1866
	 *
1867
	 */
1868
1869
1870
	/**
1871
	 * Calls for security report submissions.
1872
	 *
1873
	 * @return null
1874
	 */
1875
	public static function perform_security_reporting() {
1876
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1877
1878
		if ( $no_check_needed ) {
1879
			return;
1880
		}
1881
1882
		/**
1883
		 * Fires before a security report is created.
1884
		 *
1885
		 * @since 3.4.0
1886
		 */
1887
		do_action( 'jetpack_security_report' );
1888
1889
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1890
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1891
	}
1892
1893
	/**
1894
	 * Allows plugins to submit security reports.
1895
 	 *
1896
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1897
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1898
	 * @param array   $args         See definitions above
1899
	 */
1900
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1901
1902
		if( !doing_action( 'jetpack_security_report' ) ) {
1903
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1904
		}
1905
1906
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1907
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1908
		}
1909
1910
		if( !function_exists( 'get_plugin_data' ) ) {
1911
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1912
		}
1913
1914
		//Get rid of any non-allowed args
1915
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1916
1917
		$plugin = get_plugin_data( $plugin_file );
1918
1919
		if ( !$plugin['Name'] ) {
1920
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1921
		}
1922
1923
		// Sanitize everything to make sure we're not syncing something wonky
1924
		$type = sanitize_key( $type );
1925
1926
		$args['plugin'] = $plugin;
1927
1928
		// Cast blocked, last and next as integers.
1929
		// Last and next should be in unix timestamp format
1930
		if ( isset( $args['blocked'] ) ) {
1931
			$args['blocked'] = (int) $args['blocked'];
1932
		}
1933
		if ( isset( $args['last'] ) ) {
1934
			$args['last'] = (int) $args['last'];
1935
		}
1936
		if ( isset( $args['next'] ) ) {
1937
			$args['next'] = (int) $args['next'];
1938
		}
1939
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1940
			$args['status'] = 'ok';
1941
		}
1942
		if ( isset( $args['message'] ) ) {
1943
1944
			if( $args['status'] == 'ok' ) {
1945
				unset( $args['message'] );
1946
			}
1947
1948
			$allowed_html = array(
1949
			    'a' => array(
1950
			        'href' => array(),
1951
			        'title' => array()
1952
			    ),
1953
			    'em' => array(),
1954
			    'strong' => array(),
1955
			);
1956
1957
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1958
		}
1959
1960
		$plugin_name = $plugin[ 'Name' ];
1961
1962
		self::$security_report[ $type ][ $plugin_name ] = $args;
1963
	}
1964
1965
	/**
1966
	 * Collects a new report if needed, then returns it.
1967
	 */
1968
	public function get_security_report() {
1969
		self::perform_security_reporting();
1970
		return Jetpack_Options::get_option( 'security_report' );
1971
	}
1972
1973
1974
/* Jetpack Options API */
1975
1976
	public static function get_option_names( $type = 'compact' ) {
1977
		return Jetpack_Options::get_option_names( $type );
1978
	}
1979
1980
	/**
1981
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1982
 	 *
1983
	 * @param string $name    Option name
1984
	 * @param mixed  $default (optional)
1985
	 */
1986
	public static function get_option( $name, $default = false ) {
1987
		return Jetpack_Options::get_option( $name, $default );
1988
	}
1989
1990
	/**
1991
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1992
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1993
	* $name must be a registered option name.
1994
	*/
1995
	public static function create_nonce( $name ) {
1996
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1997
1998
		Jetpack_Options::update_option( $name, $secret );
1999
		@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...
2000
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2001
			return new Jetpack_Error( 'missing_secrets' );
2002
2003
		return array(
2004
			'secret_1' => $secret_1,
2005
			'secret_2' => $secret_2,
2006
			'eol'      => $eol,
2007
		);
2008
	}
2009
2010
	/**
2011
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2012
 	 *
2013
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2014
	 * @param string $name  Option name
2015
	 * @param mixed  $value Option value
2016
	 */
2017
	public static function update_option( $name, $value ) {
2018
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2019
		return Jetpack_Options::update_option( $name, $value );
2020
	}
2021
2022
	/**
2023
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2024
 	 *
2025
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2026
	 * @param array $array array( option name => option value, ... )
2027
	 */
2028
	public static function update_options( $array ) {
2029
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2030
		return Jetpack_Options::update_options( $array );
2031
	}
2032
2033
	/**
2034
	 * Deletes the given option.  May be passed multiple option names as an array.
2035
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2036
	 *
2037
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2038
	 * @param string|array $names
2039
	 */
2040
	public static function delete_option( $names ) {
2041
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2042
		return Jetpack_Options::delete_option( $names );
2043
	}
2044
2045
	/**
2046
	 * Enters a user token into the user_tokens option
2047
	 *
2048
	 * @param int $user_id
2049
	 * @param string $token
2050
	 * return bool
2051
	 */
2052
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2053
		// not designed for concurrent updates
2054
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2055
		if ( ! is_array( $user_tokens ) )
2056
			$user_tokens = array();
2057
		$user_tokens[$user_id] = $token;
2058
		if ( $is_master_user ) {
2059
			$master_user = $user_id;
2060
			$options     = compact( 'user_tokens', 'master_user' );
2061
		} else {
2062
			$options = compact( 'user_tokens' );
2063
		}
2064
		return Jetpack_Options::update_options( $options );
2065
	}
2066
2067
	/**
2068
	 * Returns an array of all PHP files in the specified absolute path.
2069
	 * Equivalent to glob( "$absolute_path/*.php" ).
2070
	 *
2071
	 * @param string $absolute_path The absolute path of the directory to search.
2072
	 * @return array Array of absolute paths to the PHP files.
2073
	 */
2074
	public static function glob_php( $absolute_path ) {
2075
		if ( function_exists( 'glob' ) ) {
2076
			return glob( "$absolute_path/*.php" );
2077
		}
2078
2079
		$absolute_path = untrailingslashit( $absolute_path );
2080
		$files = array();
2081
		if ( ! $dir = @opendir( $absolute_path ) ) {
2082
			return $files;
2083
		}
2084
2085
		while ( false !== $file = readdir( $dir ) ) {
2086
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2087
				continue;
2088
			}
2089
2090
			$file = "$absolute_path/$file";
2091
2092
			if ( ! is_file( $file ) ) {
2093
				continue;
2094
			}
2095
2096
			$files[] = $file;
2097
		}
2098
2099
		closedir( $dir );
2100
2101
		return $files;
2102
	}
2103
2104
	public static function activate_new_modules( $redirect = false ) {
2105
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2106
			return;
2107
		}
2108
2109
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2110 View Code Duplication
		if ( ! $jetpack_old_version ) {
2111
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2112
			/** This action is documented in class.jetpack.php */
2113
			do_action( 'updating_jetpack_version', $version, false );
2114
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2115
		}
2116
2117
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2118
2119
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2120
			return;
2121
		}
2122
2123
		$active_modules     = Jetpack::get_active_modules();
2124
		$reactivate_modules = array();
2125
		foreach ( $active_modules as $active_module ) {
2126
			$module = Jetpack::get_module( $active_module );
2127
			if ( ! isset( $module['changed'] ) ) {
2128
				continue;
2129
			}
2130
2131
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2132
				continue;
2133
			}
2134
2135
			$reactivate_modules[] = $active_module;
2136
			Jetpack::deactivate_module( $active_module );
2137
		}
2138
2139
		$new_version = JETPACK__VERSION . ':' . time();
2140
		/** This action is documented in class.jetpack.php */
2141
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2142
		Jetpack_Options::update_options(
2143
			array(
2144
				'version'     => $new_version,
2145
				'old_version' => $jetpack_old_version,
2146
			)
2147
		);
2148
2149
		Jetpack::state( 'message', 'modules_activated' );
2150
		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...
2151
2152
		if ( $redirect ) {
2153
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2154
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2155
				$page = $_GET['page'];
2156
			}
2157
2158
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2159
			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...
2160
		}
2161
	}
2162
2163
	/**
2164
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2165
	 * Make sure to tuck away module "library" files in a sub-directory.
2166
	 */
2167
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2168
		static $modules = null;
2169
2170
		if ( ! isset( $modules ) ) {
2171
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2172
			// Use the cache if we're on the front-end and it's available...
2173
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2174
				$modules = $available_modules_option[ JETPACK__VERSION ];
2175
			} else {
2176
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2177
2178
				$modules = array();
2179
2180
				foreach ( $files as $file ) {
2181
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2182
						continue;
2183
					}
2184
2185
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2186
				}
2187
2188
				Jetpack_Options::update_option( 'available_modules', array(
2189
					JETPACK__VERSION => $modules,
2190
				) );
2191
			}
2192
		}
2193
2194
		/**
2195
		 * Filters the array of modules available to be activated.
2196
		 *
2197
		 * @since 2.4.0
2198
		 *
2199
		 * @param array $modules Array of available modules.
2200
		 * @param string $min_version Minimum version number required to use modules.
2201
		 * @param string $max_version Maximum version number required to use modules.
2202
		 */
2203
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2204
2205
		if ( ! $min_version && ! $max_version ) {
2206
			return array_keys( $mods );
2207
		}
2208
2209
		$r = array();
2210
		foreach ( $mods as $slug => $introduced ) {
2211
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2212
				continue;
2213
			}
2214
2215
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2216
				continue;
2217
			}
2218
2219
			$r[] = $slug;
2220
		}
2221
2222
		return $r;
2223
	}
2224
2225
	/**
2226
	 * Default modules loaded on activation.
2227
	 */
2228
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2229
		$return = array();
2230
2231
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2232
			$module_data = Jetpack::get_module( $module );
2233
2234
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2235
				case 'yes' :
2236
					$return[] = $module;
2237
					break;
2238
				case 'public' :
2239
					if ( Jetpack_Options::get_option( 'public' ) ) {
2240
						$return[] = $module;
2241
					}
2242
					break;
2243
				case 'no' :
2244
				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...
2245
					break;
2246
			}
2247
		}
2248
		/**
2249
		 * Filters the array of default modules.
2250
		 *
2251
		 * @since 2.5.0
2252
		 *
2253
		 * @param array $return Array of default modules.
2254
		 * @param string $min_version Minimum version number required to use modules.
2255
		 * @param string $max_version Maximum version number required to use modules.
2256
		 */
2257
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2258
	}
2259
2260
	/**
2261
	 * Checks activated modules during auto-activation to determine
2262
	 * if any of those modules are being deprecated.  If so, close
2263
	 * them out, and add any replacement modules.
2264
	 *
2265
	 * Runs at priority 99 by default.
2266
	 *
2267
	 * This is run late, so that it can still activate a module if
2268
	 * the new module is a replacement for another that the user
2269
	 * currently has active, even if something at the normal priority
2270
	 * would kibosh everything.
2271
	 *
2272
	 * @since 2.6
2273
	 * @uses jetpack_get_default_modules filter
2274
	 * @param array $modules
2275
	 * @return array
2276
	 */
2277
	function handle_deprecated_modules( $modules ) {
2278
		$deprecated_modules = array(
2279
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2280
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2281
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2282
		);
2283
2284
		// Don't activate SSO if they never completed activating WPCC.
2285
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2286
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2287
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2288
				$deprecated_modules['wpcc'] = null;
2289
			}
2290
		}
2291
2292
		foreach ( $deprecated_modules as $module => $replacement ) {
2293
			if ( Jetpack::is_module_active( $module ) ) {
2294
				self::deactivate_module( $module );
2295
				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...
2296
					$modules[] = $replacement;
2297
				}
2298
			}
2299
		}
2300
2301
		return array_unique( $modules );
2302
	}
2303
2304
	/**
2305
	 * Checks activated plugins during auto-activation to determine
2306
	 * if any of those plugins are in the list with a corresponding module
2307
	 * that is not compatible with the plugin. The module will not be allowed
2308
	 * to auto-activate.
2309
	 *
2310
	 * @since 2.6
2311
	 * @uses jetpack_get_default_modules filter
2312
	 * @param array $modules
2313
	 * @return array
2314
	 */
2315
	function filter_default_modules( $modules ) {
2316
2317
		$active_plugins = self::get_active_plugins();
2318
2319
		if ( ! empty( $active_plugins ) ) {
2320
2321
			// For each module we'd like to auto-activate...
2322
			foreach ( $modules as $key => $module ) {
2323
				// If there are potential conflicts for it...
2324
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2325
					// For each potential conflict...
2326
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2327
						// If that conflicting plugin is active...
2328
						if ( in_array( $plugin, $active_plugins ) ) {
2329
							// Remove that item from being auto-activated.
2330
							unset( $modules[ $key ] );
2331
						}
2332
					}
2333
				}
2334
			}
2335
		}
2336
2337
		return $modules;
2338
	}
2339
2340
	/**
2341
	 * Extract a module's slug from its full path.
2342
	 */
2343
	public static function get_module_slug( $file ) {
2344
		return str_replace( '.php', '', basename( $file ) );
2345
	}
2346
2347
	/**
2348
	 * Generate a module's path from its slug.
2349
	 */
2350
	public static function get_module_path( $slug ) {
2351
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2352
	}
2353
2354
	/**
2355
	 * Load module data from module file. Headers differ from WordPress
2356
	 * plugin headers to avoid them being identified as standalone
2357
	 * plugins on the WordPress plugins page.
2358
	 */
2359
	public static function get_module( $module ) {
2360
		$headers = array(
2361
			'name'                      => 'Module Name',
2362
			'description'               => 'Module Description',
2363
			'jumpstart_desc'            => 'Jumpstart Description',
2364
			'sort'                      => 'Sort Order',
2365
			'recommendation_order'      => 'Recommendation Order',
2366
			'introduced'                => 'First Introduced',
2367
			'changed'                   => 'Major Changes In',
2368
			'deactivate'                => 'Deactivate',
2369
			'free'                      => 'Free',
2370
			'requires_connection'       => 'Requires Connection',
2371
			'auto_activate'             => 'Auto Activate',
2372
			'module_tags'               => 'Module Tags',
2373
			'feature'                   => 'Feature',
2374
			'additional_search_queries' => 'Additional Search Queries',
2375
		);
2376
2377
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2378
2379
		$mod = Jetpack::get_file_data( $file, $headers );
2380
		if ( empty( $mod['name'] ) ) {
2381
			return false;
2382
		}
2383
2384
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2385
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2386
		$mod['deactivate']              = empty( $mod['deactivate'] );
2387
		$mod['free']                    = empty( $mod['free'] );
2388
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2389
2390
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2391
			$mod['auto_activate'] = 'No';
2392
		} else {
2393
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2394
		}
2395
2396
		if ( $mod['module_tags'] ) {
2397
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2398
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2399
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2400
		} else {
2401
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2402
		}
2403
2404
		if ( $mod['feature'] ) {
2405
			$mod['feature'] = explode( ',', $mod['feature'] );
2406
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2407
		} else {
2408
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2409
		}
2410
2411
		/**
2412
		 * Filters the feature array on a module.
2413
		 *
2414
		 * This filter allows you to control where each module is filtered: Recommended,
2415
		 * Jumpstart, and the default "Other" listing.
2416
		 *
2417
		 * @since 3.5.0
2418
		 *
2419
		 * @param array   $mod['feature'] The areas to feature this module:
2420
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2421
		 *     'Recommended' shows on the main Jetpack admin screen.
2422
		 *     'Other' should be the default if no other value is in the array.
2423
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2424
		 * @param array   $mod All the currently assembled module data.
2425
		 */
2426
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2427
2428
		/**
2429
		 * Filter the returned data about a module.
2430
		 *
2431
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2432
		 * so please be careful.
2433
		 *
2434
		 * @since 3.6.0
2435
		 *
2436
		 * @param array   $mod    The details of the requested module.
2437
		 * @param string  $module The slug of the module, e.g. sharedaddy
2438
		 * @param string  $file   The path to the module source file.
2439
		 */
2440
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2441
	}
2442
2443
	/**
2444
	 * Like core's get_file_data implementation, but caches the result.
2445
	 */
2446
	public static function get_file_data( $file, $headers ) {
2447
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2448
		$file_name = basename( $file );
2449
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2450
		$key              = md5( $file_name . serialize( $headers ) );
2451
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2452
2453
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2454
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2455
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2456
		}
2457
2458
		$data = get_file_data( $file, $headers );
2459
2460
		// Strip out any old Jetpack versions that are cluttering the option.
2461
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2462
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2463
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2464
2465
		return $data;
2466
	}
2467
2468
	/**
2469
	 * Return translated module tag.
2470
	 *
2471
	 * @param string $tag Tag as it appears in each module heading.
2472
	 *
2473
	 * @return mixed
2474
	 */
2475
	public static function translate_module_tag( $tag ) {
2476
		return jetpack_get_module_i18n_tag( $tag );
2477
	}
2478
2479
	/**
2480
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2481
	 *
2482
	 * @since 3.9.2
2483
	 *
2484
	 * @param array $modules
2485
	 *
2486
	 * @return string|void
2487
	 */
2488
	public static function get_translated_modules( $modules ) {
2489
		foreach ( $modules as $index => $module ) {
2490
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2491
			if ( isset( $module['name'] ) ) {
2492
				$modules[ $index ]['name'] = $i18n_module['name'];
2493
			}
2494
			if ( isset( $module['description'] ) ) {
2495
				$modules[ $index ]['description'] = $i18n_module['description'];
2496
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2497
			}
2498
		}
2499
		return $modules;
2500
	}
2501
2502
	/**
2503
	 * Get a list of activated modules as an array of module slugs.
2504
	 */
2505
	public static function get_active_modules() {
2506
		$active = Jetpack_Options::get_option( 'active_modules' );
2507
		if ( ! is_array( $active ) )
2508
			$active = array();
2509
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2510
			$active[] = 'vaultpress';
2511
		} else {
2512
			$active = array_diff( $active, array( 'vaultpress' ) );
2513
		}
2514
2515
		//If protect is active on the main site of a multisite, it should be active on all sites.
2516
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2517
			$active[] = 'protect';
2518
		}
2519
2520
		return array_unique( $active );
2521
	}
2522
2523
	/**
2524
	 * Check whether or not a Jetpack module is active.
2525
	 *
2526
	 * @param string $module The slug of a Jetpack module.
2527
	 * @return bool
2528
	 *
2529
	 * @static
2530
	 */
2531
	public static function is_module_active( $module ) {
2532
		return in_array( $module, self::get_active_modules() );
2533
	}
2534
2535
	public static function is_module( $module ) {
2536
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2537
	}
2538
2539
	/**
2540
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2541
	 *
2542
	 * @param bool $catch True to start catching, False to stop.
2543
	 *
2544
	 * @static
2545
	 */
2546
	public static function catch_errors( $catch ) {
2547
		static $display_errors, $error_reporting;
2548
2549
		if ( $catch ) {
2550
			$display_errors  = @ini_set( 'display_errors', 1 );
2551
			$error_reporting = @error_reporting( E_ALL );
2552
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2553
		} else {
2554
			@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...
2555
			@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...
2556
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2557
		}
2558
	}
2559
2560
	/**
2561
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2562
	 */
2563
	public static function catch_errors_on_shutdown() {
2564
		Jetpack::state( 'php_errors', ob_get_clean() );
2565
	}
2566
2567
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2568
		$jetpack = Jetpack::init();
2569
2570
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2571
		$modules = array_merge( $other_modules, $modules );
2572
2573
		// Look for standalone plugins and disable if active.
2574
2575
		$to_deactivate = array();
2576
		foreach ( $modules as $module ) {
2577
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2578
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2579
			}
2580
		}
2581
2582
		$deactivated = array();
2583
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2584
			list( $probable_file, $probable_title ) = $deactivate_me;
2585
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2586
				$deactivated[] = $module;
2587
			}
2588
		}
2589
2590
		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...
2591
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2592
2593
			$url = add_query_arg(
2594
				array(
2595
					'action'   => 'activate_default_modules',
2596
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2597
				),
2598
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2599
			);
2600
			wp_safe_redirect( $url );
2601
			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...
2602
		}
2603
2604
		/**
2605
		 * Fires before default modules are activated.
2606
		 *
2607
		 * @since 1.9.0
2608
		 *
2609
		 * @param string $min_version Minimum version number required to use modules.
2610
		 * @param string $max_version Maximum version number required to use modules.
2611
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2612
		 */
2613
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2614
2615
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2616
		Jetpack::restate();
2617
		Jetpack::catch_errors( true );
2618
2619
		$active = Jetpack::get_active_modules();
2620
2621
		foreach ( $modules as $module ) {
2622
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2623
				$active[] = $module;
2624
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2625
				continue;
2626
			}
2627
2628
			if ( in_array( $module, $active ) ) {
2629
				$module_info = Jetpack::get_module( $module );
2630
				if ( ! $module_info['deactivate'] ) {
2631
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2632 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2633
						$active_state = explode( ',', $active_state );
2634
					} else {
2635
						$active_state = array();
2636
					}
2637
					$active_state[] = $module;
2638
					Jetpack::state( $state, implode( ',', $active_state ) );
2639
				}
2640
				continue;
2641
			}
2642
2643
			$file = Jetpack::get_module_path( $module );
2644
			if ( ! file_exists( $file ) ) {
2645
				continue;
2646
			}
2647
2648
			// we'll override this later if the plugin can be included without fatal error
2649
			if ( $redirect ) {
2650
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2651
			}
2652
			Jetpack::state( 'error', 'module_activation_failed' );
2653
			Jetpack::state( 'module', $module );
2654
			ob_start();
2655
			require $file;
2656
			/**
2657
			 * Fires when a specific module is activated.
2658
			 *
2659
			 * @since 1.9.0
2660
			 *
2661
			 * @param string $module Module slug.
2662
			 */
2663
			do_action( 'jetpack_activate_module', $module );
2664
			$active[] = $module;
2665
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2666 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2667
				$active_state = explode( ',', $active_state );
2668
			} else {
2669
				$active_state = array();
2670
			}
2671
			$active_state[] = $module;
2672
			Jetpack::state( $state, implode( ',', $active_state ) );
2673
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2674
			ob_end_clean();
2675
		}
2676
		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...
2677
		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...
2678
		Jetpack::catch_errors( false );
2679
		/**
2680
		 * Fires when default modules are activated.
2681
		 *
2682
		 * @since 1.9.0
2683
		 *
2684
		 * @param string $min_version Minimum version number required to use modules.
2685
		 * @param string $max_version Maximum version number required to use modules.
2686
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2687
		 */
2688
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2689
	}
2690
2691
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2692
		/**
2693
		 * Fires before a module is activated.
2694
		 *
2695
		 * @since 2.6.0
2696
		 *
2697
		 * @param string $module Module slug.
2698
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2699
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2700
		 */
2701
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2702
2703
		$jetpack = Jetpack::init();
2704
2705
		if ( ! strlen( $module ) )
2706
			return false;
2707
2708
		if ( ! Jetpack::is_module( $module ) )
2709
			return false;
2710
2711
		// If it's already active, then don't do it again
2712
		$active = Jetpack::get_active_modules();
2713
		foreach ( $active as $act ) {
2714
			if ( $act == $module )
2715
				return true;
2716
		}
2717
2718
		$module_data = Jetpack::get_module( $module );
2719
2720
		if ( ! Jetpack::is_active() ) {
2721
			if ( !Jetpack::is_development_mode() )
2722
				return false;
2723
2724
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2725
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2726
				return false;
2727
		}
2728
2729
		// Check and see if the old plugin is active
2730
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2731
			// Deactivate the old plugin
2732
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2733
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2734
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2735
				Jetpack::state( 'deactivated_plugins', $module );
2736
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2737
				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...
2738
			}
2739
		}
2740
2741
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2742
		Jetpack::state( 'module', $module );
2743
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2744
2745
		Jetpack::catch_errors( true );
2746
		ob_start();
2747
		require Jetpack::get_module_path( $module );
2748
		/** This action is documented in class.jetpack.php */
2749
		do_action( 'jetpack_activate_module', $module );
2750
		$active[] = $module;
2751
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2752
		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...
2753
		Jetpack::state( 'message', 'module_activated' );
2754
		Jetpack::state( 'module', $module );
2755
		ob_end_clean();
2756
		Jetpack::catch_errors( false );
2757
2758
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2759 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2760
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2761
2762
			//Jump start is being dismissed send data to MC Stats
2763
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2764
2765
			$jetpack->do_stats( 'server_side' );
2766
		}
2767
2768
		if ( $redirect ) {
2769
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2770
		}
2771
		if ( $exit ) {
2772
			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...
2773
		}
2774
		return true;
2775
	}
2776
2777
	function activate_module_actions( $module ) {
2778
		/**
2779
		 * Fires when a module is activated.
2780
		 * The dynamic part of the filter, $module, is the module slug.
2781
		 *
2782
		 * @since 1.9.0
2783
		 *
2784
		 * @param string $module Module slug.
2785
		 */
2786
		do_action( "jetpack_activate_module_$module", $module );
2787
2788
		$this->sync->sync_all_module_options( $module );
2789
	}
2790
2791
	public static function deactivate_module( $module ) {
2792
		/**
2793
		 * Fires when a module is deactivated.
2794
		 *
2795
		 * @since 1.9.0
2796
		 *
2797
		 * @param string $module Module slug.
2798
		 */
2799
		do_action( 'jetpack_pre_deactivate_module', $module );
2800
2801
		$jetpack = Jetpack::init();
2802
2803
		$active = Jetpack::get_active_modules();
2804
		$new    = array_filter( array_diff( $active, (array) $module ) );
2805
2806
		/**
2807
		 * Fires when a module is deactivated.
2808
		 * The dynamic part of the filter, $module, is the module slug.
2809
		 *
2810
		 * @since 1.9.0
2811
		 *
2812
		 * @param string $module Module slug.
2813
		 */
2814
		do_action( "jetpack_deactivate_module_$module", $module );
2815
2816
		// A flag for Jump Start so it's not shown again.
2817 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2818
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2819
2820
			//Jump start is being dismissed send data to MC Stats
2821
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2822
2823
			$jetpack->do_stats( 'server_side' );
2824
		}
2825
2826
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2827
	}
2828
2829
	public static function enable_module_configurable( $module ) {
2830
		$module = Jetpack::get_module_slug( $module );
2831
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2832
	}
2833
2834
	public static function module_configuration_url( $module ) {
2835
		$module = Jetpack::get_module_slug( $module );
2836
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2837
	}
2838
2839
	public static function module_configuration_load( $module, $method ) {
2840
		$module = Jetpack::get_module_slug( $module );
2841
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2842
	}
2843
2844
	public static function module_configuration_head( $module, $method ) {
2845
		$module = Jetpack::get_module_slug( $module );
2846
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2847
	}
2848
2849
	public static function module_configuration_screen( $module, $method ) {
2850
		$module = Jetpack::get_module_slug( $module );
2851
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2852
	}
2853
2854
	public static function module_configuration_activation_screen( $module, $method ) {
2855
		$module = Jetpack::get_module_slug( $module );
2856
		add_action( 'display_activate_module_setting_' . $module, $method );
2857
	}
2858
2859
/* Installation */
2860
2861
	public static function bail_on_activation( $message, $deactivate = true ) {
2862
?>
2863
<!doctype html>
2864
<html>
2865
<head>
2866
<meta charset="<?php bloginfo( 'charset' ); ?>">
2867
<style>
2868
* {
2869
	text-align: center;
2870
	margin: 0;
2871
	padding: 0;
2872
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2873
}
2874
p {
2875
	margin-top: 1em;
2876
	font-size: 18px;
2877
}
2878
</style>
2879
<body>
2880
<p><?php echo esc_html( $message ); ?></p>
2881
</body>
2882
</html>
2883
<?php
2884
		if ( $deactivate ) {
2885
			$plugins = get_option( 'active_plugins' );
2886
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2887
			$update  = false;
2888
			foreach ( $plugins as $i => $plugin ) {
2889
				if ( $plugin === $jetpack ) {
2890
					$plugins[$i] = false;
2891
					$update = true;
2892
				}
2893
			}
2894
2895
			if ( $update ) {
2896
				update_option( 'active_plugins', array_filter( $plugins ) );
2897
			}
2898
		}
2899
		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...
2900
	}
2901
2902
	/**
2903
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2904
	 * @static
2905
	 */
2906
	public static function plugin_activation( $network_wide ) {
2907
		Jetpack_Options::update_option( 'activated', 1 );
2908
2909
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2910
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2911
		}
2912
2913
		if ( $network_wide )
2914
			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...
2915
2916
		Jetpack::plugin_initialize();
2917
	}
2918
	/**
2919
	 * Runs before bumping version numbers up to a new version
2920
	 * @param  (string) $version    Version:timestamp
2921
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2922
	 * @return null              [description]
2923
	 */
2924
	public static function do_version_bump( $version, $old_version ) {
2925
2926
		if ( ! $old_version ) { // For new sites
2927
			// Setting up jetpack manage
2928
			Jetpack::activate_manage();
2929
		}
2930
	}
2931
2932
	/**
2933
	 * Sets the internal version number and activation state.
2934
	 * @static
2935
	 */
2936
	public static function plugin_initialize() {
2937
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2938
			Jetpack_Options::update_option( 'activated', 2 );
2939
		}
2940
2941 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2942
			$version = $old_version = JETPACK__VERSION . ':' . time();
2943
			/** This action is documented in class.jetpack.php */
2944
			do_action( 'updating_jetpack_version', $version, false );
2945
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2946
		}
2947
2948
		Jetpack::load_modules();
2949
2950
		Jetpack_Options::delete_option( 'do_activate' );
2951
	}
2952
2953
	/**
2954
	 * Removes all connection options
2955
	 * @static
2956
	 */
2957
	public static function plugin_deactivation( ) {
2958
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2959
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2960
			Jetpack_Network::init()->deactivate();
2961
		} else {
2962
			Jetpack::disconnect( false );
2963
			//Jetpack_Heartbeat::init()->deactivate();
2964
		}
2965
	}
2966
2967
	/**
2968
	 * Disconnects from the Jetpack servers.
2969
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2970
	 * @static
2971
	 */
2972
	public static function disconnect( $update_activated_state = true ) {
2973
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2974
		Jetpack::clean_nonces( true );
2975
2976
		Jetpack::load_xml_rpc_client();
2977
		$xml = new Jetpack_IXR_Client();
2978
		$xml->query( 'jetpack.deregister' );
2979
2980
		Jetpack_Options::delete_option(
2981
			array(
2982
				'register',
2983
				'blog_token',
2984
				'user_token',
2985
				'user_tokens',
2986
				'master_user',
2987
				'time_diff',
2988
				'fallback_no_verify_ssl_certs',
2989
			)
2990
		);
2991
2992
		if ( $update_activated_state ) {
2993
			Jetpack_Options::update_option( 'activated', 4 );
2994
		}
2995
2996
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2997
		// Check then record unique disconnection if site has never been disconnected previously
2998
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2999
			$jetpack_unique_connection['disconnected'] = 1;
3000
		}
3001
		else {
3002
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3003
				//track unique disconnect
3004
				$jetpack = Jetpack::init();
3005
3006
				$jetpack->stat( 'connections', 'unique-disconnect' );
3007
				$jetpack->do_stats( 'server_side' );
3008
			}
3009
			// increment number of times disconnected
3010
			$jetpack_unique_connection['disconnected'] += 1;
3011
		}
3012
3013
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3014
3015
		// Disable the Heartbeat cron
3016
		Jetpack_Heartbeat::init()->deactivate();
3017
	}
3018
3019
	/**
3020
	 * Unlinks the current user from the linked WordPress.com user
3021
	 */
3022
	public static function unlink_user( $user_id = null ) {
3023
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3024
			return false;
3025
3026
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3027
3028
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3029
			return false;
3030
3031
		if ( ! isset( $tokens[ $user_id ] ) )
3032
			return false;
3033
3034
		Jetpack::load_xml_rpc_client();
3035
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3036
		$xml->query( 'jetpack.unlink_user', $user_id );
3037
3038
		unset( $tokens[ $user_id ] );
3039
3040
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3041
3042
		return true;
3043
	}
3044
3045
	/**
3046
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3047
	 */
3048
	public static function try_registration() {
3049
		// Let's get some testing in beta versions and such.
3050
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3051
			// Before attempting to connect, let's make sure that the domains are viable.
3052
			$domains_to_check = array_unique( array(
3053
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3054
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3055
			) );
3056
			foreach ( $domains_to_check as $domain ) {
3057
				$result = Jetpack_Data::is_usable_domain( $domain );
3058
				if ( is_wp_error( $result ) ) {
3059
					return $result;
3060
				}
3061
			}
3062
		}
3063
3064
		$result = Jetpack::register();
3065
3066
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3067
		if ( ! $result || is_wp_error( $result ) ) {
3068
			return $result;
3069
		} else {
3070
			return true;
3071
		}
3072
	}
3073
3074
	/**
3075
	 * Tracking an internal event log. Try not to put too much chaff in here.
3076
	 *
3077
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3078
	 */
3079
	public static function log( $code, $data = null ) {
3080
		// only grab the latest 200 entries
3081
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3082
3083
		// Append our event to the log
3084
		$log_entry = array(
3085
			'time'    => time(),
3086
			'user_id' => get_current_user_id(),
3087
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3088
			'code'    => $code,
3089
		);
3090
		// Don't bother storing it unless we've got some.
3091
		if ( ! is_null( $data ) ) {
3092
			$log_entry['data'] = $data;
3093
		}
3094
		$log[] = $log_entry;
3095
3096
		// Try add_option first, to make sure it's not autoloaded.
3097
		// @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...
3098
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3099
			Jetpack_Options::update_option( 'log', $log );
3100
		}
3101
3102
		/**
3103
		 * Fires when Jetpack logs an internal event.
3104
		 *
3105
		 * @since 3.0.0
3106
		 *
3107
		 * @param array $log_entry {
3108
		 *	Array of details about the log entry.
3109
		 *
3110
		 *	@param string time Time of the event.
3111
		 *	@param int user_id ID of the user who trigerred the event.
3112
		 *	@param int blog_id Jetpack Blog ID.
3113
		 *	@param string code Unique name for the event.
3114
		 *	@param string data Data about the event.
3115
		 * }
3116
		 */
3117
		do_action( 'jetpack_log_entry', $log_entry );
3118
	}
3119
3120
	/**
3121
	 * Get the internal event log.
3122
	 *
3123
	 * @param $event (string) - only return the specific log events
3124
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3125
	 *
3126
	 * @return array of log events || WP_Error for invalid params
3127
	 */
3128
	public static function get_log( $event = false, $num = false ) {
3129
		if ( $event && ! is_string( $event ) ) {
3130
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3131
		}
3132
3133
		if ( $num && ! is_numeric( $num ) ) {
3134
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3135
		}
3136
3137
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3138
3139
		// If nothing set - act as it did before, otherwise let's start customizing the output
3140
		if ( ! $num && ! $event ) {
3141
			return $entire_log;
3142
		} else {
3143
			$entire_log = array_reverse( $entire_log );
3144
		}
3145
3146
		$custom_log_output = array();
3147
3148
		if ( $event ) {
3149
			foreach ( $entire_log as $log_event ) {
3150
				if ( $event == $log_event[ 'code' ] ) {
3151
					$custom_log_output[] = $log_event;
3152
				}
3153
			}
3154
		} else {
3155
			$custom_log_output = $entire_log;
3156
		}
3157
3158
		if ( $num ) {
3159
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3160
		}
3161
3162
		return $custom_log_output;
3163
	}
3164
3165
	/**
3166
	 * Log modification of important settings.
3167
	 */
3168
	public static function log_settings_change( $option, $old_value, $value ) {
3169
		switch( $option ) {
3170
			case 'jetpack_sync_non_public_post_stati':
3171
				self::log( $option, $value );
3172
				break;
3173
		}
3174
	}
3175
3176
	/**
3177
	 * Return stat data for WPCOM sync
3178
	 */
3179
	function get_stat_data() {
3180
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3181
		$additional_data = $this->get_additional_stat_data();
3182
3183
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3184
	}
3185
3186
	/**
3187
	 * Get additional stat data to sync to WPCOM
3188
	 */
3189
	function get_additional_stat_data( $prefix = '' ) {
3190
		$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...
3191
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3192
		$return["{$prefix}users"]          = count_users();
3193
		$return["{$prefix}site-count"]     = 0;
3194
		if ( function_exists( 'get_blog_count' ) ) {
3195
			$return["{$prefix}site-count"] = get_blog_count();
3196
		}
3197
		return $return;
3198
	}
3199
3200
	/* Admin Pages */
3201
3202
	function admin_init() {
3203
		// If the plugin is not connected, display a connect message.
3204
		if (
3205
			// the plugin was auto-activated and needs its candy
3206
			Jetpack_Options::get_option( 'do_activate' )
3207
		||
3208
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3209
			! Jetpack_Options::get_option( 'activated' )
3210
		) {
3211
			Jetpack::plugin_initialize();
3212
		}
3213
3214
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3215
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3216
				// Show connect notice on dashboard and plugins pages
3217
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3218
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3219
			}
3220
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3221
			// Upgrade: 1.1 -> 1.1.1
3222
			// Check and see if host can verify the Jetpack servers' SSL certificate
3223
			$args = array();
3224
			Jetpack_Client::_wp_remote_request(
3225
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3226
				$args,
3227
				true
3228
			);
3229
		} else {
3230
			// Show the notice on the Dashboard only for now
3231
3232
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3233
3234
			// Identity crisis notices
3235
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3236
		}
3237
3238
		// If the plugin has just been disconnected from WP.com, show the survey notice
3239
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3240
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3241
		}
3242
3243
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3244
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3245
		}
3246
3247
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3248
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3249
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3250
3251
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3252
			// Artificially throw errors in certain whitelisted cases during plugin activation
3253
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3254
3255
			// Kick off synchronization of user role when it changes
3256
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3257
		}
3258
3259
		// Jetpack Manage Activation Screen from .com
3260
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3261
	}
3262
3263
	function admin_body_class( $admin_body_class = '' ) {
3264
		$classes = explode( ' ', trim( $admin_body_class ) );
3265
3266
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3267
3268
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3269
		return " $admin_body_class ";
3270
	}
3271
3272
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3273
		return $admin_body_class . ' jetpack-pagestyles ';
3274
	}
3275
3276
	function prepare_connect_notice() {
3277
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3278
3279
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3280
3281
		if ( Jetpack::state( 'network_nag' ) )
3282
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3283
	}
3284
	/**
3285
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3286
	 *
3287
	 * @return null
3288
	 */
3289
	function prepare_manage_jetpack_notice() {
3290
3291
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3292
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3293
	}
3294
3295
	function manage_activate_screen() {
3296
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3297
	}
3298
	/**
3299
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3300
	 * This function artificially throws errors for such cases (whitelisted).
3301
	 *
3302
	 * @param string $plugin The activated plugin.
3303
	 */
3304
	function throw_error_on_activate_plugin( $plugin ) {
3305
		$active_modules = Jetpack::get_active_modules();
3306
3307
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3308
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3309
			$throw = false;
3310
3311
			// Try and make sure it really was the stats plugin
3312
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3313
				if ( 'stats.php' == basename( $plugin ) ) {
3314
					$throw = true;
3315
				}
3316
			} else {
3317
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3318
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3319
					$throw = true;
3320
				}
3321
			}
3322
3323
			if ( $throw ) {
3324
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3325
			}
3326
		}
3327
	}
3328
3329
	function intercept_plugin_error_scrape_init() {
3330
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3331
	}
3332
3333
	function intercept_plugin_error_scrape( $action, $result ) {
3334
		if ( ! $result ) {
3335
			return;
3336
		}
3337
3338
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3339
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3340
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3341
			}
3342
		}
3343
	}
3344
3345
	function add_remote_request_handlers() {
3346
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3347
	}
3348
3349
	function remote_request_handlers() {
3350
		switch ( current_filter() ) {
3351
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3352
			$response = $this->upload_handler();
3353
			break;
3354
		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...
3355
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3356
			break;
3357
		}
3358
3359
		if ( ! $response ) {
3360
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3361
		}
3362
3363
		if ( is_wp_error( $response ) ) {
3364
			$status_code       = $response->get_error_data();
3365
			$error             = $response->get_error_code();
3366
			$error_description = $response->get_error_message();
3367
3368
			if ( ! is_int( $status_code ) ) {
3369
				$status_code = 400;
3370
			}
3371
3372
			status_header( $status_code );
3373
			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...
3374
		}
3375
3376
		status_header( 200 );
3377
		if ( true === $response ) {
3378
			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...
3379
		}
3380
3381
		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...
3382
	}
3383
3384
	function upload_handler() {
3385
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3386
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3387
		}
3388
3389
		$user = wp_authenticate( '', '' );
3390
		if ( ! $user || is_wp_error( $user ) ) {
3391
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3392
		}
3393
3394
		wp_set_current_user( $user->ID );
3395
3396
		if ( ! current_user_can( 'upload_files' ) ) {
3397
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3398
		}
3399
3400
		if ( empty( $_FILES ) ) {
3401
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3402
		}
3403
3404
		foreach ( array_keys( $_FILES ) as $files_key ) {
3405
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3406
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3407
			}
3408
		}
3409
3410
		$media_keys = array_keys( $_FILES['media'] );
3411
3412
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3413
		if ( ! $token || is_wp_error( $token ) ) {
3414
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3415
		}
3416
3417
		$uploaded_files = array();
3418
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3419
		unset( $GLOBALS['post'] );
3420
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3421
			$file = array();
3422
			foreach ( $media_keys as $media_key ) {
3423
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3424
			}
3425
3426
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3427
3428
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3429
			if ( $hmac_provided !== $hmac_file ) {
3430
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3431
				continue;
3432
			}
3433
3434
			$_FILES['.jetpack.upload.'] = $file;
3435
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3436
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3437
				$post_id = 0;
3438
			}
3439
			$attachment_id = media_handle_upload(
3440
				'.jetpack.upload.',
3441
				$post_id,
3442
				array(),
3443
				array(
3444
					'action' => 'jetpack_upload_file',
3445
				)
3446
			);
3447
3448
			if ( ! $attachment_id ) {
3449
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3450
			} elseif ( is_wp_error( $attachment_id ) ) {
3451
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3452
			} else {
3453
				$attachment = get_post( $attachment_id );
3454
				$uploaded_files[$index] = (object) array(
3455
					'id'   => (string) $attachment_id,
3456
					'file' => $attachment->post_title,
3457
					'url'  => wp_get_attachment_url( $attachment_id ),
3458
					'type' => $attachment->post_mime_type,
3459
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3460
				);
3461
			}
3462
		}
3463
		if ( ! is_null( $global_post ) ) {
3464
			$GLOBALS['post'] = $global_post;
3465
		}
3466
3467
		return $uploaded_files;
3468
	}
3469
3470
	/**
3471
	 * Add help to the Jetpack page
3472
	 *
3473
	 * @since Jetpack (1.2.3)
3474
	 * @return false if not the Jetpack page
3475
	 */
3476
	function admin_help() {
3477
		$current_screen = get_current_screen();
3478
3479
		// Overview
3480
		$current_screen->add_help_tab(
3481
			array(
3482
				'id'		=> 'home',
3483
				'title'		=> __( 'Home', 'jetpack' ),
3484
				'content'	=>
3485
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3486
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3487
					'<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>',
3488
			)
3489
		);
3490
3491
		// Screen Content
3492
		if ( current_user_can( 'manage_options' ) ) {
3493
			$current_screen->add_help_tab(
3494
				array(
3495
					'id'		=> 'settings',
3496
					'title'		=> __( 'Settings', 'jetpack' ),
3497
					'content'	=>
3498
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3499
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3500
						'<ol>' .
3501
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3502
							'<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>' .
3503
						'</ol>' .
3504
						'<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>'
3505
				)
3506
			);
3507
		}
3508
3509
		// Help Sidebar
3510
		$current_screen->set_help_sidebar(
3511
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3512
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3513
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3514
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3515
		);
3516
	}
3517
3518
	function admin_menu_css() {
3519
		wp_enqueue_style( 'jetpack-icons' );
3520
	}
3521
3522
	function admin_menu_order() {
3523
		return true;
3524
	}
3525
3526 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3527
		$jp_menu_order = array();
3528
3529
		foreach ( $menu_order as $index => $item ) {
3530
			if ( $item != 'jetpack' ) {
3531
				$jp_menu_order[] = $item;
3532
			}
3533
3534
			if ( $index == 0 ) {
3535
				$jp_menu_order[] = 'jetpack';
3536
			}
3537
		}
3538
3539
		return $jp_menu_order;
3540
	}
3541
3542
	function admin_head() {
3543 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3544
			/** This action is documented in class.jetpack-admin-page.php */
3545
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3546
	}
3547
3548
	function admin_banner_styles() {
3549
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3550
3551
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3552
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3553
		wp_style_add_data( 'jetpack', 'suffix', $min );
3554
	}
3555
3556
	function admin_scripts() {
3557
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3558
		wp_localize_script(
3559
			'jetpack-js',
3560
			'jetpackL10n',
3561
			array(
3562
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3563
				'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?",
3564
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3565
			)
3566
		);
3567
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3568
	}
3569
3570
	function plugin_action_links( $actions ) {
3571
3572
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3573
3574
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3575
			return array_merge(
3576
				$jetpack_home,
3577
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3578
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3579
				$actions
3580
				);
3581
			}
3582
3583
		return array_merge( $jetpack_home, $actions );
3584
	}
3585
3586
	function admin_connect_notice() {
3587
		// Don't show the connect notice anywhere but the plugins.php after activating
3588
		$current = get_current_screen();
3589
		if ( 'plugins' !== $current->parent_base )
3590
			return;
3591
3592
		if ( ! current_user_can( 'jetpack_connect' ) )
3593
			return;
3594
3595
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3596
		?>
3597
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3598
			<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>
3599
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3600
				<div class="jp-banner__content is-connection">
3601
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3602
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3603
				</div>
3604
				<div class="jp-banner__action-container is-connection">
3605
						<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>
3606
				</div>
3607 View Code Duplication
			<?php else : ?>
3608
				<div class="jp-banner__content">
3609
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3610
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3611
				</div>
3612
				<div class="jp-banner__action-container">
3613
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3614
				</div>
3615
			<?php endif; ?>
3616
		</div>
3617
3618
		<?php
3619
	}
3620
3621
	/**
3622
	 * This is the first banner
3623
	 * It should be visible only to user that can update the option
3624
	 * Are not connected
3625
	 *
3626
	 * @return null
3627
	 */
3628
	function admin_jetpack_manage_notice() {
3629
		$screen = get_current_screen();
3630
3631
		// Don't show the connect notice on the jetpack settings page.
3632
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3633
			return;
3634
3635
		// Only show it if don't have the managment option set.
3636
		// And not dismissed it already.
3637
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3638
			return;
3639
		}
3640
3641
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3642
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3643
		/**
3644
		 * I think it would be great to have different wordsing depending on where you are
3645
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3646
		 * etc..
3647
		 */
3648
3649
		?>
3650
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3651
			<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>
3652
			<div class="jp-banner__content">
3653
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3654
				<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>
3655
			</div>
3656
			<div class="jp-banner__action-container is-opt-in">
3657
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3658
			</div>
3659
		</div>
3660
		<?php
3661
	}
3662
3663
	/**
3664
	 * Returns the url that the user clicks to remove the notice for the big banner
3665
	 * @return (string)
3666
	 */
3667
	function opt_out_jetpack_manage_url() {
3668
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3669
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3670
	}
3671
	/**
3672
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3673
	 * @return (string)
3674
	 */
3675
	function opt_in_jetpack_manage_url() {
3676
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3677
	}
3678
3679
	function opt_in_jetpack_manage_notice() {
3680
		?>
3681
		<div class="wrap">
3682
			<div id="message" class="jetpack-message is-opt-in">
3683
				<?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' ); ?>
3684
			</div>
3685
		</div>
3686
		<?php
3687
3688
	}
3689
	/**
3690
	 * Determines whether to show the notice of not true = display notice
3691
	 * @return (bool)
3692
	 */
3693
	function can_display_jetpack_manage_notice() {
3694
		// never display the notice to users that can't do anything about it anyways
3695
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3696
			return false;
3697
3698
		// don't display if we are in development more
3699
		if( Jetpack::is_development_mode() ) {
3700
			return false;
3701
		}
3702
		// don't display if the site is private
3703
		if(  ! Jetpack_Options::get_option( 'public' ) )
3704
			return false;
3705
3706
		/**
3707
		 * Should the Jetpack Remote Site Management notice be displayed.
3708
		 *
3709
		 * @since 3.3.0
3710
		 *
3711
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3712
		 */
3713
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3714
	}
3715
3716
	function network_connect_notice() {
3717
		?>
3718
		<div id="message" class="updated jetpack-message">
3719
			<div class="squeezer">
3720
				<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>
3721
			</div>
3722
		</div>
3723
		<?php
3724
	}
3725
3726
	public static function jetpack_comment_notice() {
3727
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3728
			return '';
3729
		}
3730
3731
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3732
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3733
3734
		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...
3735
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3736
				return '';
3737
			}
3738
		}
3739
3740
		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...
3741
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3742
				return '';
3743
			}
3744
		}
3745
3746
		return '<br /><br />' . sprintf(
3747
			__( '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' ),
3748
			wp_nonce_url(
3749
				Jetpack::admin_url(
3750
					array(
3751
						'page'   => 'jetpack',
3752
						'action' => 'activate',
3753
						'module' => 'comments',
3754
					)
3755
				),
3756
				'jetpack_activate-comments'
3757
			),
3758
			__( 'click here', 'jetpack' )
3759
		);
3760
	}
3761
3762
	/**
3763
	 * Show the survey link when the user has just disconnected Jetpack.
3764
	 */
3765
	function disconnect_survey_notice() {
3766
		?>
3767
		<div class="wrap">
3768
			<div id="message" class="jetpack-message stay-visible">
3769
				<div class="squeezer">
3770
					<h2>
3771
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3772
						<br />
3773
						<?php echo sprintf(
3774
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3775
							'https://jetpack.com/survey-disconnected/',
3776
							'_blank'
3777
						); ?>
3778
					</h2>
3779
				</div>
3780
			</div>
3781
		</div>
3782
		<?php
3783
	}
3784
3785
	/*
3786
	 * Registration flow:
3787
	 * 1 - ::admin_page_load() action=register
3788
	 * 2 - ::try_registration()
3789
	 * 3 - ::register()
3790
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3791
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3792
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3793
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3794
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3795
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3796
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3797
	 *       jetpack_id, jetpack_secret, jetpack_public
3798
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3799
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3800
	 * 5 - user logs in with WP.com account
3801
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3802
	 *		- Jetpack_Client_Server::authorize()
3803
	 *		- Jetpack_Client_Server::get_token()
3804
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3805
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3806
	 *			- which responds with access_token, token_type, scope
3807
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3808
	 *		- Jetpack::activate_default_modules()
3809
	 *     		- Deactivates deprecated plugins
3810
	 *     		- Activates all default modules
3811
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3812
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3813
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3814
	 *     Done!
3815
	 */
3816
3817
	/**
3818
	 * Handles the page load events for the Jetpack admin page
3819
	 */
3820
	function admin_page_load() {
3821
		$error = false;
3822
3823
		// Make sure we have the right body class to hook stylings for subpages off of.
3824
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3825
3826
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3827
			// Should only be used in intermediate redirects to preserve state across redirects
3828
			Jetpack::restate();
3829
		}
3830
3831
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3832
			// User clicked in the iframe to link their accounts
3833
			if ( ! Jetpack::is_user_connected() ) {
3834
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3835
				if ( isset( $_GET['notes_iframe'] ) )
3836
					$connect_url .= '&notes_iframe';
3837
				wp_redirect( $connect_url );
3838
				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...
3839
			} else {
3840
				Jetpack::state( 'message', 'already_authorized' );
3841
				wp_safe_redirect( Jetpack::admin_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
			}
3844
		}
3845
3846
3847
		if ( isset( $_GET['action'] ) ) {
3848
			switch ( $_GET['action'] ) {
3849
			case 'authorize':
3850
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3851
					Jetpack::state( 'message', 'already_authorized' );
3852
					wp_safe_redirect( Jetpack::admin_url() );
3853
					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...
3854
				}
3855
				Jetpack::log( 'authorize' );
3856
				$client_server = new Jetpack_Client_Server;
3857
				$client_server->client_authorize();
3858
				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...
3859
			case 'register' :
3860
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3861
					$error = 'cheatin';
3862
					break;
3863
				}
3864
				check_admin_referer( 'jetpack-register' );
3865
				Jetpack::log( 'register' );
3866
				Jetpack::maybe_set_version_option();
3867
				$registered = Jetpack::try_registration();
3868
				if ( is_wp_error( $registered ) ) {
3869
					$error = $registered->get_error_code();
3870
					Jetpack::state( 'error_description', $registered->get_error_message() );
3871
					break;
3872
				}
3873
3874
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3875
3876
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3877
				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...
3878
			case 'activate' :
3879
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3880
					$error = 'cheatin';
3881
					break;
3882
				}
3883
3884
				$module = stripslashes( $_GET['module'] );
3885
				check_admin_referer( "jetpack_activate-$module" );
3886
				Jetpack::log( 'activate', $module );
3887
				Jetpack::activate_module( $module );
3888
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3889
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3890
				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...
3891
			case 'activate_default_modules' :
3892
				check_admin_referer( 'activate_default_modules' );
3893
				Jetpack::log( 'activate_default_modules' );
3894
				Jetpack::restate();
3895
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3896
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3897
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3898
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3899
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3900
				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...
3901
			case 'disconnect' :
3902
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3903
					$error = 'cheatin';
3904
					break;
3905
				}
3906
3907
				check_admin_referer( 'jetpack-disconnect' );
3908
				Jetpack::log( 'disconnect' );
3909
				Jetpack::disconnect();
3910
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3911
				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...
3912
			case 'reconnect' :
3913
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3914
					$error = 'cheatin';
3915
					break;
3916
				}
3917
3918
				check_admin_referer( 'jetpack-reconnect' );
3919
				Jetpack::log( 'reconnect' );
3920
				$this->disconnect();
3921
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3922
				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...
3923 View Code Duplication
			case 'deactivate' :
3924
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3925
					$error = 'cheatin';
3926
					break;
3927
				}
3928
3929
				$modules = stripslashes( $_GET['module'] );
3930
				check_admin_referer( "jetpack_deactivate-$modules" );
3931
				foreach ( explode( ',', $modules ) as $module ) {
3932
					Jetpack::log( 'deactivate', $module );
3933
					Jetpack::deactivate_module( $module );
3934
					Jetpack::state( 'message', 'module_deactivated' );
3935
				}
3936
				Jetpack::state( 'module', $modules );
3937
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3938
				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...
3939
			case 'unlink' :
3940
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3941
				check_admin_referer( 'jetpack-unlink' );
3942
				Jetpack::log( 'unlink' );
3943
				$this->unlink_user();
3944
				Jetpack::state( 'message', 'unlinked' );
3945
				if ( 'sub-unlink' == $redirect ) {
3946
					wp_safe_redirect( admin_url() );
3947
				} else {
3948
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3949
				}
3950
				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...
3951
			default:
3952
				/**
3953
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3954
				 *
3955
				 * @since 2.6.0
3956
				 *
3957
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3958
				 */
3959
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3960
			}
3961
		}
3962
3963
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3964
			self::activate_new_modules( true );
3965
		}
3966
3967
		switch ( $error ) {
3968
		case 'cheatin' :
3969
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3970
			break;
3971
		case 'access_denied' :
3972
			$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>';
3973
			break;
3974
		case 'wrong_state' :
3975
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3976
			break;
3977
		case 'invalid_client' :
3978
			// @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...
3979
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3980
			break;
3981
		case 'invalid_grant' :
3982
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3983
			break;
3984
		case 'site_inaccessible' :
3985
		case 'site_requires_authorization' :
3986
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3987
			break;
3988
		case 'module_activation_failed' :
3989
			$module = Jetpack::state( 'module' );
3990
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3991
				$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'] );
3992
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3993
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3994
				}
3995
			} else {
3996
				$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' );
3997
			}
3998
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
3999
				$this->error .= "<br />\n";
4000
				$this->error .= $php_errors;
4001
			}
4002
			break;
4003
		case 'master_user_required' :
4004
			$module = Jetpack::state( 'module' );
4005
			$module_name = '';
4006
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4007
				$module_name = $mod['name'];
4008
			}
4009
4010
			$master_user = Jetpack_Options::get_option( 'master_user' );
4011
			$master_userdata = get_userdata( $master_user ) ;
4012
			if ( $master_userdata ) {
4013
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
4014
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
4015
				} else {
4016
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
4017
				}
4018
				$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 ) );
4019
4020
			} else {
4021
				$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 );
4022
			}
4023
			break;
4024
		case 'not_public' :
4025
			$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' );
4026
			break;
4027
		case 'wpcom_408' :
4028
		case 'wpcom_5??' :
4029
		case 'wpcom_bad_response' :
4030
		case 'wpcom_outage' :
4031
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
4032
			break;
4033
		case 'register_http_request_failed' :
4034
		case 'token_http_request_failed' :
4035
			$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>" );
4036
			break;
4037
		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...
4038
			if ( empty( $error ) ) {
4039
				break;
4040
			}
4041
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
4042
			// no break: fall through
4043
		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...
4044
		case 'no_cap' :
4045
		case 'no_code' :
4046
		case 'no_state' :
4047
		case 'invalid_state' :
4048
		case 'invalid_request' :
4049
		case 'invalid_scope' :
4050
		case 'unsupported_response_type' :
4051
		case 'invalid_token' :
4052
		case 'no_token' :
4053
		case 'missing_secrets' :
4054
		case 'home_missing' :
4055
		case 'siteurl_missing' :
4056
		case 'gmt_offset_missing' :
4057
		case 'site_name_missing' :
4058
		case 'secret_1_missing' :
4059
		case 'secret_2_missing' :
4060
		case 'site_lang_missing' :
4061
		case 'home_malformed' :
4062
		case 'siteurl_malformed' :
4063
		case 'gmt_offset_malformed' :
4064
		case 'timezone_string_malformed' :
4065
		case 'site_name_malformed' :
4066
		case 'secret_1_malformed' :
4067
		case 'secret_2_malformed' :
4068
		case 'site_lang_malformed' :
4069
		case 'secrets_mismatch' :
4070
		case 'verify_secret_1_missing' :
4071
		case 'verify_secret_1_malformed' :
4072
		case 'verify_secrets_missing' :
4073
		case 'verify_secrets_mismatch' :
4074
			$error = esc_html( $error );
4075
			$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>" );
4076
			if ( ! Jetpack::is_active() ) {
4077
				$this->error .= '<br />';
4078
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4079
			}
4080
			break;
4081
		}
4082
4083
		$message_code = Jetpack::state( 'message' );
4084
4085
		$active_state = Jetpack::state( 'activated_modules' );
4086
		if ( ! empty( $active_state ) ) {
4087
			$available    = Jetpack::get_available_modules();
4088
			$active_state = explode( ',', $active_state );
4089
			$active_state = array_intersect( $active_state, $available );
4090
			if ( count( $active_state ) ) {
4091
				foreach ( $active_state as $mod ) {
4092
					$this->stat( 'module-activated', $mod );
4093
				}
4094
			} else {
4095
				$active_state = false;
4096
			}
4097
		}
4098
		if( Jetpack::state( 'optin-manage' ) ) {
4099
			$activated_manage = $message_code;
4100
			$message_code = 'jetpack-manage';
4101
4102
		}
4103
		switch ( $message_code ) {
4104
		case 'modules_activated' :
4105
			$this->message = sprintf(
4106
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4107
				JETPACK__VERSION
4108
			);
4109
4110
			if ( $active_state ) {
4111
				$titles = array();
4112 View Code Duplication
				foreach ( $active_state as $mod ) {
4113
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4114
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4115
					}
4116
				}
4117
				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...
4118
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4119
				}
4120
			}
4121
4122
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4123
				$titles = array();
4124 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4125
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4126
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4127
					}
4128
				}
4129
				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...
4130
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4131
				}
4132
			}
4133
4134
			$this->message .= Jetpack::jetpack_comment_notice();
4135
			break;
4136
		case 'jetpack-manage':
4137
			$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>';
4138
			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...
4139
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4140
			}
4141
			break;
4142
		case 'module_activated' :
4143
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4144
				$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'] );
4145
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4146
			}
4147
			break;
4148
4149
		case 'module_deactivated' :
4150
			$modules = Jetpack::state( 'module' );
4151
			if ( ! $modules ) {
4152
				break;
4153
			}
4154
4155
			$module_names = array();
4156
			foreach ( explode( ',', $modules ) as $module_slug ) {
4157
				$module = Jetpack::get_module( $module_slug );
4158
				if ( $module ) {
4159
					$module_names[] = $module['name'];
4160
				}
4161
4162
				$this->stat( 'module-deactivated', $module_slug );
4163
			}
4164
4165
			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...
4166
				break;
4167
			}
4168
4169
			$this->message = wp_sprintf(
4170
				_nx(
4171
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4172
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4173
					count( $module_names ),
4174
					'%l = list of Jetpack module/feature names',
4175
					'jetpack'
4176
				),
4177
				$module_names
4178
			);
4179
			break;
4180
4181
		case 'module_configured' :
4182
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4183
			break;
4184
4185
		case 'already_authorized' :
4186
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4187
			break;
4188
4189
		case 'authorized' :
4190
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4191
			$this->message .= Jetpack::jetpack_comment_notice();
4192
			break;
4193
4194
		case 'linked' :
4195
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4196
			$this->message .= Jetpack::jetpack_comment_notice();
4197
			break;
4198
4199
		case 'unlinked' :
4200
			$user = wp_get_current_user();
4201
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4202
			break;
4203
4204
		case 'switch_master' :
4205
			global $current_user;
4206
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4207
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4208
			if ( $is_master_user ) {
4209
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4210
			} else {
4211
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4212
			}
4213
			break;
4214
		}
4215
4216
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4217
4218
		if ( ! empty( $deactivated_plugins ) ) {
4219
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4220
			$deactivated_titles  = array();
4221
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4222
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4223
					continue;
4224
				}
4225
4226
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4227
			}
4228
4229
			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...
4230
				if ( $this->message ) {
4231
					$this->message .= "<br /><br />\n";
4232
				}
4233
4234
				$this->message .= wp_sprintf(
4235
					_n(
4236
						'Jetpack contains the most recent version of the old %l plugin.',
4237
						'Jetpack contains the most recent versions of the old %l plugins.',
4238
						count( $deactivated_titles ),
4239
						'jetpack'
4240
					),
4241
					$deactivated_titles
4242
				);
4243
4244
				$this->message .= "<br />\n";
4245
4246
				$this->message .= _n(
4247
					'The old version has been deactivated and can be removed from your site.',
4248
					'The old versions have been deactivated and can be removed from your site.',
4249
					count( $deactivated_titles ),
4250
					'jetpack'
4251
				);
4252
			}
4253
		}
4254
4255
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4256
4257
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4258
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4259
		}
4260
4261 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4262
			/**
4263
			 * Fires when a module configuration page is loaded.
4264
			 * The dynamic part of the hook is the configure parameter from the URL.
4265
			 *
4266
			 * @since 1.1.0
4267
			 */
4268
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4269
		}
4270
4271
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4272
	}
4273
4274
	function admin_notices() {
4275
4276
		if ( $this->error ) {
4277
?>
4278
<div id="message" class="jetpack-message jetpack-err">
4279
	<div class="squeezer">
4280
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4281
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4282
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4283
<?php	endif; ?>
4284
	</div>
4285
</div>
4286
<?php
4287
		}
4288
4289
		if ( $this->message ) {
4290
?>
4291
<div id="message" class="jetpack-message">
4292
	<div class="squeezer">
4293
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4294
	</div>
4295
</div>
4296
<?php
4297
		}
4298
4299
		if ( $this->privacy_checks ) :
4300
			$module_names = $module_slugs = array();
4301
4302
			$privacy_checks = explode( ',', $this->privacy_checks );
4303
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4304
			foreach ( $privacy_checks as $module_slug ) {
4305
				$module = Jetpack::get_module( $module_slug );
4306
				if ( ! $module ) {
4307
					continue;
4308
				}
4309
4310
				$module_slugs[] = $module_slug;
4311
				$module_names[] = "<strong>{$module['name']}</strong>";
4312
			}
4313
4314
			$module_slugs = join( ',', $module_slugs );
4315
?>
4316
<div id="message" class="jetpack-message jetpack-err">
4317
	<div class="squeezer">
4318
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4319
		<p><?php
4320
			echo wp_kses(
4321
				wptexturize(
4322
					wp_sprintf(
4323
						_nx(
4324
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4325
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4326
							count( $privacy_checks ),
4327
							'%l = list of Jetpack module/feature names',
4328
							'jetpack'
4329
						),
4330
						$module_names
4331
					)
4332
				),
4333
				array( 'strong' => true )
4334
			);
4335
4336
			echo "\n<br />\n";
4337
4338
			echo wp_kses(
4339
				sprintf(
4340
					_nx(
4341
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4342
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4343
						count( $privacy_checks ),
4344
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4345
						'jetpack'
4346
					),
4347
					wp_nonce_url(
4348
						Jetpack::admin_url(
4349
							array(
4350
								'page'   => 'jetpack',
4351
								'action' => 'deactivate',
4352
								'module' => urlencode( $module_slugs ),
4353
							)
4354
						),
4355
						"jetpack_deactivate-$module_slugs"
4356
					),
4357
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4358
				),
4359
				array( 'a' => array( 'href' => true, 'title' => true ) )
4360
			);
4361
		?></p>
4362
	</div>
4363
</div>
4364
<?php endif;
4365
	// only display the notice if the other stuff is not there
4366
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4367
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4368
			$this->opt_in_jetpack_manage_notice();
4369
		}
4370
	}
4371
4372
	/**
4373
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4374
	 */
4375
	function stat( $group, $detail ) {
4376
		if ( ! isset( $this->stats[ $group ] ) )
4377
			$this->stats[ $group ] = array();
4378
		$this->stats[ $group ][] = $detail;
4379
	}
4380
4381
	/**
4382
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4383
	 */
4384
	function do_stats( $method = '' ) {
4385
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4386
			foreach ( $this->stats as $group => $stats ) {
4387
				if ( is_array( $stats ) && count( $stats ) ) {
4388
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4389
					if ( 'server_side' === $method ) {
4390
						self::do_server_side_stat( $args );
4391
					} else {
4392
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4393
					}
4394
				}
4395
				unset( $this->stats[ $group ] );
4396
			}
4397
		}
4398
	}
4399
4400
	/**
4401
	 * Runs stats code for a one-off, server-side.
4402
	 *
4403
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4404
	 *
4405
	 * @return bool If it worked.
4406
	 */
4407
	static function do_server_side_stat( $args ) {
4408
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4409
		if ( is_wp_error( $response ) )
4410
			return false;
4411
4412
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4413
			return false;
4414
4415
		return true;
4416
	}
4417
4418
	/**
4419
	 * Builds the stats url.
4420
	 *
4421
	 * @param $args array|string The arguments to append to the URL.
4422
	 *
4423
	 * @return string The URL to be pinged.
4424
	 */
4425
	static function build_stats_url( $args ) {
4426
		$defaults = array(
4427
			'v'    => 'wpcom2',
4428
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4429
		);
4430
		$args     = wp_parse_args( $args, $defaults );
4431
		/**
4432
		 * Filter the URL used as the Stats tracking pixel.
4433
		 *
4434
		 * @since 2.3.2
4435
		 *
4436
		 * @param string $url Base URL used as the Stats tracking pixel.
4437
		 */
4438
		$base_url = apply_filters(
4439
			'jetpack_stats_base_url',
4440
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4441
		);
4442
		$url      = add_query_arg( $args, $base_url );
4443
		return $url;
4444
	}
4445
4446
	function translate_current_user_to_role() {
4447
		foreach ( $this->capability_translations as $role => $cap ) {
4448
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4449
				return $role;
4450
			}
4451
		}
4452
4453
		return false;
4454
	}
4455
4456
	function translate_role_to_cap( $role ) {
4457
		if ( ! isset( $this->capability_translations[$role] ) ) {
4458
			return false;
4459
		}
4460
4461
		return $this->capability_translations[$role];
4462
	}
4463
4464
	function sign_role( $role ) {
4465
		if ( ! $user_id = (int) get_current_user_id() ) {
4466
			return false;
4467
		}
4468
4469
		$token = Jetpack_Data::get_access_token();
4470
		if ( ! $token || is_wp_error( $token ) ) {
4471
			return false;
4472
		}
4473
4474
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4475
	}
4476
4477
4478
	/**
4479
	 * Builds a URL to the Jetpack connection auth page
4480
	 *
4481
	 * @since 3.9.5
4482
	 *
4483
	 * @param bool $raw If true, URL will not be escaped.
4484
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4485
	 *                              If string, will be a custom redirect.
4486
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4487
	 *
4488
	 * @return string Connect URL
4489
	 */
4490
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4491
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4492
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4493
			if( is_network_admin() ) {
4494
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4495
			    'admin.php?page=jetpack-settings' ), $url );
4496
			}
4497
		} else {
4498
			require_once JETPACK__GLOTPRESS_LOCALES_PATH;
4499
			$role = $this->translate_current_user_to_role();
4500
			$signed_role = $this->sign_role( $role );
4501
4502
			$user = wp_get_current_user();
4503
4504
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4505
4506
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4507
4508
			if( isset( $_REQUEST['is_multisite'] ) ) {
4509
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4510
			}
4511
4512
			$secrets = Jetpack::init()->generate_secrets();
4513
			Jetpack_Options::update_option( 'authorize', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] . ':' . $secrets[3] );
4514
4515
			@list( $secret ) = explode( ':', Jetpack_Options::get_option( 'authorize' ) );
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...
4516
4517
			$args = urlencode_deep(
4518
				array(
4519
					'response_type' => 'code',
4520
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4521
					'redirect_uri'  => add_query_arg(
4522
						array(
4523
							'action'   => 'authorize',
4524
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4525
							'redirect' => urlencode( $redirect ),
4526
						),
4527
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4528
					),
4529
					'state'         => $user->ID,
4530
					'scope'         => $signed_role,
4531
					'user_email'    => $user->user_email,
4532
					'user_login'    => $user->user_login,
4533
					'is_active'     => Jetpack::is_active(),
4534
					'jp_version'    => JETPACK__VERSION,
4535
					'auth_type'     => 'calypso',
4536
					'secret'        => $secret,
4537
					'locale'        => isset( $gp_locale->slug ) ? $gp_locale->slug : '',
4538
					'blogname'      => get_option( 'blogname' ),
4539
				)
4540
			);
4541
4542
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4543
		}
4544
4545
		if ( $from ) {
4546
			$url = add_query_arg( 'from', $from, $url );
4547
		}
4548
4549
		if ( isset( $_GET['calypso_env'] ) ) {
4550
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4551
		}
4552
4553
		return $raw ? $url : esc_url( $url );
4554
	}
4555
4556
	function build_reconnect_url( $raw = false ) {
4557
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4558
		return $raw ? $url : esc_url( $url );
4559
	}
4560
4561
	public static function admin_url( $args = null ) {
4562
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4563
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4564
		return $url;
4565
	}
4566
4567
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4568
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4569
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4570
	}
4571
4572
	function dismiss_jetpack_notice() {
4573
4574
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4575
			return;
4576
		}
4577
4578
		switch( $_GET['jetpack-notice'] ) {
4579
			case 'dismiss':
4580
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4581
4582
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4583
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4584
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4585
				}
4586
				break;
4587 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...
4588
4589
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4590
					// Don't show the banner again
4591
4592
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4593
					// redirect back to the page that had the notice
4594
					if ( wp_get_referer() ) {
4595
						wp_safe_redirect( wp_get_referer() );
4596
					} else {
4597
						// Take me to Jetpack
4598
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4599
					}
4600
				}
4601
				break;
4602 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...
4603
4604
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4605
					// Don't show the banner again
4606
4607
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4608
					// redirect back to the page that had the notice
4609
					if ( wp_get_referer() ) {
4610
						wp_safe_redirect( wp_get_referer() );
4611
					} else {
4612
						// Take me to Jetpack
4613
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4614
					}
4615
				}
4616
				break;
4617
			case 'jetpack-manage-opt-in':
4618
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4619
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4620
4621
					$redirection_url = Jetpack::admin_url();
4622
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4623
4624
					// Don't redirect form the Jetpack Setting Page
4625
					$referer_parsed = parse_url ( wp_get_referer() );
4626
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4627
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4628
						// Take the user to Jetpack home except when on the setting page
4629
						$redirection_url = wp_get_referer();
4630
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4631
					}
4632
					// Also update the JSON API FULL MANAGEMENT Option
4633
					Jetpack::activate_module( 'manage', false, false );
4634
4635
					// Special Message when option in.
4636
					Jetpack::state( 'optin-manage', 'true' );
4637
					// Activate the Module if not activated already
4638
4639
					// Redirect properly
4640
					wp_safe_redirect( $redirection_url );
4641
4642
				}
4643
				break;
4644
		}
4645
	}
4646
4647
	function debugger_page() {
4648
		nocache_headers();
4649
		if ( ! current_user_can( 'manage_options' ) ) {
4650
			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...
4651
		}
4652
		Jetpack_Debugger::jetpack_debug_display_handler();
4653
		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...
4654
	}
4655
4656
	public static function admin_screen_configure_module( $module_id ) {
4657
4658
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4659
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4660
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4661
				/**
4662
				 * Fires to diplay a custom module activation screen.
4663
				 *
4664
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4665
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4666
				 *
4667
				 * @module manage
4668
				 *
4669
				 * @since 3.8.0
4670
				 *
4671
				 * @param int $module_id Module ID.
4672
				 */
4673
				do_action( 'display_activate_module_setting_' . $module_id );
4674
			} else {
4675
				self::display_activate_module_link( $module_id );
4676
			}
4677
4678
			return false;
4679
		} ?>
4680
4681
		<div id="jp-settings-screen" style="position: relative">
4682
			<h3>
4683
			<?php
4684
				$module = Jetpack::get_module( $module_id );
4685
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4686
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4687
			?>
4688
			</h3>
4689
			<?php
4690
				/**
4691
				 * Fires within the displayed message when a feature configuation is updated.
4692
				 *
4693
				 * @since 3.4.0
4694
				 *
4695
				 * @param int $module_id Module ID.
4696
				 */
4697
				do_action( 'jetpack_notices_update_settings', $module_id );
4698
				/**
4699
				 * Fires when a feature configuation screen is loaded.
4700
				 * The dynamic part of the hook, $module_id, is the module ID.
4701
				 *
4702
				 * @since 1.1.0
4703
				 */
4704
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4705
			?>
4706
		</div><?php
4707
	}
4708
4709
	/**
4710
	 * Display link to activate the module to see the settings screen.
4711
	 * @param  string $module_id
4712
	 * @return null
4713
	 */
4714
	public static function display_activate_module_link( $module_id ) {
4715
4716
		$info =  Jetpack::get_module( $module_id );
4717
		$extra = '';
4718
		$activate_url = wp_nonce_url(
4719
				Jetpack::admin_url(
4720
					array(
4721
						'page'   => 'jetpack',
4722
						'action' => 'activate',
4723
						'module' => $module_id,
4724
					)
4725
				),
4726
				"jetpack_activate-$module_id"
4727
			);
4728
4729
		?>
4730
4731
		<div class="wrap configure-module">
4732
			<div id="jp-settings-screen">
4733
				<?php
4734
				if ( $module_id == 'json-api' ) {
4735
4736
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4737
4738
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4739
4740
					$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' );
4741
4742
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4743
				} ?>
4744
4745
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4746
				<div class="narrow">
4747
					<p><?php echo  $info['description']; ?></p>
4748
					<?php if( $extra ) { ?>
4749
					<p><?php echo esc_html( $extra ); ?></p>
4750
					<?php } ?>
4751
					<p>
4752
						<?php
4753
						if( wp_get_referer() ) {
4754
							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() );
4755
						} else {
4756
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4757
						} ?>
4758
					</p>
4759
				</div>
4760
4761
			</div>
4762
		</div>
4763
4764
		<?php
4765
	}
4766
4767
	public static function sort_modules( $a, $b ) {
4768
		if ( $a['sort'] == $b['sort'] )
4769
			return 0;
4770
4771
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4772
	}
4773
4774 View Code Duplication
	function sync_reindex_trigger() {
4775
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4776
			echo json_encode( $this->sync->reindex_trigger() );
4777
		} else {
4778
			echo '{"status":"ERROR"}';
4779
		}
4780
		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...
4781
	}
4782
4783 View Code Duplication
	function sync_reindex_status(){
4784
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4785
			echo json_encode( $this->sync->reindex_status() );
4786
		} else {
4787
			echo '{"status":"ERROR"}';
4788
		}
4789
		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...
4790
	}
4791
4792
/* Client API */
4793
4794
	/**
4795
	 * Returns the requested Jetpack API URL
4796
	 *
4797
	 * @return string
4798
	 */
4799
	public static function api_url( $relative_url ) {
4800
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4801
	}
4802
4803
	/**
4804
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4805
	 */
4806
	public static function fix_url_for_bad_hosts( $url ) {
4807
		if ( 0 !== strpos( $url, 'https://' ) ) {
4808
			return $url;
4809
		}
4810
4811
		switch ( JETPACK_CLIENT__HTTPS ) {
4812
			case 'ALWAYS' :
4813
				return $url;
4814
			case 'NEVER' :
4815
				return set_url_scheme( $url, 'http' );
4816
			// default : case 'AUTO' :
4817
		}
4818
4819
		// we now return the unmodified SSL URL by default, as a security precaution
4820
		return $url;
4821
	}
4822
4823
	/**
4824
	 * Checks to see if the URL is using SSL to connect with Jetpack
4825
	 *
4826
	 * @since 2.3.3
4827
	 * @return boolean
4828
	 */
4829
	public static function permit_ssl( $force_recheck = false ) {
4830
		// Do some fancy tests to see if ssl is being supported
4831
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4832
			$message = '';
4833
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4834
				$ssl = 0;
4835
			} else {
4836
				switch ( JETPACK_CLIENT__HTTPS ) {
4837
					case 'NEVER':
4838
						$ssl = 0;
4839
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4840
						break;
4841
					case 'ALWAYS':
4842
					case 'AUTO':
4843
					default:
4844
						$ssl = 1;
4845
						break;
4846
				}
4847
4848
				// If it's not 'NEVER', test to see
4849
				if ( $ssl ) {
4850
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4851
						$ssl = 0;
4852
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4853
					} else {
4854
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4855
						if ( is_wp_error( $response ) ) {
4856
							$ssl = 0;
4857
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4858
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4859
							$ssl = 0;
4860
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4861
						}
4862
					}
4863
				}
4864
			}
4865
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4866
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4867
		}
4868
4869
		return (bool) $ssl;
4870
	}
4871
4872
	/*
4873
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4874
	 */
4875
	public function alert_auto_ssl_fail() {
4876
		if ( ! current_user_can( 'manage_options' ) )
4877
			return;
4878
		?>
4879
4880
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4881
			<div class="jp-banner__content">
4882
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4883
				<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>
4884
				<p>
4885
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4886
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4887
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4888
				</p>
4889
				<p>
4890
					<?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' ), 
4891
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4892
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4893
				</p>
4894
			</div>
4895
		</div>
4896
		<style>
4897
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4898
		</style>
4899
		<script type="text/javascript">
4900
			jQuery( document ).ready( function( $ ) {
4901
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4902
					var $this = $( this );
4903
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4904
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4905
					e.preventDefault();
4906
					$.post( '/wp-json/jetpack/v4/recheck-ssl' )
4907
					  .done( function( response ) {
4908
					  	if ( response.enabled ) {
4909
					  		$( '#jetpack-ssl-warning' ).hide();
4910
					  	} else {
4911
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4912
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4913
					  	}
4914
					  }.bind( $this ) );
4915
				} );
4916
			} );
4917
		</script>
4918
4919
		<?php
4920
	}
4921
4922
	/**
4923
	 * Returns the Jetpack XML-RPC API
4924
	 *
4925
	 * @return string
4926
	 */
4927
	public static function xmlrpc_api_url() {
4928
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4929
		return untrailingslashit( $base ) . '/xmlrpc.php';
4930
	}
4931
4932
	/**
4933
	 * Creates two secret tokens and the end of life timestamp for them.
4934
	 *
4935
	 * Note these tokens are unique per call, NOT static per site for connecting.
4936
	 *
4937
	 * @since 2.6
4938
	 * @return array
4939
	 */
4940
	public function generate_secrets() {
4941
	    $secrets = array(
4942
			wp_generate_password( 32, false ), // secret_1
4943
			wp_generate_password( 32, false ), // secret_2
4944
			( time() + 600 ), // eol ( End of Life )
4945
			get_current_user_id(), // ties the secrets to the current user
4946
	    );
4947
4948
	    return $secrets;
4949
	}
4950
4951
	/**
4952
	 * Builds the timeout limit for queries talking with the wpcom servers.
4953
	 *
4954
	 * Based on local php max_execution_time in php.ini
4955
	 *
4956
	 * @since 2.6
4957
	 * @return int
4958
	 **/
4959
	public function get_remote_query_timeout_limit() {
4960
	    $timeout = (int) ini_get( 'max_execution_time' );
4961
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4962
		$timeout = 30;
4963
	    return intval( $timeout / 2 );
4964
	}
4965
4966
4967
	/**
4968
	 * Takes the response from the Jetpack register new site endpoint and
4969
	 * verifies it worked properly.
4970
	 *
4971
	 * @since 2.6
4972
	 * @return true or Jetpack_Error
4973
	 **/
4974
	public function validate_remote_register_response( $response ) {
4975
	    	if ( is_wp_error( $response ) ) {
4976
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4977
		}
4978
4979
		$code   = wp_remote_retrieve_response_code( $response );
4980
		$entity = wp_remote_retrieve_body( $response );
4981
		if ( $entity )
4982
			$json = json_decode( $entity );
4983
		else
4984
			$json = false;
4985
4986
		$code_type = intval( $code / 100 );
4987
		if ( 5 == $code_type ) {
4988
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4989
		} elseif ( 408 == $code ) {
4990
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4991
		} elseif ( ! empty( $json->error ) ) {
4992
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4993
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4994
		} elseif ( 200 != $code ) {
4995
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4996
		}
4997
4998
		// Jetpack ID error block
4999
		if ( empty( $json->jetpack_id ) ) {
5000
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5001
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
5002
			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 );
5003
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
5004
			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 );
5005
		}
5006
5007
	    return true;
5008
	}
5009
	/**
5010
	 * @return bool|WP_Error
5011
	 */
5012
	public static function register() {
5013
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5014
		$secrets = Jetpack::init()->generate_secrets();
5015
5016
		Jetpack_Options::update_option( 'register', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] . ':' . $secrets[3] );
5017
5018
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack_Options::get_option( 'register' ) );
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...
5019
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
5020
			return new Jetpack_Error( 'missing_secrets' );
5021
		}
5022
5023
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
5024
5025
		$gmt_offset = get_option( 'gmt_offset' );
5026
		if ( ! $gmt_offset ) {
5027
			$gmt_offset = 0;
5028
		}
5029
5030
		$stats_options = get_option( 'stats_options' );
5031
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5032
5033
		$args = array(
5034
			'method'  => 'POST',
5035
			'body'    => array(
5036
				'siteurl'         => site_url(),
5037
				'home'            => home_url(),
5038
				'gmt_offset'      => $gmt_offset,
5039
				'timezone_string' => (string) get_option( 'timezone_string' ),
5040
				'site_name'       => (string) get_option( 'blogname' ),
5041
				'secret_1'        => $secret_1,
5042
				'secret_2'        => $secret_2,
5043
				'site_lang'       => get_locale(),
5044
				'timeout'         => $timeout,
5045
				'stats_id'        => $stats_id,
5046
				'state'           => get_current_user_id(),
5047
			),
5048
			'headers' => array(
5049
				'Accept' => 'application/json',
5050
			),
5051
			'timeout' => $timeout,
5052
		);
5053
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5054
5055
5056
		// Make sure the response is valid and does not contain any Jetpack errors
5057
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
5058
		if( is_wp_error( $valid_response ) || !$valid_response ) {
5059
		    return $valid_response;
5060
		}
5061
5062
		// Grab the response values to work with
5063
		$code   = wp_remote_retrieve_response_code( $response );
5064
		$entity = wp_remote_retrieve_body( $response );
5065
5066
		if ( $entity )
5067
			$json = json_decode( $entity );
5068
		else
5069
			$json = false;
5070
5071 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
5072
			return new Jetpack_Error( 'jetpack_secret', '', $code );
5073
5074
		if ( isset( $json->jetpack_public ) ) {
5075
			$jetpack_public = (int) $json->jetpack_public;
5076
		} else {
5077
			$jetpack_public = false;
5078
		}
5079
5080
		Jetpack_Options::update_options(
5081
			array(
5082
				'id'         => (int)    $json->jetpack_id,
5083
				'blog_token' => (string) $json->jetpack_secret,
5084
				'public'     => $jetpack_public,
5085
			)
5086
		);
5087
5088
		/**
5089
		 * Fires when a site is registered on WordPress.com.
5090
		 *
5091
		 * @since 3.7.0
5092
		 *
5093
		 * @param int $json->jetpack_id Jetpack Blog ID.
5094
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5095
		 * @param int|bool $jetpack_public Is the site public.
5096
		 */
5097
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
5098
5099
		// Initialize Jump Start for the first and only time.
5100
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5101
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5102
5103
			$jetpack = Jetpack::init();
5104
5105
			$jetpack->stat( 'jumpstart', 'unique-views' );
5106
			$jetpack->do_stats( 'server_side' );
5107
		};
5108
5109
		return true;
5110
	}
5111
5112
	/**
5113
	 * If the db version is showing something other that what we've got now, bump it to current.
5114
	 *
5115
	 * @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...
5116
	 */
5117
	public static function maybe_set_version_option() {
5118
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5119
		if ( JETPACK__VERSION != $version ) {
5120
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5121
			return true;
5122
		}
5123
		return false;
5124
	}
5125
5126
/* Client Server API */
5127
5128
	/**
5129
	 * Loads the Jetpack XML-RPC client
5130
	 */
5131
	public static function load_xml_rpc_client() {
5132
		require_once ABSPATH . WPINC . '/class-IXR.php';
5133
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5134
	}
5135
5136
	function verify_xml_rpc_signature() {
5137
		if ( $this->xmlrpc_verification ) {
5138
			return $this->xmlrpc_verification;
5139
		}
5140
5141
		// It's not for us
5142
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5143
			return false;
5144
		}
5145
5146
		@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...
5147
		if (
5148
			empty( $token_key )
5149
		||
5150
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5151
		) {
5152
			return false;
5153
		}
5154
5155
		if ( '0' === $user_id ) {
5156
			$token_type = 'blog';
5157
			$user_id = 0;
5158
		} else {
5159
			$token_type = 'user';
5160
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5161
				return false;
5162
			}
5163
			$user_id = (int) $user_id;
5164
5165
			$user = new WP_User( $user_id );
5166
			if ( ! $user || ! $user->exists() ) {
5167
				return false;
5168
			}
5169
		}
5170
5171
		$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...
5172
		if ( ! $token ) {
5173
			return false;
5174
		}
5175
5176
		$token_check = "$token_key.";
5177
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5178
			return false;
5179
		}
5180
5181
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5182
5183
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5184
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5185
			$post_data   = $_POST;
5186
			$file_hashes = array();
5187
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5188
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5189
					continue;
5190
				}
5191
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5192
				$file_hashes[$post_data_key] = $post_data_value;
5193
			}
5194
5195
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5196
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5197
				$post_data[$post_data_key] = $post_data_value;
5198
			}
5199
5200
			ksort( $post_data );
5201
5202
			$body = http_build_query( stripslashes_deep( $post_data ) );
5203
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5204
			$body = file_get_contents( 'php://input' );
5205
		} else {
5206
			$body = null;
5207
		}
5208
		$signature = $jetpack_signature->sign_current_request(
5209
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5210
		);
5211
5212
		if ( ! $signature ) {
5213
			return false;
5214
		} else if ( is_wp_error( $signature ) ) {
5215
			return $signature;
5216
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5217
			return false;
5218
		}
5219
5220
		$timestamp = (int) $_GET['timestamp'];
5221
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5222
5223
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5224
			return false;
5225
		}
5226
5227
		$this->xmlrpc_verification = array(
5228
			'type'    => $token_type,
5229
			'user_id' => $token->external_user_id,
5230
		);
5231
5232
		return $this->xmlrpc_verification;
5233
	}
5234
5235
	/**
5236
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5237
	 */
5238
	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...
5239
		if ( is_a( $user, 'WP_User' ) ) {
5240
			return $user;
5241
		}
5242
5243
		$token_details = $this->verify_xml_rpc_signature();
5244
5245
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5246
			return $user;
5247
		}
5248
5249
		if ( 'user' !== $token_details['type'] ) {
5250
			return $user;
5251
		}
5252
5253
		if ( ! $token_details['user_id'] ) {
5254
			return $user;
5255
		}
5256
5257
		nocache_headers();
5258
5259
		return new WP_User( $token_details['user_id'] );
5260
	}
5261
5262
	function add_nonce( $timestamp, $nonce ) {
5263
		global $wpdb;
5264
		static $nonces_used_this_request = array();
5265
5266
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5267
			return $nonces_used_this_request["$timestamp:$nonce"];
5268
		}
5269
5270
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5271
		$timestamp = (int) $timestamp;
5272
		$nonce     = esc_sql( $nonce );
5273
5274
		// Raw query so we can avoid races: add_option will also update
5275
		$show_errors = $wpdb->show_errors( false );
5276
5277
		$old_nonce = $wpdb->get_row(
5278
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5279
		);
5280
5281
		if ( is_null( $old_nonce ) ) {
5282
			$return = $wpdb->query(
5283
				$wpdb->prepare(
5284
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5285
					"jetpack_nonce_{$timestamp}_{$nonce}",
5286
					time(),
5287
					'no'
5288
				)
5289
			);
5290
		} else {
5291
			$return = false;
5292
		}
5293
5294
		$wpdb->show_errors( $show_errors );
5295
5296
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5297
5298
		return $return;
5299
	}
5300
5301
	/**
5302
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5303
	 * Capture it here so we can verify the signature later.
5304
	 */
5305
	function xmlrpc_methods( $methods ) {
5306
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5307
		return $methods;
5308
	}
5309
5310
	function public_xmlrpc_methods( $methods ) {
5311
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5312
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5313
		}
5314
		return $methods;
5315
	}
5316
5317
	function jetpack_getOptions( $args ) {
5318
		global $wp_xmlrpc_server;
5319
5320
		$wp_xmlrpc_server->escape( $args );
5321
5322
		$username	= $args[1];
5323
		$password	= $args[2];
5324
5325
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5326
			return $wp_xmlrpc_server->error;
5327
		}
5328
5329
		$options = array();
5330
		$user_data = $this->get_connected_user_data();
5331
		if ( is_array( $user_data ) ) {
5332
			$options['jetpack_user_id'] = array(
5333
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5334
				'readonly'      => true,
5335
				'value'         => $user_data['ID'],
5336
			);
5337
			$options['jetpack_user_login'] = array(
5338
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5339
				'readonly'      => true,
5340
				'value'         => $user_data['login'],
5341
			);
5342
			$options['jetpack_user_email'] = array(
5343
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5344
				'readonly'      => true,
5345
				'value'         => $user_data['email'],
5346
			);
5347
			$options['jetpack_user_site_count'] = array(
5348
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5349
				'readonly'      => true,
5350
				'value'         => $user_data['site_count'],
5351
			);
5352
		}
5353
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5354
		$args = stripslashes_deep( $args );
5355
		return $wp_xmlrpc_server->wp_getOptions( $args );
5356
	}
5357
5358
	function xmlrpc_options( $options ) {
5359
		$jetpack_client_id = false;
5360
		if ( self::is_active() ) {
5361
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5362
		}
5363
		$options['jetpack_version'] = array(
5364
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5365
				'readonly'      => true,
5366
				'value'         => JETPACK__VERSION,
5367
		);
5368
5369
		$options['jetpack_client_id'] = array(
5370
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5371
				'readonly'      => true,
5372
				'value'         => $jetpack_client_id,
5373
		);
5374
		return $options;
5375
	}
5376
5377
	public static function clean_nonces( $all = false ) {
5378
		global $wpdb;
5379
5380
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5381
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
5382
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5383
		} else {
5384
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
5385
		}
5386
5387
		if ( true !== $all ) {
5388
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5389
			$sql_args[] = time() - 3600;
5390
		}
5391
5392
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5393
5394
		$sql = $wpdb->prepare( $sql, $sql_args );
5395
5396
		for ( $i = 0; $i < 1000; $i++ ) {
5397
			if ( ! $wpdb->query( $sql ) ) {
5398
				break;
5399
			}
5400
		}
5401
	}
5402
5403
	/**
5404
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5405
	 * SET: state( $key, $value );
5406
	 * GET: $value = state( $key );
5407
	 *
5408
	 * @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...
5409
	 * @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...
5410
	 * @param bool $restate private
5411
	 */
5412
	public static function state( $key = null, $value = null, $restate = false ) {
5413
		static $state = array();
5414
		static $path, $domain;
5415
		if ( ! isset( $path ) ) {
5416
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5417
			$admin_url = Jetpack::admin_url();
5418
			$bits      = parse_url( $admin_url );
5419
5420
			if ( is_array( $bits ) ) {
5421
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5422
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5423
			} else {
5424
				$path = $domain = null;
5425
			}
5426
		}
5427
5428
		// Extract state from cookies and delete cookies
5429
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5430
			$yum = $_COOKIE[ 'jetpackState' ];
5431
			unset( $_COOKIE[ 'jetpackState' ] );
5432
			foreach ( $yum as $k => $v ) {
5433
				if ( strlen( $v ) )
5434
					$state[ $k ] = $v;
5435
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5436
			}
5437
		}
5438
5439
		if ( $restate ) {
5440
			foreach ( $state as $k => $v ) {
5441
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5442
			}
5443
			return;
5444
		}
5445
5446
		// Get a state variable
5447
		if ( isset( $key ) && ! isset( $value ) ) {
5448
			if ( array_key_exists( $key, $state ) )
5449
				return $state[ $key ];
5450
			return null;
5451
		}
5452
5453
		// Set a state variable
5454
		if ( isset ( $key ) && isset( $value ) ) {
5455
			if( is_array( $value ) && isset( $value[0] ) ) {
5456
				$value = $value[0];
5457
			}
5458
			$state[ $key ] = $value;
5459
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5460
		}
5461
	}
5462
5463
	public static function restate() {
5464
		Jetpack::state( null, null, true );
5465
	}
5466
5467
	public static function check_privacy( $file ) {
5468
		static $is_site_publicly_accessible = null;
5469
5470
		if ( is_null( $is_site_publicly_accessible ) ) {
5471
			$is_site_publicly_accessible = false;
5472
5473
			Jetpack::load_xml_rpc_client();
5474
			$rpc = new Jetpack_IXR_Client();
5475
5476
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5477
			if ( $success ) {
5478
				$response = $rpc->getResponse();
5479
				if ( $response ) {
5480
					$is_site_publicly_accessible = true;
5481
				}
5482
			}
5483
5484
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5485
		}
5486
5487
		if ( $is_site_publicly_accessible ) {
5488
			return;
5489
		}
5490
5491
		$module_slug = self::get_module_slug( $file );
5492
5493
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5494
		if ( ! $privacy_checks ) {
5495
			$privacy_checks = $module_slug;
5496
		} else {
5497
			$privacy_checks .= ",$module_slug";
5498
		}
5499
5500
		Jetpack::state( 'privacy_checks', $privacy_checks );
5501
	}
5502
5503
	/**
5504
	 * Helper method for multicall XMLRPC.
5505
	 */
5506
	public static function xmlrpc_async_call() {
5507
		global $blog_id;
5508
		static $clients = array();
5509
5510
		$client_blog_id = is_multisite() ? $blog_id : 0;
5511
5512
		if ( ! isset( $clients[$client_blog_id] ) ) {
5513
			Jetpack::load_xml_rpc_client();
5514
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5515
			if ( function_exists( 'ignore_user_abort' ) ) {
5516
				ignore_user_abort( true );
5517
			}
5518
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5519
		}
5520
5521
		$args = func_get_args();
5522
5523
		if ( ! empty( $args[0] ) ) {
5524
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5525
		} elseif ( is_multisite() ) {
5526
			foreach ( $clients as $client_blog_id => $client ) {
5527
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5528
					continue;
5529
				}
5530
5531
				$switch_success = switch_to_blog( $client_blog_id, true );
5532
				if ( ! $switch_success ) {
5533
					continue;
5534
				}
5535
5536
				flush();
5537
				$client->query();
5538
5539
				restore_current_blog();
5540
			}
5541
		} else {
5542
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5543
				flush();
5544
				$clients[0]->query();
5545
			}
5546
		}
5547
	}
5548
5549
	public static function staticize_subdomain( $url ) {
5550
5551
		// Extract hostname from URL
5552
		$host = parse_url( $url, PHP_URL_HOST );
5553
5554
		// Explode hostname on '.'
5555
		$exploded_host = explode( '.', $host );
5556
5557
		// Retrieve the name and TLD
5558
		if ( count( $exploded_host ) > 1 ) {
5559
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5560
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5561
			// Rebuild domain excluding subdomains
5562
			$domain = $name . '.' . $tld;
5563
		} else {
5564
			$domain = $host;
5565
		}
5566
		// Array of Automattic domains
5567
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5568
5569
		// Return $url if not an Automattic domain
5570
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5571
			return $url;
5572
		}
5573
5574
		if ( is_ssl() ) {
5575
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5576
		}
5577
5578
		srand( crc32( basename( $url ) ) );
5579
		$static_counter = rand( 0, 2 );
5580
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5581
5582
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5583
	}
5584
5585
/* JSON API Authorization */
5586
5587
	/**
5588
	 * Handles the login action for Authorizing the JSON API
5589
	 */
5590
	function login_form_json_api_authorization() {
5591
		$this->verify_json_api_authorization_request();
5592
5593
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5594
5595
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5596
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5597
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5598
	}
5599
5600
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5601
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5602
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5603
			return $url;
5604
		}
5605
5606
		$parsed_url = parse_url( $url );
5607
		$url = strtok( $url, '?' );
5608
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5609
		if ( ! empty( $parsed_url['query'] ) )
5610
			$url .= "&{$parsed_url['query']}";
5611
5612
		return $url;
5613
	}
5614
5615
	// Make sure the POSTed request is handled by the same action
5616
	function preserve_action_in_login_form_for_json_api_authorization() {
5617
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5618
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5619
	}
5620
5621
	// If someone logs in to approve API access, store the Access Code in usermeta
5622
	function store_json_api_authorization_token( $user_login, $user ) {
5623
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5624
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5625
		$token = wp_generate_password( 32, false );
5626
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5627
	}
5628
5629
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5630
	function allow_wpcom_public_api_domain( $domains ) {
5631
		$domains[] = 'public-api.wordpress.com';
5632
		return $domains;
5633
	}
5634
5635
	// Add the Access Code details to the public-api.wordpress.com redirect
5636
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5637
		return add_query_arg(
5638
			urlencode_deep(
5639
				array(
5640
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5641
					'jetpack-user-id' => (int) $user->ID,
5642
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5643
				)
5644
			),
5645
			$redirect_to
5646
		);
5647
	}
5648
5649
	// Verifies the request by checking the signature
5650
	function verify_json_api_authorization_request() {
5651
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5652
5653
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5654
		if ( ! $token || empty( $token->secret ) ) {
5655
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5656
		}
5657
5658
		$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' );
5659
5660
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5661
5662
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5663
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5664
		} else {
5665
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5666
		}
5667
5668
		if ( ! $signature ) {
5669
			wp_die( $die_error );
5670
		} else if ( is_wp_error( $signature ) ) {
5671
			wp_die( $die_error );
5672
		} else if ( $signature !== $_GET['signature'] ) {
5673
			if ( is_ssl() ) {
5674
				// 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
5675
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5676
				if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5677
					wp_die( $die_error );
5678
				}
5679
			} else {
5680
				wp_die( $die_error );
5681
			}
5682
		}
5683
5684
		$timestamp = (int) $_GET['timestamp'];
5685
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5686
5687
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5688
			// De-nonce the nonce, at least for 5 minutes.
5689
			// 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)
5690
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5691
			if ( $old_nonce_time < time() - 300 ) {
5692
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5693
			}
5694
		}
5695
5696
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5697
		$data_filters = array(
5698
			'state'        => 'opaque',
5699
			'client_id'    => 'int',
5700
			'client_title' => 'string',
5701
			'client_image' => 'url',
5702
		);
5703
5704
		foreach ( $data_filters as $key => $sanitation ) {
5705
			if ( ! isset( $data->$key ) ) {
5706
				wp_die( $die_error );
5707
			}
5708
5709
			switch ( $sanitation ) {
5710
			case 'int' :
5711
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5712
				break;
5713
			case 'opaque' :
5714
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5715
				break;
5716
			case 'string' :
5717
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5718
				break;
5719
			case 'url' :
5720
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5721
				break;
5722
			}
5723
		}
5724
5725
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5726
			wp_die( $die_error );
5727
		}
5728
	}
5729
5730
	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...
5731
		return '<p class="message">' . sprintf(
5732
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5733
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5734
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5735
	}
5736
5737
	/**
5738
	 * Get $content_width, but with a <s>twist</s> filter.
5739
	 */
5740
	public static function get_content_width() {
5741
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5742
		/**
5743
		 * Filter the Content Width value.
5744
		 *
5745
		 * @since 2.2.3
5746
		 *
5747
		 * @param string $content_width Content Width value.
5748
		 */
5749
		return apply_filters( 'jetpack_content_width', $content_width );
5750
	}
5751
5752
	/**
5753
	 * Centralize the function here until it gets added to core.
5754
	 *
5755
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5756
	 * @param int $size Size of the avatar image
5757
	 * @param string $default URL to a default image to use if no avatar is available
5758
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5759
	 *
5760
	 * @return array First element is the URL, second is the class.
5761
	 */
5762
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5763
		// Don't bother adding the __return_true filter if it's already there.
5764
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5765
5766
		if ( $force_display && ! $has_filter )
5767
			add_filter( 'pre_option_show_avatars', '__return_true' );
5768
5769
		$avatar = get_avatar( $id_or_email, $size, $default );
5770
5771
		if ( $force_display && ! $has_filter )
5772
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5773
5774
		// If no data, fail out.
5775
		if ( is_wp_error( $avatar ) || ! $avatar )
5776
			return array( null, null );
5777
5778
		// Pull out the URL.  If it's not there, fail out.
5779
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5780
			return array( null, null );
5781
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5782
5783
		// Pull out the class, but it's not a big deal if it's missing.
5784
		$class = '';
5785
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5786
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5787
5788
		return array( $url, $class );
5789
	}
5790
5791
	/**
5792
	 * Pings the WordPress.com Mirror Site for the specified options.
5793
	 *
5794
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5795
	 *
5796
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5797
	 */
5798
	public function get_cloud_site_options( $option_names ) {
5799
		$option_names = array_filter( (array) $option_names, 'is_string' );
5800
5801
		Jetpack::load_xml_rpc_client();
5802
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5803
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5804
		if ( $xml->isError() ) {
5805
			return array(
5806
				'error_code' => $xml->getErrorCode(),
5807
				'error_msg'  => $xml->getErrorMessage(),
5808
			);
5809
		}
5810
		$cloud_site_options = $xml->getResponse();
5811
5812
		return $cloud_site_options;
5813
	}
5814
5815
	/**
5816
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5817
	 *
5818
	 * @return array An array of options to check.
5819
	 */
5820
	public static function identity_crisis_options_to_check() {
5821
		return array(
5822
			'siteurl',
5823
			'home',
5824
		);
5825
	}
5826
5827
	/**
5828
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5829
	 *
5830
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5831
	 *
5832
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5833
	 */
5834
	public static function check_identity_crisis( $force_recheck = false ) {
5835
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5836
			return false;
5837
5838
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5839
			$options_to_check = self::identity_crisis_options_to_check();
5840
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5841
			$errors        = array();
5842
5843
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5844
5845
				// If it's not the same as the local value...
5846
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5847
5848
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5849
					if ( 'error_code' == $cloud_key ) {
5850
						$errors[ $cloud_key ] = $cloud_value;
5851
						break;
5852
					}
5853
5854
					$parsed_cloud_value = parse_url( $cloud_value );
5855
					// If the current options is an IP address
5856
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5857
						// Give the new value a Jetpack to fly in to the clouds
5858
						Jetpack::resolve_identity_crisis( $cloud_key );
5859
						continue;
5860
					}
5861
5862
					// And it's not been added to the whitelist...
5863
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5864
						/*
5865
						 * This should be a temporary hack until a cleaner solution is found.
5866
						 *
5867
						 * The siteurl and home can be set to use http in General > Settings
5868
						 * however some constants can be defined that can force https in wp-admin
5869
						 * when this happens wpcom can confuse wporg with a fake identity
5870
						 * crisis with a mismatch of http vs https when it should be allowed.
5871
						 * we need to check that here.
5872
						 *
5873
						 * @see https://github.com/Automattic/jetpack/issues/1006
5874
						 */
5875
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5876
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5877
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5878
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5879
							continue;
5880
						}
5881
5882
5883
						// Then kick an error!
5884
						$errors[ $cloud_key ] = $cloud_value;
5885
					}
5886
				}
5887
			}
5888
		}
5889
5890
		/**
5891
		 * Filters the errors returned when checking for an Identity Crisis.
5892
		 *
5893
		 * @since 2.3.2
5894
		 *
5895
		 * @param array $errors Array of Identity Crisis errors.
5896
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5897
		 */
5898
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5899
	}
5900
5901
	/*
5902
	 * Resolve ID crisis
5903
	 *
5904
	 * If the URL has changed, but the rest of the options are the same (i.e. blog/user tokens)
5905
	 * The user has the option to update the shadow site with the new URL before a new
5906
	 * token is created.
5907
	 *
5908
	 * @param $key : Which option to sync.  null defautlts to home and siteurl
5909
	 */
5910
	public static function resolve_identity_crisis( $key = null ) {
5911
		if ( $key ) {
5912
			$identity_options = array( $key );
5913
		} else {
5914
			$identity_options = self::identity_crisis_options_to_check();
5915
		}
5916
5917
		if ( is_array( $identity_options ) ) {
5918
			foreach( $identity_options as $identity_option ) {
5919
				Jetpack_Sync::sync_options( __FILE__, $identity_option );
5920
5921
				/**
5922
				 * Fires when a shadow site option is updated.
5923
				 * These options are updated via the Identity Crisis UI.
5924
				 * $identity_option is the option that gets updated.
5925
				 *
5926
				 * @since 3.7.0
5927
				 */
5928
				do_action( "update_option_{$identity_option}" );
5929
			}
5930
		}
5931
	}
5932
5933
	/*
5934
	 * Whitelist URL
5935
	 *
5936
	 * Ignore the URL differences between the blog and the shadow site.
5937
	 */
5938
	public static function whitelist_current_url() {
5939
		$options_to_check = Jetpack::identity_crisis_options_to_check();
5940
		$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5941
5942
		foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5943
			Jetpack::whitelist_identity_crisis_value( $cloud_key, $cloud_value );
5944
		}
5945
	}
5946
5947
	/*
5948
	 * Ajax callbacks for ID crisis resolutions
5949
	 *
5950
	 * Things that could happen here:
5951
	 *  - site_migrated : Update the URL on the shadow blog to match new domain
5952
	 *  - whitelist     : Ignore the URL difference
5953
	 *  - default       : Error message
5954
	 */
5955
	public static function resolve_identity_crisis_ajax_callback() {
5956
		check_ajax_referer( 'resolve-identity-crisis', 'ajax-nonce' );
5957
5958
		switch ( $_POST[ 'crisis_resolution_action' ] ) {
5959
			case 'site_migrated':
5960
				Jetpack::resolve_identity_crisis();
5961
				echo 'resolved';
5962
				break;
5963
5964
			case 'whitelist':
5965
				Jetpack::whitelist_current_url();
5966
				echo 'whitelisted';
5967
				break;
5968
5969
			case 'reset_connection':
5970
				// Delete the options first so it doesn't get confused which site to disconnect dotcom-side
5971
				Jetpack_Options::delete_option(
5972
					array(
5973
						'register',
5974
						'blog_token',
5975
						'user_token',
5976
						'user_tokens',
5977
						'master_user',
5978
						'time_diff',
5979
						'fallback_no_verify_ssl_certs',
5980
						'id',
5981
					)
5982
				);
5983
				delete_transient( 'jetpack_has_identity_crisis' );
5984
5985
				echo 'reset-connection-success';
5986
				break;
5987
5988
			default:
5989
				echo 'missing action';
5990
				break;
5991
		}
5992
5993
		wp_die();
5994
	}
5995
5996
	/**
5997
	 * Adds a value to the whitelist for the specified key.
5998
	 *
5999
	 * @param string $key The option name that we're whitelisting the value for.
6000
	 * @param string $value The value that we're intending to add to the whitelist.
6001
	 *
6002
	 * @return bool Whether the value was added to the whitelist, or false if it was already there.
6003
	 */
6004
	public static function whitelist_identity_crisis_value( $key, $value ) {
6005
		if ( Jetpack::is_identity_crisis_value_whitelisted( $key, $value ) ) {
6006
			return false;
6007
		}
6008
6009
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6010
		if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
6011
			$whitelist[ $key ] = array();
6012
		}
6013
		array_push( $whitelist[ $key ], $value );
6014
6015
		Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
6016
		return true;
6017
	}
6018
6019
	/**
6020
	 * Checks whether a value is already whitelisted.
6021
	 *
6022
	 * @param string $key The option name that we're checking the value for.
6023
	 * @param string $value The value that we're curious to see if it's on the whitelist.
6024
	 *
6025
	 * @return bool Whether the value is whitelisted.
6026
	 */
6027
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
6028
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6029
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
6030
			return true;
6031
		}
6032
		return false;
6033
	}
6034
6035
	/**
6036
	 * Checks whether the home and siteurl specifically are whitelisted
6037
	 * Written so that we don't have re-check $key and $value params every time
6038
	 * we want to check if this site is whitelisted, for example in footer.php
6039
	 *
6040
	 * @return bool True = already whitelsisted False = not whitelisted
6041
	 */
6042
	public static function is_staging_site() {
6043
		$is_staging = false;
6044
6045
		$current_whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist' );
6046
		if ( $current_whitelist ) {
6047
			$options_to_check  = Jetpack::identity_crisis_options_to_check();
6048
			$cloud_options     = Jetpack::init()->get_cloud_site_options( $options_to_check );
6049
6050
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6051
				if ( self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
6052
					$is_staging = true;
6053
					break;
6054
				}
6055
			}
6056
		}
6057
		$known_staging = array(
6058
			'urls' => array(
6059
				'#\.staging\.wpengine\.com$#i',
6060
				),
6061
			'constants' => array(
6062
				'IS_WPE_SNAPSHOT',
6063
				'KINSTA_DEV_ENV',
6064
				'JETPACK_STAGING_MODE',
6065
				)
6066
			);
6067
		/**
6068
		 * Filters the flags of known staging sites.
6069
		 *
6070
		 * @since 3.9.0
6071
		 *
6072
		 * @param array $known_staging {
6073
		 *     An array of arrays that each are used to check if the current site is staging.
6074
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6075
		 *     @type array $cosntants PHP constants of known staging/developement environments.
6076
		 *  }
6077
		 */
6078
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6079
6080
		if ( isset( $known_staging['urls'] ) ) {
6081
			foreach ( $known_staging['urls'] as $url ){
6082
				if ( preg_match( $url, site_url() ) ) {
6083
					$is_staging = true;
6084
					break;
6085
				}
6086
			}
6087
		}
6088
6089
		if ( isset( $known_staging['constants'] ) ) {
6090
			foreach ( $known_staging['constants'] as $constant ) {
6091
				if ( defined( $constant ) && constant( $constant ) ) {
6092
					$is_staging = true;
6093
				}
6094
			}
6095
		}
6096
6097
		/**
6098
		 * Filters is_staging_site check.
6099
		 *
6100
		 * @since 3.9.0
6101
		 *
6102
		 * @param bool $is_staging If the current site is a staging site.
6103
		 */
6104
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6105
	}
6106
6107
	public function identity_crisis_js( $nonce ) {
6108
?>
6109
<script>
6110
(function( $ ) {
6111
	var SECOND_IN_MS = 1000;
6112
6113
	function contactSupport( e ) {
6114
		e.preventDefault();
6115
		$( '.jp-id-crisis-question' ).hide();
6116
		$( '#jp-id-crisis-contact-support' ).show();
6117
	}
6118
6119
	function autodismissSuccessBanner() {
6120
		$( '.jp-identity-crisis' ).fadeOut(600); //.addClass( 'dismiss' );
6121
	}
6122
6123
	var data = { action: 'jetpack_resolve_identity_crisis', 'ajax-nonce': '<?php echo $nonce; ?>' };
6124
6125
	$( document ).ready(function() {
6126
6127
		// Site moved: Update the URL on the shadow blog
6128
		$( '.site-moved' ).click(function( e ) {
6129
			e.preventDefault();
6130
			data.crisis_resolution_action = 'site_migrated';
6131
			$( '#jp-id-crisis-question-1 .spinner' ).show();
6132
			$.post( ajaxurl, data, function() {
6133
				$( '.jp-id-crisis-question' ).hide();
6134
				$( '.banner-title' ).hide();
6135
				$( '#jp-id-crisis-success' ).show();
6136
				setTimeout( autodismissSuccessBanner, 6 * SECOND_IN_MS );
6137
			});
6138
6139
		});
6140
6141
		// URL hasn't changed, next question please.
6142
		$( '.site-not-moved' ).click(function( e ) {
6143
			e.preventDefault();
6144
			$( '.jp-id-crisis-question' ).hide();
6145
			$( '#jp-id-crisis-question-2' ).show();
6146
		});
6147
6148
		// Reset connection: two separate sites.
6149
		$( '.reset-connection' ).click(function( e ) {
6150
			data.crisis_resolution_action = 'reset_connection';
6151
			$.post( ajaxurl, data, function( response ) {
6152
				if ( 'reset-connection-success' === response ) {
6153
					window.location.replace( '<?php echo Jetpack::admin_url(); ?>' );
6154
				}
6155
			});
6156
		});
6157
6158
		// It's a dev environment.  Ignore.
6159
		$( '.is-dev-env' ).click(function( e ) {
6160
			data.crisis_resolution_action = 'whitelist';
6161
			$( '#jp-id-crisis-question-2 .spinner' ).show();
6162
			$.post( ajaxurl, data, function() {
6163
				$( '.jp-id-crisis-question' ).hide();
6164
				$( '.banner-title' ).hide();
6165
				$( '#jp-id-crisis-success' ).show();
6166
				setTimeout( autodismissSuccessBanner, 4 * SECOND_IN_MS );
6167
			});
6168
		});
6169
6170
		$( '.not-reconnecting' ).click(contactSupport);
6171
		$( '.not-staging-or-dev' ).click(contactSupport);
6172
	});
6173
})( jQuery );
6174
</script>
6175
<?php
6176
	}
6177
6178
	/**
6179
	 * Displays an admin_notice, alerting the user to an identity crisis.
6180
	 */
6181
	public function alert_identity_crisis() {
6182
		// @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...
6183
		if ( ! Jetpack::is_development_version() ) {
6184
			return;
6185
		}
6186
6187
		// @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...
6188
		// @see https://github.com/Automattic/jetpack/issues/2702
6189
		if ( is_multisite() && defined( 'SUNRISE' ) && ! Jetpack::is_development_version() ) {
6190
			return;
6191
		}
6192
6193
		if ( ! current_user_can( 'jetpack_disconnect' ) ) {
6194
			return;
6195
		}
6196
6197
		if ( ! $errors = self::check_identity_crisis() ) {
6198
			return;
6199
		}
6200
6201
		// Only show on dashboard and jetpack pages
6202
		$screen = get_current_screen();
6203
		if ( 'dashboard' !== $screen->base && ! did_action( 'jetpack_notices' ) ) {
6204
			return;
6205
		}
6206
6207
		// Include the js!
6208
		$ajax_nonce = wp_create_nonce( 'resolve-identity-crisis' );
6209
		$this->identity_crisis_js( $ajax_nonce );
6210
6211
		// Include the CSS!
6212
		if ( ! wp_script_is( 'jetpack', 'done' ) ) {
6213
			$this->admin_banner_styles();
6214
		}
6215
6216
		if ( ! array_key_exists( 'error_code', $errors ) ) {
6217
			$key = 'siteurl';
6218
			if ( ! $errors[ $key ] ) {
6219
				$key = 'home';
6220
			}
6221
		} else {
6222
			$key = 'error_code';
6223
			// 401 is the only error we care about.  Any other errors should not trigger the alert.
6224
			if ( 401 !== $errors[ $key ] ) {
6225
				return;
6226
			}
6227
		}
6228
6229
		?>
6230
6231
		<style>
6232
			.jp-identity-crisis .jp-btn-group {
6233
					margin: 15px 0;
6234
				}
6235
			.jp-identity-crisis strong {
6236
					color: #518d2a;
6237
				}
6238
			.jp-identity-crisis.dismiss {
6239
				display: none;
6240
			}
6241
			.jp-identity-crisis .button {
6242
				margin-right: 4px;
6243
			}
6244
		</style>
6245
6246
		<div id="message" class="error jetpack-message jp-identity-crisis stay-visible">
6247
			<div class="service-mark"></div>
6248
			<div class="jp-id-banner__content">
6249
				<!-- <h3 class="banner-title"><?php _e( 'Something\'s not quite right with your Jetpack connection! Let\'s fix that.', 'jetpack' ); ?></h3> -->
6250
6251
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-1">
6252
					<?php
6253
					// 401 means that this site has been disconnected from wpcom, but the remote site still thinks it's connected.
6254
					if ( 'error_code' == $key && '401' == $errors[ $key ] ) : ?>
6255
						<div class="banner-content">
6256
							<p><?php
6257
								/* translators: %s is a URL */
6258
								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/' );
6259
							?></p>
6260
						</div>
6261
						<div class="jp-btn-group">
6262
							<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a>
6263
							<span class="idc-separator">|</span>
6264
							<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>"><?php _e( 'Deactivate Jetpack', 'jetpack' ); ?></a>
6265
						</div>
6266
					<?php else : ?>
6267
							<div class="banner-content">
6268
							<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>
6269
							</div>
6270
						<div class="jp-btn-group">
6271
							<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>
6272
							<span class="spinner"></span>
6273
						</div>
6274
					<?php endif ; ?>
6275
				</div>
6276
6277
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-2" style="display: none;">
6278
					<div class="banner-content">
6279
						<p><?php printf(
6280
							/* translators: %1$s, %2$s and %3$s are URLs */
6281
							__(
6282
								'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>',
6283
								'jetpack'
6284
							),
6285
							$errors[ $key ],
6286
							(string) get_option( $key ),
6287
							'https://jetpack.com/support/what-does-resetting-the-connection-mean/'
6288
						); ?></p>
6289
					</div>
6290
					<div class="jp-btn-group">
6291
						<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6292
						<a href="#" class="is-dev-env"><?php _e( 'This is a development environment', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6293
						<a href="https://jetpack.com/contact-support/" class="contact-support"><?php _e( 'Submit a support ticket', 'jetpack' ); ?></a>
6294
						<span class="spinner"></span>
6295
					</div>
6296
				</div>
6297
6298
				<div class="jp-id-crisis-success" id="jp-id-crisis-success" style="display: none;">
6299
					<h3 class="success-notice"><?php printf( __( 'Thanks for taking the time to sort things out. We&#039;ve updated our records accordingly!', 'jetpack' ) ); ?></h3>
6300
				</div>
6301
			</div>
6302
		</div>
6303
6304
		<?php
6305
	}
6306
6307
	/**
6308
	 * Maybe Use a .min.css stylesheet, maybe not.
6309
	 *
6310
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6311
	 */
6312
	public static function maybe_min_asset( $url, $path, $plugin ) {
6313
		// Short out on things trying to find actual paths.
6314
		if ( ! $path || empty( $plugin ) ) {
6315
			return $url;
6316
		}
6317
6318
		// Strip out the abspath.
6319
		$base = dirname( plugin_basename( $plugin ) );
6320
6321
		// Short out on non-Jetpack assets.
6322
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6323
			return $url;
6324
		}
6325
6326
		// File name parsing.
6327
		$file              = "{$base}/{$path}";
6328
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6329
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6330
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6331
		$extension         = array_shift( $file_name_parts_r );
6332
6333
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6334
			// Already pointing at the minified version.
6335
			if ( 'min' === $file_name_parts_r[0] ) {
6336
				return $url;
6337
			}
6338
6339
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6340
			if ( file_exists( $min_full_path ) ) {
6341
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6342
			}
6343
		}
6344
6345
		return $url;
6346
	}
6347
6348
	/**
6349
	 * Maybe inlines a stylesheet.
6350
	 *
6351
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6352
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6353
	 *
6354
	 * Attached to `style_loader_tag` filter.
6355
	 *
6356
	 * @param string $tag The tag that would link to the external asset.
6357
	 * @param string $handle The registered handle of the script in question.
6358
	 *
6359
	 * @return string
6360
	 */
6361
	public static function maybe_inline_style( $tag, $handle ) {
6362
		global $wp_styles;
6363
		$item = $wp_styles->registered[ $handle ];
6364
6365
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6366
			return $tag;
6367
		}
6368
6369
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6370
			$href = $matches[1];
6371
			// Strip off query string
6372
			if ( $pos = strpos( $href, '?' ) ) {
6373
				$href = substr( $href, 0, $pos );
6374
			}
6375
			// Strip off fragment
6376
			if ( $pos = strpos( $href, '#' ) ) {
6377
				$href = substr( $href, 0, $pos );
6378
			}
6379
		} else {
6380
			return $tag;
6381
		}
6382
6383
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6384
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6385
			return $tag;
6386
		}
6387
6388
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6389
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6390
			// And this isn't the pass that actually deals with the RTL version...
6391
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6392
				// Short out, as the RTL version will deal with it in a moment.
6393
				return $tag;
6394
			}
6395
		}
6396
6397
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6398
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6399
		if ( $css ) {
6400
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6401
			if ( empty( $item->extra['after'] ) ) {
6402
				wp_add_inline_style( $handle, $css );
6403
			} else {
6404
				array_unshift( $item->extra['after'], $css );
6405
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6406
			}
6407
		}
6408
6409
		return $tag;
6410
	}
6411
6412
	/**
6413
	 * Loads a view file from the views
6414
	 *
6415
	 * Data passed in with the $data parameter will be available in the
6416
	 * template file as $data['value']
6417
	 *
6418
	 * @param string $template - Template file to load
6419
	 * @param array $data - Any data to pass along to the template
6420
	 * @return boolean - If template file was found
6421
	 **/
6422
	public function load_view( $template, $data = array() ) {
6423
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6424
6425
		if( file_exists( $views_dir . $template ) ) {
6426
			require_once( $views_dir . $template );
6427
			return true;
6428
		}
6429
6430
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6431
		return false;
6432
	}
6433
6434
	/**
6435
	 * Sends a ping to the Jetpack servers to toggle on/off remote portions
6436
	 * required by some modules.
6437
	 *
6438
	 * @param string $module_slug
6439
	 */
6440
	public function toggle_module_on_wpcom( $module_slug ) {
6441
		Jetpack::init()->sync->register( 'noop' );
6442
6443
		if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
6444
			self::check_privacy( $module_slug );
6445
		}
6446
6447
	}
6448
6449
	/**
6450
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6451
	 */
6452
	public function deprecated_hooks() {
6453
		global $wp_filter;
6454
6455
		/*
6456
		 * Format:
6457
		 * deprecated_filter_name => replacement_name
6458
		 *
6459
		 * If there is no replacement us null for replacement_name
6460
		 */
6461
		$deprecated_list = array(
6462
			'jetpack_bail_on_shortcode'                => 'jetpack_shortcodes_to_include',
6463
			'wpl_sharing_2014_1'                       => null,
6464
			'jetpack-tools-to-include'                 => 'jetpack_tools_to_include',
6465
			'jetpack_identity_crisis_options_to_check' => null,
6466
		);
6467
6468
		// This is a silly loop depth. Better way?
6469
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6470
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
6471
				foreach( $wp_filter[$hook] AS $func => $values ) {
6472
					foreach( $values AS $hooked ) {
6473
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
6474
					}
6475
				}
6476
			}
6477
		}
6478
	}
6479
6480
	/**
6481
	 * Converts any url in a stylesheet, to the correct absolute url.
6482
	 *
6483
	 * Considerations:
6484
	 *  - Normal, relative URLs     `feh.png`
6485
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6486
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6487
	 *  - Absolute URLs             `http://domain.com/feh.png`
6488
	 *  - Domain root relative URLs `/feh.png`
6489
	 *
6490
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6491
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6492
	 *
6493
	 * @return mixed|string
6494
	 */
6495
	public static function absolutize_css_urls( $css, $css_file_url ) {
6496
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6497
		$css_dir = dirname( $css_file_url );
6498
		$p       = parse_url( $css_dir );
6499
		$domain  = sprintf(
6500
					'%1$s//%2$s%3$s%4$s',
6501
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6502
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6503
					$p['host'],
6504
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6505
				);
6506
6507
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6508
			$find = $replace = array();
6509
			foreach ( $matches as $match ) {
6510
				$url = trim( $match['path'], "'\" \t" );
6511
6512
				// If this is a data url, we don't want to mess with it.
6513
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6514
					continue;
6515
				}
6516
6517
				// If this is an absolute or protocol-agnostic url,
6518
				// we don't want to mess with it.
6519
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6520
					continue;
6521
				}
6522
6523
				switch ( substr( $url, 0, 1 ) ) {
6524
					case '/':
6525
						$absolute = $domain . $url;
6526
						break;
6527
					default:
6528
						$absolute = $css_dir . '/' . $url;
6529
				}
6530
6531
				$find[]    = $match[0];
6532
				$replace[] = sprintf( 'url("%s")', $absolute );
6533
			}
6534
			$css = str_replace( $find, $replace, $css );
6535
		}
6536
6537
		return $css;
6538
	}
6539
6540
	/**
6541
	 * This method checks to see if SSL is required by the site in
6542
	 * order to visit it in some way other than only setting the
6543
	 * https value in the home or siteurl values.
6544
	 *
6545
	 * @since 3.2
6546
	 * @return boolean
6547
	 **/
6548
	private function is_ssl_required_to_visit_site() {
6549
		global $wp_version;
6550
		$ssl = is_ssl();
6551
6552
		if ( force_ssl_admin() ) {
6553
			$ssl = true;
6554
		}
6555
		return $ssl;
6556
	}
6557
6558
	/**
6559
	 * This methods removes all of the registered css files on the frontend
6560
	 * from Jetpack in favor of using a single file. In effect "imploding"
6561
	 * all the files into one file.
6562
	 *
6563
	 * Pros:
6564
	 * - Uses only ONE css asset connection instead of 15
6565
	 * - Saves a minimum of 56k
6566
	 * - Reduces server load
6567
	 * - Reduces time to first painted byte
6568
	 *
6569
	 * Cons:
6570
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6571
	 *		should not cause any issues with themes.
6572
	 * - Plugins/themes dequeuing styles no longer do anything. See
6573
	 *		jetpack_implode_frontend_css filter for a workaround
6574
	 *
6575
	 * For some situations developers may wish to disable css imploding and
6576
	 * instead operate in legacy mode where each file loads seperately and
6577
	 * can be edited individually or dequeued. This can be accomplished with
6578
	 * the following line:
6579
	 *
6580
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6581
	 *
6582
	 * @since 3.2
6583
	 **/
6584
	public function implode_frontend_css( $travis_test = false ) {
6585
		$do_implode = true;
6586
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6587
			$do_implode = false;
6588
		}
6589
6590
		/**
6591
		 * Allow CSS to be concatenated into a single jetpack.css file.
6592
		 *
6593
		 * @since 3.2.0
6594
		 *
6595
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6596
		 */
6597
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6598
6599
		// Do not use the imploded file when default behaviour was altered through the filter
6600
		if ( ! $do_implode ) {
6601
			return;
6602
		}
6603
6604
		// We do not want to use the imploded file in dev mode, or if not connected
6605
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6606
			if ( ! $travis_test ) {
6607
				return;
6608
			}
6609
		}
6610
6611
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6612
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6613
			return;
6614
		}
6615
6616
		/*
6617
		 * Now we assume Jetpack is connected and able to serve the single
6618
		 * file.
6619
		 *
6620
		 * In the future there will be a check here to serve the file locally
6621
		 * or potentially from the Jetpack CDN
6622
		 *
6623
		 * For now:
6624
		 * - Enqueue a single imploded css file
6625
		 * - Zero out the style_loader_tag for the bundled ones
6626
		 * - Be happy, drink scotch
6627
		 */
6628
6629
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6630
6631
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6632
6633
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6634
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6635
	}
6636
6637
	function concat_remove_style_loader_tag( $tag, $handle ) {
6638
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6639
			$tag = '';
6640
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6641
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6642
			}
6643
		}
6644
6645
		return $tag;
6646
	}
6647
6648
	/*
6649
	 * Check the heartbeat data
6650
	 *
6651
	 * Organizes the heartbeat data by severity.  For example, if the site
6652
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6653
	 *
6654
	 * Data will be added to "caution" array, if it either:
6655
	 *  - Out of date Jetpack version
6656
	 *  - Out of date WP version
6657
	 *  - Out of date PHP version
6658
	 *
6659
	 * $return array $filtered_data
6660
	 */
6661
	public static function jetpack_check_heartbeat_data() {
6662
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6663
6664
		$good    = array();
6665
		$caution = array();
6666
		$bad     = array();
6667
6668
		foreach ( $raw_data as $stat => $value ) {
6669
6670
			// Check jetpack version
6671
			if ( 'version' == $stat ) {
6672
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6673
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6674
					continue;
6675
				}
6676
			}
6677
6678
			// Check WP version
6679
			if ( 'wp-version' == $stat ) {
6680
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6681
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6682
					continue;
6683
				}
6684
			}
6685
6686
			// Check PHP version
6687
			if ( 'php-version' == $stat ) {
6688
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6689
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6690
					continue;
6691
				}
6692
			}
6693
6694
			// Check ID crisis
6695
			if ( 'identitycrisis' == $stat ) {
6696
				if ( 'yes' == $value ) {
6697
					$bad[ $stat ] = $value;
6698
					continue;
6699
				}
6700
			}
6701
6702
			// The rest are good :)
6703
			$good[ $stat ] = $value;
6704
		}
6705
6706
		$filtered_data = array(
6707
			'good'    => $good,
6708
			'caution' => $caution,
6709
			'bad'     => $bad
6710
		);
6711
6712
		return $filtered_data;
6713
	}
6714
6715
6716
	/*
6717
	 * This method is used to organize all options that can be reset
6718
	 * without disconnecting Jetpack.
6719
	 *
6720
	 * It is used in class.jetpack-cli.php to reset options
6721
	 *
6722
	 * @return array of options to delete.
6723
	 */
6724
	public static function get_jetpack_options_for_reset() {
6725
		$jetpack_options            = Jetpack_Options::get_option_names();
6726
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6727
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6728
6729
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6730
6731
		// A manual build of the wp options
6732
		$wp_options = array(
6733
			'sharing-options',
6734
			'disabled_likes',
6735
			'disabled_reblogs',
6736
			'jetpack_comments_likes_enabled',
6737
			'wp_mobile_excerpt',
6738
			'wp_mobile_featured_images',
6739
			'wp_mobile_app_promos',
6740
			'stats_options',
6741
			'stats_dashboard_widget',
6742
			'safecss_preview_rev',
6743
			'safecss_rev',
6744
			'safecss_revision_migrated',
6745
			'nova_menu_order',
6746
			'jetpack_portfolio',
6747
			'jetpack_portfolio_posts_per_page',
6748
			'jetpack_testimonial',
6749
			'jetpack_testimonial_posts_per_page',
6750
			'wp_mobile_custom_css',
6751
			'sharedaddy_disable_resources',
6752
			'sharing-options',
6753
			'sharing-services',
6754
			'site_icon_temp_data',
6755
			'featured-content',
6756
			'site_logo',
6757
		);
6758
6759
		// Flag some Jetpack options as unsafe
6760
		$unsafe_options = array(
6761
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6762
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6763
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6764
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6765
6766
			// non_compact
6767
			'activated',
6768
6769
			// private
6770
			'register',
6771
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6772
			'user_token',                  // (string) The User Token of this site. (deprecated)
6773
			'user_tokens'
6774
		);
6775
6776
		// Remove the unsafe Jetpack options
6777
		foreach ( $unsafe_options as $unsafe_option ) {
6778
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6779
				unset( $all_jp_options[ $key ] );
6780
			}
6781
		}
6782
6783
		$options = array(
6784
			'jp_options' => $all_jp_options,
6785
			'wp_options' => $wp_options
6786
		);
6787
6788
		return $options;
6789
	}
6790
6791
	/**
6792
	 * Check if an option of a Jetpack module has been updated.
6793
	 *
6794
	 * If any module option has been updated before Jump Start has been dismissed,
6795
	 * update the 'jumpstart' option so we can hide Jump Start.
6796
	 *
6797
	 * @param string $option_name
6798
	 *
6799
	 * @return bool
6800
	 */
6801
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6802
		// Bail if Jump Start has already been dismissed
6803
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6804
			return false;
6805
		}
6806
6807
		$jetpack = Jetpack::init();
6808
6809
		// Manual build of module options
6810
		$option_names = self::get_jetpack_options_for_reset();
6811
6812
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6813
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6814
6815
			//Jump start is being dismissed send data to MC Stats
6816
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6817
6818
			$jetpack->do_stats( 'server_side' );
6819
		}
6820
6821
	}
6822
6823
	/*
6824
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6825
	 * so we can bring them directly to their site in calypso.
6826
	 *
6827
	 * @param string | url
6828
	 * @return string | url without the guff
6829
	 */
6830
	public static function build_raw_urls( $url ) {
6831
		$strip_http = '/.*?:\/\//i';
6832
		$url = preg_replace( $strip_http, '', $url  );
6833
		$url = str_replace( '/', '::', $url );
6834
		return $url;
6835
	}
6836
6837
	/**
6838
	 * Stores and prints out domains to prefetch for page speed optimization.
6839
	 *
6840
	 * @param mixed $new_urls
6841
	 */
6842
	public static function dns_prefetch( $new_urls = null ) {
6843
		static $prefetch_urls = array();
6844
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6845
			echo "\r\n";
6846
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6847
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6848
			}
6849
		} elseif ( ! empty( $new_urls ) ) {
6850
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6851
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6852
			}
6853
			foreach ( (array) $new_urls as $this_new_url ) {
6854
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6855
			}
6856
			$prefetch_urls = array_unique( $prefetch_urls );
6857
		}
6858
	}
6859
6860
	public function wp_dashboard_setup() {
6861
		if ( self::is_active() ) {
6862
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6863
			$widget_title = __( 'Site Stats', 'jetpack' );
6864
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6865
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6866
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6867
		}
6868
6869
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6870
			wp_add_dashboard_widget(
6871
				'jetpack_summary_widget',
6872
				$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...
6873
				array( __CLASS__, 'dashboard_widget' )
6874
			);
6875
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6876
6877
			// If we're inactive and not in development mode, sort our box to the top.
6878
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6879
				global $wp_meta_boxes;
6880
6881
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6882
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6883
6884
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6885
			}
6886
		}
6887
	}
6888
6889
	/**
6890
	 * @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...
6891
	 * @return mixed
6892
	 */
6893
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6894
		if ( ! is_array( $sorted ) ) {
6895
			return $sorted;
6896
		}
6897
6898
		foreach ( $sorted as $box_context => $ids ) {
6899
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6900
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6901
				continue;
6902
			}
6903
6904
			$ids_array = explode( ',', $ids );
6905
			$key = array_search( 'dashboard_stats', $ids_array );
6906
6907
			if ( false !== $key ) {
6908
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6909
				$ids_array[ $key ] = 'jetpack_summary_widget';
6910
				$sorted[ $box_context ] = implode( ',', $ids_array );
6911
				// We've found it, stop searching, and just return.
6912
				break;
6913
			}
6914
		}
6915
6916
		return $sorted;
6917
	}
6918
6919
	public static function dashboard_widget() {
6920
		/**
6921
		 * Fires when the dashboard is loaded.
6922
		 *
6923
		 * @since 3.4.0
6924
		 */
6925
		do_action( 'jetpack_dashboard_widget' );
6926
	}
6927
6928
	public static function dashboard_widget_footer() {
6929
		?>
6930
		<footer>
6931
6932
		<div class="protect">
6933
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6934
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6935
				<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>
6936
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6937
				<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' ); ?>">
6938
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6939
				</a>
6940
			<?php else : ?>
6941
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6942
			<?php endif; ?>
6943
		</div>
6944
6945
		<div class="akismet">
6946
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6947
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6948
				<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>
6949 View Code Duplication
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6950
				<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">
6951
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6952
				</a>
6953
			<?php else : ?>
6954
				<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>
6955
			<?php endif; ?>
6956
		</div>
6957
6958
6959 View Code Duplication
		<?php if ( ! current_user_can( 'edit_posts' ) && self::is_user_connected() ) : ?>
6960
			<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>
6961
		<?php endif; ?>
6962
6963
		</footer>
6964
		<?php
6965
	}
6966
6967
	public function dashboard_widget_connect_to_wpcom() {
6968
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6969
			return;
6970
		}
6971
		?>
6972
		<div class="wpcom-connect">
6973
			<div class="jp-emblem">
6974
			<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">
6975
				<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"/>
6976
			</svg>
6977
			</div>
6978
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6979
			<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>
6980
6981
			<div class="actions">
6982
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6983
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6984
				</a>
6985
			</div>
6986
		</div>
6987
		<?php
6988
	}
6989
6990
	/*
6991
	 * A graceful transition to using Core's site icon.
6992
	 *
6993
	 * All of the hard work has already been done with the image
6994
	 * in all_done_page(). All that needs to be done now is update
6995
	 * the option and display proper messaging.
6996
	 *
6997
	 * @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...
6998
	 *
6999
	 * @since 3.6.1
7000
	 *
7001
	 * @return bool false = Core's icon not available || true = Core's icon is available
7002
	 */
7003
	public static function jetpack_site_icon_available_in_core() {
7004
		global $wp_version;
7005
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
7006
7007
		if ( ! $core_icon_available ) {
7008
			return false;
7009
		}
7010
7011
		// No need for Jetpack's site icon anymore if core's is already set
7012
		if ( has_site_icon() ) {
7013
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
7014
				Jetpack::log( 'deactivate', 'site-icon' );
7015
				Jetpack::deactivate_module( 'site-icon' );
7016
			}
7017
			return true;
7018
		}
7019
7020
		// Transfer Jetpack's site icon to use core.
7021
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
7022
		if ( $site_icon_id ) {
7023
			// Update core's site icon
7024
			update_option( 'site_icon', $site_icon_id );
7025
7026
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
7027
			delete_option( 'site_icon_id' );
7028
		}
7029
7030
		// No need for Jetpack's site icon anymore
7031
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
7032
			Jetpack::log( 'deactivate', 'site-icon' );
7033
			Jetpack::deactivate_module( 'site-icon' );
7034
		}
7035
7036
		return true;
7037
	}
7038
7039
}
7040