Completed
Push — add/connect-jp-remotely ( bc025e...307eed )
by
unknown
08:32
created

Jetpack::refresh_theme_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 2

Duplication

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

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

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	static $instance = false;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $instance.

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

class A {
    var $property;
}

the property is implicitly global.

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

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