Completed
Push — add/sync-action ( cda3e4...59c977 )
by
unknown
24:57 queued 24:46
created

class.jetpack.php (14 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
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();
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;
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			self::$instance = new Jetpack;
311
312
			self::$instance->plugin_upgrade();
313
314
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
315
316
		}
317
318
		return self::$instance;
319
	}
320
321
	/**
322
	 * Must never be called statically
323
	 */
324
	function plugin_upgrade() {
325
		if ( Jetpack::is_active() ) {
326
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
327
			if ( JETPACK__VERSION != $version ) {
328
329
				// Check which active modules actually exist and remove others from active_modules list
330
				$unfiltered_modules = Jetpack::get_active_modules();
331
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
332
				if ( array_diff( $unfiltered_modules, $modules ) ) {
333
					Jetpack_Options::update_option( 'active_modules', $modules );
334
				}
335
336
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
337
				/**
338
				 * Fires when synchronizing all registered options and constants.
339
				 *
340
				 * @since 3.3.0
341
				 */
342
				do_action( 'jetpack_sync_all_registered_options' );
343
			}
344
		}
345
	}
346
347
	static function activate_manage( ) {
348
349
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
350
			self::activate_module( 'manage', false, false );
351
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
352
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
353
		}
354
355
	}
356
357
	/**
358
	 * Constructor.  Initializes WordPress hooks
359
	 */
360
	private function __construct() {
361
		/*
362
		 * Check for and alert any deprecated hooks
363
		 */
364
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
365
366
		/**
367
		 * We need sync object even in Multisite mode
368
		 */
369
		$this->sync = new Jetpack_Sync;
370
371
		/**
372
		 * Trigger a wp_version sync when updating WP versions
373
		 **/
374
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
375
		$this->sync->mock_option( 'wp_version', array( 'Jetpack', 'get_wp_version' ) );
376
377
		add_action( 'init', array( $this, 'sync_update_data') );
378
		add_action( 'init', array( $this, 'sync_theme_data' ) );
379
380
		/*
381
		 * Load things that should only be in Network Admin.
382
		 *
383
		 * For now blow away everything else until a more full
384
		 * understanding of what is needed at the network level is
385
		 * available
386
		 */
387
		if( is_multisite() ) {
388
			Jetpack_Network::init();
389
390
			// Only sync this info if we are on a multi site
391
			// @since  3.7
392
			$this->sync->mock_option( 'network_name', array( 'Jetpack', 'network_name' ) );
393
			$this->sync->mock_option( 'network_allow_new_registrations', array( 'Jetpack', 'network_allow_new_registrations' ) );
394
			$this->sync->mock_option( 'network_add_new_users', array( 'Jetpack', 'network_add_new_users' ) );
395
			$this->sync->mock_option( 'network_site_upload_space', array( 'Jetpack', 'network_site_upload_space' ) );
396
			$this->sync->mock_option( 'network_upload_file_types', array( 'Jetpack', 'network_upload_file_types' ) );
397
			$this->sync->mock_option( 'network_enable_administration_menus', array( 'Jetpack', 'network_enable_administration_menus' ) );
398
399
			if( is_network_admin() ) {
400
				// Sync network site data if it is updated or not.
401
				add_action( 'update_wpmu_options', array( $this, 'update_jetpack_network_settings' ) );
402
				return; // End here to prevent single site actions from firing
403
			}
404
		}
405
406
407
		$theme_slug = get_option( 'stylesheet' );
408
409
410
		// Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
411
		// We access the "internal" method here only because the Jetpack object isn't instantiated yet
412
		$this->sync->options(
413
			JETPACK__PLUGIN_DIR . 'jetpack.php',
414
			'home',
415
			'siteurl',
416
			'blogname',
417
			'gmt_offset',
418
			'timezone_string',
419
			'security_report',
420
			'stylesheet',
421
			"theme_mods_{$theme_slug}",
422
			'jetpack_sync_non_public_post_stati',
423
			'jetpack_options',
424
			'site_icon', // (int) - ID of core's Site Icon attachment ID
425
			'default_post_format',
426
			'default_category',
427
			'large_size_w',
428
			'large_size_h',
429
			'thumbnail_size_w',
430
			'thumbnail_size_h',
431
			'medium_size_w',
432
			'medium_size_h',
433
			'thumbnail_crop',
434
			'image_default_link_type'
435
		);
436
437
		foreach( Jetpack_Options::get_option_names( 'non-compact' ) as $option ) {
438
			$this->sync->options( __FILE__, 'jetpack_' . $option );
439
		}
440
441
		/**
442
		 * Sometimes you want to sync data to .com without adding options to .org sites.
443
		 * The mock option allows you to do just that.
444
		 */
445
		$this->sync->mock_option( 'is_main_network',   array( $this, 'is_main_network_option' ) );
446
		$this->sync->mock_option( 'is_multi_site', array( $this, 'is_multisite' ) );
447
		$this->sync->mock_option( 'main_network_site', array( $this, 'jetpack_main_network_site_option' ) );
448
		$this->sync->mock_option( 'single_user_site', array( 'Jetpack', 'is_single_user_site' ) );
449
		$this->sync->mock_option( 'stat_data', array( $this, 'get_stat_data' ) );
450
451
		$this->sync->mock_option( 'has_file_system_write_access', array( 'Jetpack', 'file_system_write_access' ) );
452
		$this->sync->mock_option( 'is_version_controlled', array( 'Jetpack', 'is_version_controlled' ) );
453
		$this->sync->mock_option( 'max_upload_size', 'wp_max_upload_size' );
454
		$this->sync->mock_option( 'content_width', array( 'Jetpack', 'get_content_width' ) );
455
456
		/**
457
		 * Trigger an update to the main_network_site when we update the blogname of a site.
458
		 *
459
		 */
460
		add_action( 'update_option_siteurl', array( $this, 'update_jetpack_main_network_site_option' ) );
461
462
		add_action( 'update_option', array( $this, 'log_settings_change' ), 10, 3 );
463
464
		// Update the settings everytime the we register a new user to the site or we delete a user.
465
		add_action( 'user_register', array( $this, 'is_single_user_site_invalidate' ) );
466
		add_action( 'deleted_user', array( $this, 'is_single_user_site_invalidate' ) );
467
468
		// Unlink user before deleting the user from .com
469
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
470
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
471
472
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
473
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
474
475
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
476
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
477
478
			$this->require_jetpack_authentication();
479
480
			if ( Jetpack::is_active() ) {
481
				// Hack to preserve $HTTP_RAW_POST_DATA
482
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
483
484
				$signed = $this->verify_xml_rpc_signature();
485
				if ( $signed && ! is_wp_error( $signed ) ) {
486
					// The actual API methods.
487
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
488
				} else {
489
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
490
					// active Jetpack connection, so that additional users can link their account.
491
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
492
				}
493
			} else {
494
				// The bootstrap API methods.
495
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
496
			}
497
498
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
499
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
500
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
501
			$this->require_jetpack_authentication();
502
			$this->add_remote_request_handlers();
503
		} else {
504
			if ( Jetpack::is_active() ) {
505
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
506
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
507
			}
508
		}
509
510
		if ( Jetpack::is_active() ) {
511
			Jetpack_Heartbeat::init();
512
		}
513
514
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
515
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
516
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
517
		}
518
519
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
520
521
		add_action( 'admin_init', array( $this, 'admin_init' ) );
522
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
523
524
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
525
526
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
527
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
528
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
529
530
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
531
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
532
533
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
534
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
535
536
		// Identity Crisis AJAX callback function
537
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
538
539
		// JITM AJAX callback function
540
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
541
542
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
543
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
544
545
		// Universal ajax callback for all tracking events triggered via js
546
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
547
548
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
549
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
550
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
551
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
552
553
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
554
555
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
556
557
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
558
559
		/**
560
		 * These actions run checks to load additional files.
561
		 * They check for external files or plugins, so they need to run as late as possible.
562
		 */
563
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
564
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
565
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
566
567
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
568
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
569
570
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
571
572
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
573
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
574
575
		// A filter to control all just in time messages
576
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
577
578
		/**
579
		 * This is the hack to concatinate all css files into one.
580
		 * For description and reasoning see the implode_frontend_css method
581
		 *
582
		 * Super late priority so we catch all the registered styles
583
		 */
584
		if( !is_admin() ) {
585
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
586
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
587
		}
588
589
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
590
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
591
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
592
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
593
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
594
595
	}
596
597
	/*
598
	 * Make sure any site icon added to core can get
599
	 * synced back to dotcom, so we can display it there.
600
	 */
601
	function jetpack_sync_core_icon() {
602
		if ( function_exists( 'get_site_icon_url' ) ) {
603
			$url = get_site_icon_url();
604
		} else {
605
			return;
606
		}
607
608
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
609
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
610
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
611
			// This is the option that is synced with dotcom
612
			Jetpack_Options::update_option( 'site_icon_url', $url );
613
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
614
			Jetpack_Options::delete_option( 'site_icon_url' );
615
		}
616
	}
617
618
	function jetpack_admin_ajax_tracks_callback() {
619
		// Check for nonce
620
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
621
			wp_die( 'Permissions check failed.' );
622
		}
623
624
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
625
			wp_die( 'No valid event name or type.' );
626
		}
627
628
		$tracks_data = array();
629
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
630
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
631
		}
632
633
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
634
		wp_send_json_success();
635
		wp_die();
636
	}
637
638
	function jetpack_admin_ajax_callback() {
639
		// Check for nonce
640 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
641
			wp_die( 'permissions check failed' );
642
		}
643
644
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
645
			$slug = $_REQUEST['thisModuleSlug'];
646
647
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
648
				wp_die( 'That is not a Jetpack module slug' );
649
			}
650
651
			if ( Jetpack::is_module_active( $slug ) ) {
652
				Jetpack::deactivate_module( $slug );
653
			} else {
654
				Jetpack::activate_module( $slug, false, false );
655
			}
656
657
			$modules = Jetpack_Admin::init()->get_modules();
658
			echo json_encode( $modules[ $slug ] );
659
660
			exit;
661
		}
662
663
		wp_die();
664
	}
665
666
	/*
667
	 * Sometimes we need to refresh the data,
668
	 * especially if the page is visited via a 'history'
669
	 * event like back/forward
670
	 */
671
	function jetpack_admin_ajax_refresh_data() {
672
		// Check for nonce
673 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
674
			wp_die( 'permissions check failed' );
675
		}
676
677
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
678
			$modules = Jetpack_Admin::init()->get_modules();
679
			echo json_encode( $modules );
680
			exit;
681
		}
682
683
		wp_die();
684
	}
685
686
	/**
687
	 * The callback for the JITM ajax requests.
688
	 */
689
	function jetpack_jitm_ajax_callback() {
690
		// Check for nonce
691
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
692
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
693
		}
694
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
695
			$module_slug = $_REQUEST['jitmModule'];
696
			Jetpack::log( 'activate', $module_slug );
697
			Jetpack::activate_module( $module_slug, false, false );
698
			Jetpack::state( 'message', 'no_message' );
699
700
			//A Jetpack module is being activated through a JITM, track it
701
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
702
			$this->do_stats( 'server_side' );
703
704
			wp_send_json_success();
705
		}
706
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
707
			// get the hide_jitm options array
708
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
709
			$module_slug = $_REQUEST['jitmModule'];
710
711
			if( ! $jetpack_hide_jitm ) {
712
				$jetpack_hide_jitm = array(
713
					$module_slug => 'hide'
714
				);
715
			} else {
716
				$jetpack_hide_jitm[$module_slug] = 'hide';
717
			}
718
719
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
720
721
			//jitm is being dismissed forever, track it
722
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
723
			$this->do_stats( 'server_side' );
724
725
			wp_send_json_success();
726
		}
727 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
728
			$module_slug = $_REQUEST['jitmModule'];
729
730
			// User went to WordPress.com, track this
731
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
732
			$this->do_stats( 'server_side' );
733
734
			wp_send_json_success();
735
		}
736 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
737
			$track = $_REQUEST['jitmModule'];
738
739
			// User is viewing JITM, track it.
740
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
741
			$this->do_stats( 'server_side' );
742
743
			wp_send_json_success();
744
		}
745
	}
746
747
	/**
748
	 * If there are any stats that need to be pushed, but haven't been, push them now.
749
	 */
750
	function __destruct() {
751
		if ( ! empty( $this->stats ) ) {
752
			$this->do_stats( 'server_side' );
753
		}
754
	}
755
756
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
757
		switch( $cap ) {
758
			case 'jetpack_connect' :
759
			case 'jetpack_reconnect' :
760
				if ( Jetpack::is_development_mode() ) {
761
					$caps = array( 'do_not_allow' );
762
					break;
763
				}
764
				/**
765
				 * Pass through. If it's not development mode, these should match disconnect.
766
				 * Let users disconnect if it's development mode, just in case things glitch.
767
				 */
768
			case 'jetpack_disconnect' :
769
				/**
770
				 * In multisite, can individual site admins manage their own connection?
771
				 *
772
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
773
				 */
774
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
775
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
776
						/**
777
						 * We need to update the option name -- it's terribly unclear which
778
						 * direction the override goes.
779
						 *
780
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
781
						 */
782
						$caps = array( 'do_not_allow' );
783
						break;
784
					}
785
				}
786
787
				$caps = array( 'manage_options' );
788
				break;
789
			case 'jetpack_manage_modules' :
790
			case 'jetpack_activate_modules' :
791
			case 'jetpack_deactivate_modules' :
792
				$caps = array( 'manage_options' );
793
				break;
794
			case 'jetpack_configure_modules' :
795
				$caps = array( 'manage_options' );
796
				break;
797
			case 'jetpack_network_admin_page':
798
			case 'jetpack_network_settings_page':
799
				$caps = array( 'manage_network_plugins' );
800
				break;
801
			case 'jetpack_network_sites_page':
802
				$caps = array( 'manage_sites' );
803
				break;
804
			case 'jetpack_admin_page' :
805
				if ( Jetpack::is_development_mode() ) {
806
					$caps = array( 'manage_options' );
807
					break;
808
				}
809
810
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
811
				if ( ! current_user_can( 'edit_posts' ) ) {
812
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
813
						// We need this in order to unlink the user.
814
						$this->admin_page_load();
815
					}
816
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
817
						$caps = array( 'do_not_allow' );
818
						break;
819
					}
820
				}
821
822
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
823
					$caps = array( 'do_not_allow' );
824
					break;
825
				}
826
				/**
827
				 * Pass through. If it's not development mode, these should match the admin page.
828
				 * Let users disconnect if it's development mode, just in case things glitch.
829
				 */
830
			case 'jetpack_connect_user' :
831
				if ( Jetpack::is_development_mode() ) {
832
					$caps = array( 'do_not_allow' );
833
					break;
834
				}
835
				$caps = array( 'read' );
836
				break;
837
		}
838
		return $caps;
839
	}
840
841
	function require_jetpack_authentication() {
842
		// Don't let anyone authenticate
843
		$_COOKIE = array();
844
		remove_all_filters( 'authenticate' );
845
846
		/**
847
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
848
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
849
		 * generate false-positives.
850
		 */
851
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
852
853
		if ( Jetpack::is_active() ) {
854
			// Allow Jetpack authentication
855
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
856
		}
857
	}
858
859
	/**
860
	 * Load language files
861
	 * @action plugins_loaded
862
	 */
863
	public static function plugin_textdomain() {
864
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
865
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
866
	}
867
868
	/**
869
	 * Register assets for use in various modules and the Jetpack admin page.
870
	 *
871
	 * @uses wp_script_is, wp_register_script, plugins_url
872
	 * @action wp_loaded
873
	 * @return null
874
	 */
875
	public function register_assets() {
876 View Code Duplication
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
877
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
878
		}
879
880 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
881
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
882
		}
883
884 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
885
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
886
		}
887
888 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
889
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
890
		}
891
892
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
893
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
894
895
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
896
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
897
			if ( ! is_numeric( $fb_app_id ) ) {
898
				$fb_app_id = '';
899
			}
900
			wp_localize_script(
901
				'jetpack-facebook-embed',
902
				'jpfbembed',
903
				array(
904
					'appid' => $fb_app_id,
905
					'locale' => $this->get_locale(),
906
				)
907
			);
908
		}
909
910
		/**
911
		 * As jetpack_register_genericons is by default fired off a hook,
912
		 * the hook may have already fired by this point.
913
		 * So, let's just trigger it manually.
914
		 */
915
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
916
		jetpack_register_genericons();
917
918 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
919
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
920
	}
921
922
	/**
923
	 * Guess locale from language code.
924
	 *
925
	 * @param string $lang Language code.
926
	 * @return string|bool
927
	 */
928
	function guess_locale_from_lang( $lang ) {
929
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
930
			return 'en_US';
931
		}
932
933
		if ( ! class_exists( 'GP_Locales' ) ) {
934
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
935
				return false;
936
			}
937
938
			require JETPACK__GLOTPRESS_LOCALES_PATH;
939
		}
940
941
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
942
			// WP.com: get_locale() returns 'it'
943
			$locale = GP_Locales::by_slug( $lang );
944
		} else {
945
			// Jetpack: get_locale() returns 'it_IT';
946
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
947
		}
948
949
		if ( ! $locale ) {
950
			return false;
951
		}
952
953
		if ( empty( $locale->facebook_locale ) ) {
954
			if ( empty( $locale->wp_locale ) ) {
955
				return false;
956
			} else {
957
				// Facebook SDK is smart enough to fall back to en_US if a
958
				// locale isn't supported. Since supported Facebook locales
959
				// can fall out of sync, we'll attempt to use the known
960
				// wp_locale value and rely on said fallback.
961
				return $locale->wp_locale;
962
			}
963
		}
964
965
		return $locale->facebook_locale;
966
	}
967
968
	/**
969
	 * Get the locale.
970
	 *
971
	 * @return string|bool
972
	 */
973
	function get_locale() {
974
		$locale = $this->guess_locale_from_lang( get_locale() );
975
976
		if ( ! $locale ) {
977
			$locale = 'en_US';
978
		}
979
980
		return $locale;
981
	}
982
983
	/**
984
	 * Device Pixels support
985
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
986
	 */
987
	function devicepx() {
988
		if ( Jetpack::is_active() ) {
989
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
990
		}
991
	}
992
993
	/**
994
	 * Return the network_site_url so that .com knows what network this site is a part of.
995
	 * @param  bool $option
996
	 * @return string
997
	 */
998
	public function jetpack_main_network_site_option( $option ) {
999
		return network_site_url();
1000
	}
1001
	/**
1002
	 * Network Name.
1003
	 */
1004
	static function network_name( $option = null ) {
1005
		global $current_site;
1006
		return $current_site->site_name;
1007
	}
1008
	/**
1009
	 * Does the network allow new user and site registrations.
1010
	 * @return string
1011
	 */
1012
	static function network_allow_new_registrations( $option = null ) {
1013
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1014
	}
1015
	/**
1016
	 * Does the network allow admins to add new users.
1017
	 * @return boolian
1018
	 */
1019
	static function network_add_new_users( $option = null ) {
1020
		return (bool) get_site_option( 'add_new_users' );
1021
	}
1022
	/**
1023
	 * File upload psace left per site in MB.
1024
	 *  -1 means NO LIMIT.
1025
	 * @return number
1026
	 */
1027
	static function network_site_upload_space( $option = null ) {
1028
		// value in MB
1029
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1030
	}
1031
1032
	/**
1033
	 * Network allowed file types.
1034
	 * @return string
1035
	 */
1036
	static function network_upload_file_types( $option = null ) {
1037
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1038
	}
1039
1040
	/**
1041
	 * Maximum file upload size set by the network.
1042
	 * @return number
1043
	 */
1044
	static function network_max_upload_file_size( $option = null ) {
1045
		// value in KB
1046
		return get_site_option( 'fileupload_maxk', 300 );
1047
	}
1048
1049
	/**
1050
	 * Lets us know if a site allows admins to manage the network.
1051
	 * @return array
1052
	 */
1053
	static function network_enable_administration_menus( $option = null ) {
1054
		return get_site_option( 'menu_items' );
1055
	}
1056
1057
	/**
1058
	 * Return whether we are dealing with a multi network setup or not.
1059
	 * The reason we are type casting this is because we want to avoid the situation where
1060
	 * the result is false since when is_main_network_option return false it cases
1061
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1062
	 * database which could be set to anything as opposed to what this function returns.
1063
	 * @param  bool  $option
1064
	 *
1065
	 * @return boolean
1066
	 */
1067
	public function is_main_network_option( $option ) {
1068
		// return '1' or ''
1069
		return (string) (bool) Jetpack::is_multi_network();
1070
	}
1071
1072
	/**
1073
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1074
	 *
1075
	 * @param  string  $option
1076
	 * @return boolean
1077
	 */
1078
	public function is_multisite( $option ) {
1079
		return (string) (bool) is_multisite();
1080
	}
1081
1082
	/**
1083
	 * Implemented since there is no core is multi network function
1084
	 * Right now there is no way to tell if we which network is the dominant network on the system
1085
	 *
1086
	 * @since  3.3
1087
	 * @return boolean
1088
	 */
1089
	public static function is_multi_network() {
1090
		global  $wpdb;
1091
1092
		// if we don't have a multi site setup no need to do any more
1093
		if ( ! is_multisite() ) {
1094
			return false;
1095
		}
1096
1097
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1098
		if ( $num_sites > 1 ) {
1099
			return true;
1100
		} else {
1101
			return false;
1102
		}
1103
	}
1104
1105
	/**
1106
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1107
	 * @return null
1108
	 */
1109
	function update_jetpack_main_network_site_option() {
1110
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1111
		/**
1112
		 * Fires when the site URL is updated.
1113
		 * Determines if the site is the main site of a Mulitiste network.
1114
		 *
1115
		 * @since 3.3.0
1116
		 *
1117
		 * @param string jetpack_main_network_site.
1118
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1119
		 */
1120
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1121
		/**
1122
		 * Fires when the site URL is updated.
1123
		 * Determines if the is part of a multi network.
1124
		 *
1125
		 * @since 3.3.0
1126
		 *
1127
		 * @param string jetpack_is_main_network.
1128
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1129
		 */
1130
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1131
		/**
1132
		 * Fires when the site URL is updated.
1133
		 * Determines if the site is part of a multisite network.
1134
		 *
1135
		 * @since 3.4.0
1136
		 *
1137
		 * @param string jetpack_is_multi_site.
1138
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1139
		 */
1140
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1141
	}
1142
	/**
1143
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1144
	 *
1145
	 */
1146
	function update_jetpack_network_settings() {
1147
		// Only sync this info for the main network site.
1148
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1149
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1150
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1151
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1152
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1153
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1154
1155
	}
1156
1157
	/**
1158
	 * Get back if the current site is single user site.
1159
	 *
1160
	 * @return bool
1161
	 */
1162
	public static function is_single_user_site() {
1163
1164
		$user_query = new WP_User_Query( array(
1165
			'blog_id' => get_current_blog_id(),
1166
			'fields'  => 'ID',
1167
			'number' => 2
1168
		) );
1169
		return 1 === (int) $user_query->get_total();
1170
	}
1171
1172
	/**
1173
	 * Returns true if the site has file write access false otherwise.
1174
	 * @return string ( '1' | '0' )
1175
	 **/
1176
	public static function file_system_write_access() {
1177
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1178
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1179
		}
1180
1181
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1182
1183
		$filesystem_method = get_filesystem_method();
1184
		if ( $filesystem_method === 'direct' ) {
1185
			return 1;
1186
		}
1187
1188
		ob_start();
1189
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1190
		ob_end_clean();
1191
		if ( $filesystem_credentials_are_stored ) {
1192
			return 1;
1193
		}
1194
		return 0;
1195
	}
1196
1197
	/**
1198
	 * Finds out if a site is using a version control system.
1199
	 * @return string ( '1' | '0' )
1200
	 **/
1201
	public static function is_version_controlled() {
1202
1203
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1204
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1205
		}
1206
		$updater = new WP_Automatic_Updater();
1207
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1208
		// transients should not be empty
1209
		if ( empty( $is_version_controlled ) ) {
1210
			$is_version_controlled = '0';
1211
		}
1212
		return $is_version_controlled;
1213
	}
1214
1215
	/**
1216
	 * Determines whether the current theme supports featured images or not.
1217
	 * @return string ( '1' | '0' )
1218
	 */
1219
	public static function featured_images_enabled() {
1220
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1221
	}
1222
1223
	/*
1224
	 * Sync back wp_version
1225
	 */
1226
	public static function get_wp_version() {
1227
		global $wp_version;
1228
		return $wp_version;
1229
	}
1230
1231
	/**
1232
	 * Keeps wp_version in sync with .com when WordPress core updates
1233
	 **/
1234
	public static function update_get_wp_version( $update, $meta_data ) {
1235
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1236
			/** This action is documented in wp-includes/option.php */
1237
			/**
1238
			 * This triggers the sync for the jetpack version
1239
			 * See Jetpack_Sync options method for more info.
1240
			 */
1241
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1242
		}
1243
	}
1244
1245
	/**
1246
	 * Triggers a sync of update counts and update details
1247
	 */
1248
	function sync_update_data() {
1249
		// Anytime WordPress saves update data, we'll want to sync update data
1250
		add_action( 'set_site_transient_update_plugins', array( 'Jetpack', 'refresh_update_data' ) );
1251
		add_action( 'set_site_transient_update_themes', array( 'Jetpack', 'refresh_update_data' ) );
1252
		add_action( 'set_site_transient_update_core', array( 'Jetpack', 'refresh_update_data' ) );
1253
		// Anytime a connection to jetpack is made, sync the update data
1254
		add_action( 'jetpack_site_registered', array( 'Jetpack', 'refresh_update_data' ) );
1255
		// Anytime the Jetpack Version changes, sync the the update data
1256
		add_action( 'updating_jetpack_version', array( 'Jetpack', 'refresh_update_data' ) );
1257
1258
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1259
			$this->sync->mock_option( 'updates', array( 'Jetpack', 'get_updates' ) );
1260
		}
1261
1262
		$this->sync->mock_option( 'update_details', array( 'Jetpack', 'get_update_details' ) );
1263
	}
1264
1265
	/**
1266
	 * Triggers a sync of information specific to the current theme.
1267
	 */
1268
	function sync_theme_data() {
1269
		add_action( 'switch_theme', array( 'Jetpack', 'refresh_theme_data' ) );
1270
		$this->sync->mock_option( 'featured_images_enabled', array( 'Jetpack', 'featured_images_enabled' ) );
1271
	}
1272
1273
	/**
1274
	 * jetpack_updates is saved in the following schema:
1275
	 *
1276
	 * array (
1277
	 *      'plugins'                       => (int) Number of plugin updates available.
1278
	 *      'themes'                        => (int) Number of theme updates available.
1279
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1280
	 *      'translations'                  => (int) Number of translation updates available.
1281
	 *      'total'                         => (int) Total of all available updates.
1282
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1283
	 * )
1284
	 * @return array
1285
	 */
1286
	public static function get_updates() {
1287
		$update_data = wp_get_update_data();
1288
1289
		// Stores the individual update counts as well as the total count.
1290
		if ( isset( $update_data['counts'] ) ) {
1291
			$updates = $update_data['counts'];
1292
		}
1293
1294
		// If we need to update WordPress core, let's find the latest version number.
1295 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1296
			$cur = get_preferred_from_update_core();
1297
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1298
				$updates['wp_update_version'] = $cur->current;
1299
			}
1300
		}
1301
		return isset( $updates ) ? $updates : array();
1302
	}
1303
1304
	public static function get_update_details() {
1305
		$update_details = array(
1306
			'update_core' => get_site_transient( 'update_core' ),
1307
			'update_plugins' => get_site_transient( 'update_plugins' ),
1308
			'update_themes' => get_site_transient( 'update_themes' ),
1309
		);
1310
		return $update_details;
1311
	}
1312
1313
	public static function refresh_update_data() {
1314
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1315
			/**
1316
			 * Fires whenever the amount of updates needed for a site changes.
1317
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1318
			 *
1319
			 * @since 3.7.0
1320
			 *
1321
			 * @param string jetpack_updates
1322
			 * @param array Update counts calculated by Jetpack::get_updates
1323
			 */
1324
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1325
		}
1326
		/**
1327
		 * Fires whenever the amount of updates needed for a site changes.
1328
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1329
		 *
1330
		 * @since 3.7.0
1331
		 *
1332
		 * @param string jetpack_update_details
1333
		 * @param array Update details calculated by Jetpack::get_update_details
1334
		 */
1335
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1336
	}
1337
1338
	public static function refresh_theme_data() {
1339
		/**
1340
		 * Fires whenever a theme change is made.
1341
		 *
1342
		 * @since 3.8.1
1343
		 *
1344
		 * @param string featured_images_enabled
1345
		 * @param boolean Whether featured images are enabled or not
1346
		 */
1347
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1348
	}
1349
1350
	/**
1351
	 * Invalides the transient as well as triggers the update of the mock option.
1352
	 *
1353
	 * @return null
1354
	 */
1355
	function is_single_user_site_invalidate() {
1356
		/**
1357
		 * Fires when a user is added or removed from a site.
1358
		 * Determines if the site is a single user site.
1359
		 *
1360
		 * @since 3.4.0
1361
		 *
1362
		 * @param string jetpack_single_user_site.
1363
		 * @param bool Jetpack::is_single_user_site() Is the current site a single user site.
1364
		 */
1365
		do_action( 'update_option_jetpack_single_user_site', 'jetpack_single_user_site', (bool) Jetpack::is_single_user_site() );
1366
	}
1367
1368
	/**
1369
	 * Is Jetpack active?
1370
	 */
1371
	public static function is_active() {
1372
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1373
	}
1374
1375
	/**
1376
	 * Is Jetpack in development (offline) mode?
1377
	 */
1378
	public static function is_development_mode() {
1379
		$development_mode = false;
1380
1381
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1382
			$development_mode = JETPACK_DEV_DEBUG;
1383
		}
1384
1385
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1386
			$development_mode = true;
1387
		}
1388
		/**
1389
		 * Filters Jetpack's development mode.
1390
		 *
1391
		 * @see http://jetpack.com/support/development-mode/
1392
		 *
1393
		 * @since 2.2.1
1394
		 *
1395
		 * @param bool $development_mode Is Jetpack's development mode active.
1396
		 */
1397
		return apply_filters( 'jetpack_development_mode', $development_mode );
1398
	}
1399
1400
	/**
1401
	* Get Jetpack development mode notice text and notice class.
1402
	*
1403
	* Mirrors the checks made in Jetpack::is_development_mode
1404
	*
1405
	*/
1406
	public static function show_development_mode_notice() {
1407
		if ( Jetpack::is_development_mode() ) {
1408
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1409
				$notice = sprintf(
1410
					/* translators: %s is a URL */
1411
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1412
					'http://jetpack.com/support/development-mode/'
1413
				);
1414
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1415
				$notice = sprintf(
1416
					/* translators: %s is a URL */
1417
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1418
					'http://jetpack.com/support/development-mode/'
1419
				);
1420
			} else {
1421
				$notice = sprintf(
1422
					/* translators: %s is a URL */
1423
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1424
					'http://jetpack.com/support/development-mode/'
1425
				);
1426
			}
1427
1428
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1429
		}
1430
1431
		// Throw up a notice if using a development version and as for feedback.
1432
		if ( Jetpack::is_development_version() ) {
1433
			/* translators: %s is a URL */
1434
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1435
1436
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1437
		}
1438
		// Throw up a notice if using staging mode
1439
		if ( Jetpack::is_staging_site() ) {
1440
			/* translators: %s is a URL */
1441
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1442
1443
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1444
		}
1445
	}
1446
1447
	/**
1448
	 * Whether Jetpack's version maps to a public release, or a development version.
1449
	 */
1450
	public static function is_development_version() {
1451
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1452
	}
1453
1454
	/**
1455
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1456
	 */
1457
	public static function is_user_connected( $user_id = false ) {
1458
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1459
		if ( ! $user_id ) {
1460
			return false;
1461
		}
1462
		return (bool) Jetpack_Data::get_access_token( $user_id );
1463
	}
1464
1465
	/**
1466
	 * Get the wpcom user data of the current|specified connected user.
1467
	 */
1468 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1469
		if ( ! $user_id ) {
1470
			$user_id = get_current_user_id();
1471
		}
1472
		Jetpack::load_xml_rpc_client();
1473
		$xml = new Jetpack_IXR_Client( array(
1474
			'user_id' => $user_id,
1475
		) );
1476
		$xml->query( 'wpcom.getUser' );
1477
		if ( ! $xml->isError() ) {
1478
			return $xml->getResponse();
1479
		}
1480
		return false;
1481
	}
1482
1483
	/**
1484
	 * Get the wpcom email of the current|specified connected user.
1485
	 */
1486 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1487
		if ( ! $user_id ) {
1488
			$user_id = get_current_user_id();
1489
		}
1490
		Jetpack::load_xml_rpc_client();
1491
		$xml = new Jetpack_IXR_Client( array(
1492
			'user_id' => $user_id,
1493
		) );
1494
		$xml->query( 'wpcom.getUserEmail' );
1495
		if ( ! $xml->isError() ) {
1496
			return $xml->getResponse();
1497
		}
1498
		return false;
1499
	}
1500
1501
	/**
1502
	 * Get the wpcom email of the master user.
1503
	 */
1504
	public static function get_master_user_email() {
1505
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1506
		if ( $master_user_id ) {
1507
			return self::get_connected_user_email( $master_user_id );
1508
		}
1509
		return '';
1510
	}
1511
1512
	function current_user_is_connection_owner() {
1513
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1514
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1515
	}
1516
1517
	/**
1518
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1519
	 */
1520
	function extra_oembed_providers() {
1521
		// Cloudup: https://dev.cloudup.com/#oembed
1522
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1523
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1524
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1525
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1526
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1527
	}
1528
1529
	/**
1530
	 * Synchronize connected user role changes
1531
	 */
1532
	function user_role_change( $user_id ) {
1533
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1534
			$current_user_id = get_current_user_id();
1535
			wp_set_current_user( $user_id );
1536
			$role = $this->translate_current_user_to_role();
1537
			$signed_role = $this->sign_role( $role );
1538
			wp_set_current_user( $current_user_id );
1539
1540
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1541
			$master_user_id = absint( $master_token->external_user_id );
1542
1543
			if ( ! $master_user_id )
1544
				return; // this shouldn't happen
1545
1546
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1547
			//@todo retry on failure
1548
1549
			//try to choose a new master if we're demoting the current one
1550
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1551
				$query = new WP_User_Query(
1552
					array(
1553
						'fields'  => array( 'id' ),
1554
						'role'    => 'administrator',
1555
						'orderby' => 'id',
1556
						'exclude' => array( $master_user_id ),
1557
					)
1558
				);
1559
				$new_master = false;
1560
				foreach ( $query->results as $result ) {
1561
					$uid = absint( $result->id );
1562
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1563
						$new_master = $uid;
1564
						break;
1565
					}
1566
				}
1567
1568
				if ( $new_master ) {
1569
					Jetpack_Options::update_option( 'master_user', $new_master );
1570
				}
1571
				// else disconnect..?
1572
			}
1573
		}
1574
	}
1575
1576
	/**
1577
	 * Loads the currently active modules.
1578
	 */
1579
	public static function load_modules() {
1580
		if ( ! self::is_active() && !self::is_development_mode() ) {
1581
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1582
				return;
1583
			}
1584
		}
1585
1586
		$version = Jetpack_Options::get_option( 'version' );
1587 View Code Duplication
		if ( ! $version ) {
1588
			$version = $old_version = JETPACK__VERSION . ':' . time();
1589
			/** This action is documented in class.jetpack.php */
1590
			do_action( 'updating_jetpack_version', $version, false );
1591
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1592
		}
1593
		list( $version ) = explode( ':', $version );
1594
1595
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1596
1597
		$modules_data = array();
1598
1599
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1600
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1601
			$updated_modules = array();
1602
			foreach ( $modules as $module ) {
1603
				$modules_data[ $module ] = Jetpack::get_module( $module );
1604
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1605
					continue;
1606
				}
1607
1608
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1609
					continue;
1610
				}
1611
1612
				$updated_modules[] = $module;
1613
			}
1614
1615
			$modules = array_diff( $modules, $updated_modules );
1616
		}
1617
1618
		$is_development_mode = Jetpack::is_development_mode();
1619
1620
		foreach ( $modules as $index => $module ) {
1621
			// If we're in dev mode, disable modules requiring a connection
1622
			if ( $is_development_mode ) {
1623
				// Prime the pump if we need to
1624
				if ( empty( $modules_data[ $module ] ) ) {
1625
					$modules_data[ $module ] = Jetpack::get_module( $module );
1626
				}
1627
				// If the module requires a connection, but we're in local mode, don't include it.
1628
				if ( $modules_data[ $module ]['requires_connection'] ) {
1629
					continue;
1630
				}
1631
			}
1632
1633
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1634
				continue;
1635
			}
1636
1637
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1638
				unset( $modules[ $index ] );
1639
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1640
				continue;
1641
			}
1642
1643
			/**
1644
			 * Fires when a specific module is loaded.
1645
			 * The dynamic part of the hook, $module, is the module slug.
1646
			 *
1647
			 * @since 1.1.0
1648
			 */
1649
			do_action( 'jetpack_module_loaded_' . $module );
1650
		}
1651
1652
		/**
1653
		 * Fires when all the modules are loaded.
1654
		 *
1655
		 * @since 1.1.0
1656
		 */
1657
		do_action( 'jetpack_modules_loaded' );
1658
1659
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
1660
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1661
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1662
	}
1663
1664
	/**
1665
	 * Check if Jetpack's REST API compat file should be included
1666
	 * @action plugins_loaded
1667
	 * @return null
1668
	 */
1669
	public function check_rest_api_compat() {
1670
		/**
1671
		 * Filters the list of REST API compat files to be included.
1672
		 *
1673
		 * @since 2.2.5
1674
		 *
1675
		 * @param array $args Array of REST API compat files to include.
1676
		 */
1677
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1678
1679
		if ( function_exists( 'bbpress' ) )
1680
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1681
1682
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1683
			require_once $_jetpack_rest_api_compat_include;
1684
	}
1685
1686
	/**
1687
	 * Gets all plugins currently active in values, regardless of whether they're
1688
	 * traditionally activated or network activated.
1689
	 *
1690
	 * @todo Store the result in core's object cache maybe?
1691
	 */
1692
	public static function get_active_plugins() {
1693
		$active_plugins = (array) get_option( 'active_plugins', array() );
1694
1695
		if ( is_multisite() ) {
1696
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1697
			// whereas active_plugins stores them in the values.
1698
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1699
			if ( $network_plugins ) {
1700
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1701
			}
1702
		}
1703
1704
		sort( $active_plugins );
1705
1706
		return array_unique( $active_plugins );
1707
	}
1708
1709
	/**
1710
	 * Gets and parses additional plugin data to send with the heartbeat data
1711
	 *
1712
	 * @since 3.8.1
1713
	 *
1714
	 * @return array Array of plugin data
1715
	 */
1716
	public static function get_parsed_plugin_data() {
1717
		if ( ! function_exists( 'get_plugins' ) ) {
1718
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1719
		}
1720
		$all_plugins    = get_plugins();
1721
		$active_plugins = Jetpack::get_active_plugins();
1722
1723
		$plugins = array();
1724
		foreach ( $all_plugins as $path => $plugin_data ) {
1725
			$plugins[ $path ] = array(
1726
					'is_active' => in_array( $path, $active_plugins ),
1727
					'file'      => $path,
1728
					'name'      => $plugin_data['Name'],
1729
					'version'   => $plugin_data['Version'],
1730
					'author'    => $plugin_data['Author'],
1731
			);
1732
		}
1733
1734
		return $plugins;
1735
	}
1736
1737
	/**
1738
	 * Gets and parses theme data to send with the heartbeat data
1739
	 *
1740
	 * @since 3.8.1
1741
	 *
1742
	 * @return array Array of theme data
1743
	 */
1744
	public static function get_parsed_theme_data() {
1745
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1746
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1747
1748
		$themes = array();
1749
		foreach ( $all_themes as $slug => $theme_data ) {
1750
			$theme_headers = array();
1751
			foreach ( $header_keys as $header_key ) {
1752
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1753
			}
1754
1755
			$themes[ $slug ] = array(
1756
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1757
					'slug' => $slug,
1758
					'theme_root' => $theme_data->get_theme_root_uri(),
1759
					'parent' => $theme_data->parent(),
1760
					'headers' => $theme_headers
1761
			);
1762
		}
1763
1764
		return $themes;
1765
	}
1766
1767
	/**
1768
	 * Checks whether a specific plugin is active.
1769
	 *
1770
	 * We don't want to store these in a static variable, in case
1771
	 * there are switch_to_blog() calls involved.
1772
	 */
1773
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1774
		return in_array( $plugin, self::get_active_plugins() );
1775
	}
1776
1777
	/**
1778
	 * Check if Jetpack's Open Graph tags should be used.
1779
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1780
	 *
1781
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1782
	 * @action plugins_loaded
1783
	 * @return null
1784
	 */
1785
	public function check_open_graph() {
1786
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1787
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1788
		}
1789
1790
		$active_plugins = self::get_active_plugins();
1791
1792
		if ( ! empty( $active_plugins ) ) {
1793
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1794
				if ( in_array( $plugin, $active_plugins ) ) {
1795
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1796
					break;
1797
				}
1798
			}
1799
		}
1800
1801
		/**
1802
		 * Allow the addition of Open Graph Meta Tags to all pages.
1803
		 *
1804
		 * @since 2.0.3
1805
		 *
1806
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1807
		 */
1808
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1809
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1810
		}
1811
	}
1812
1813
	/**
1814
	 * Check if Jetpack's Twitter tags should be used.
1815
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1816
	 *
1817
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1818
	 * @action plugins_loaded
1819
	 * @return null
1820
	 */
1821
	public function check_twitter_tags() {
1822
1823
		$active_plugins = self::get_active_plugins();
1824
1825
		if ( ! empty( $active_plugins ) ) {
1826
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1827
				if ( in_array( $plugin, $active_plugins ) ) {
1828
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1829
					break;
1830
				}
1831
			}
1832
		}
1833
1834
		/**
1835
		 * Allow Twitter Card Meta tags to be disabled.
1836
		 *
1837
		 * @since 2.6.0
1838
		 *
1839
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1840
		 */
1841
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1842
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1843
		}
1844
	}
1845
1846
1847
1848
1849
	/*
1850
	 *
1851
	 * Jetpack Security Reports
1852
	 *
1853
	 * Allowed types: login_form, backup, file_scanning, spam
1854
	 *
1855
	 * Args for login_form and spam: 'blocked'=>(int)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1856
	 *
1857
	 * Args for backup and file_scanning: 'last'=>(timestamp)(optional), 'next'=>(timestamp)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1858
	 *
1859
	 *
1860
	 * Example code to submit a security report:
1861
	 *
1862
	 *  function akismet_submit_jetpack_security_report() {
1863
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1864
	 *  }
1865
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1866
	 *
1867
	 */
1868
1869
1870
	/**
1871
	 * Calls for security report submissions.
1872
	 *
1873
	 * @return null
1874
	 */
1875
	public static function perform_security_reporting() {
1876
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1877
1878
		if ( $no_check_needed ) {
1879
			return;
1880
		}
1881
1882
		/**
1883
		 * Fires before a security report is created.
1884
		 *
1885
		 * @since 3.4.0
1886
		 */
1887
		do_action( 'jetpack_security_report' );
1888
1889
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1890
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1891
	}
1892
1893
	/**
1894
	 * Allows plugins to submit security reports.
1895
 	 *
1896
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1897
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1898
	 * @param array   $args         See definitions above
1899
	 */
1900
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1901
1902
		if( !doing_action( 'jetpack_security_report' ) ) {
1903
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1904
		}
1905
1906
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1907
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1908
		}
1909
1910
		if( !function_exists( 'get_plugin_data' ) ) {
1911
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1912
		}
1913
1914
		//Get rid of any non-allowed args
1915
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1916
1917
		$plugin = get_plugin_data( $plugin_file );
1918
1919
		if ( !$plugin['Name'] ) {
1920
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1921
		}
1922
1923
		// Sanitize everything to make sure we're not syncing something wonky
1924
		$type = sanitize_key( $type );
1925
1926
		$args['plugin'] = $plugin;
1927
1928
		// Cast blocked, last and next as integers.
1929
		// Last and next should be in unix timestamp format
1930
		if ( isset( $args['blocked'] ) ) {
1931
			$args['blocked'] = (int) $args['blocked'];
1932
		}
1933
		if ( isset( $args['last'] ) ) {
1934
			$args['last'] = (int) $args['last'];
1935
		}
1936
		if ( isset( $args['next'] ) ) {
1937
			$args['next'] = (int) $args['next'];
1938
		}
1939
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1940
			$args['status'] = 'ok';
1941
		}
1942
		if ( isset( $args['message'] ) ) {
1943
1944
			if( $args['status'] == 'ok' ) {
1945
				unset( $args['message'] );
1946
			}
1947
1948
			$allowed_html = array(
1949
			    'a' => array(
1950
			        'href' => array(),
1951
			        'title' => array()
1952
			    ),
1953
			    'em' => array(),
1954
			    'strong' => array(),
1955
			);
1956
1957
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1958
		}
1959
1960
		$plugin_name = $plugin[ 'Name' ];
1961
1962
		self::$security_report[ $type ][ $plugin_name ] = $args;
1963
	}
1964
1965
	/**
1966
	 * Collects a new report if needed, then returns it.
1967
	 */
1968
	public function get_security_report() {
1969
		self::perform_security_reporting();
1970
		return Jetpack_Options::get_option( 'security_report' );
1971
	}
1972
1973
1974
/* Jetpack Options API */
1975
1976
	public static function get_option_names( $type = 'compact' ) {
1977
		return Jetpack_Options::get_option_names( $type );
1978
	}
1979
1980
	/**
1981
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1982
 	 *
1983
	 * @param string $name    Option name
1984
	 * @param mixed  $default (optional)
1985
	 */
1986
	public static function get_option( $name, $default = false ) {
1987
		return Jetpack_Options::get_option( $name, $default );
1988
	}
1989
1990
	/**
1991
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1992
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1993
	* $name must be a registered option name.
1994
	*/
1995
	public static function create_nonce( $name ) {
1996
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1997
1998
		Jetpack_Options::update_option( $name, $secret );
1999
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
2000
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
2001
			return new Jetpack_Error( 'missing_secrets' );
2002
2003
		return array(
2004
			'secret_1' => $secret_1,
2005
			'secret_2' => $secret_2,
2006
			'eol'      => $eol,
2007
		);
2008
	}
2009
2010
	/**
2011
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2012
 	 *
2013
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2014
	 * @param string $name  Option name
2015
	 * @param mixed  $value Option value
2016
	 */
2017
	public static function update_option( $name, $value ) {
2018
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2019
		return Jetpack_Options::update_option( $name, $value );
2020
	}
2021
2022
	/**
2023
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2024
 	 *
2025
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2026
	 * @param array $array array( option name => option value, ... )
2027
	 */
2028
	public static function update_options( $array ) {
2029
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2030
		return Jetpack_Options::update_options( $array );
2031
	}
2032
2033
	/**
2034
	 * Deletes the given option.  May be passed multiple option names as an array.
2035
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2036
	 *
2037
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2038
	 * @param string|array $names
2039
	 */
2040
	public static function delete_option( $names ) {
2041
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2042
		return Jetpack_Options::delete_option( $names );
2043
	}
2044
2045
	/**
2046
	 * Enters a user token into the user_tokens option
2047
	 *
2048
	 * @param int $user_id
2049
	 * @param string $token
2050
	 * return bool
2051
	 */
2052
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2053
		// not designed for concurrent updates
2054
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2055
		if ( ! is_array( $user_tokens ) )
2056
			$user_tokens = array();
2057
		$user_tokens[$user_id] = $token;
2058
		if ( $is_master_user ) {
2059
			$master_user = $user_id;
2060
			$options     = compact( 'user_tokens', 'master_user' );
2061
		} else {
2062
			$options = compact( 'user_tokens' );
2063
		}
2064
		return Jetpack_Options::update_options( $options );
2065
	}
2066
2067
	/**
2068
	 * Returns an array of all PHP files in the specified absolute path.
2069
	 * Equivalent to glob( "$absolute_path/*.php" ).
2070
	 *
2071
	 * @param string $absolute_path The absolute path of the directory to search.
2072
	 * @return array Array of absolute paths to the PHP files.
2073
	 */
2074
	public static function glob_php( $absolute_path ) {
2075
		if ( function_exists( 'glob' ) ) {
2076
			return glob( "$absolute_path/*.php" );
2077
		}
2078
2079
		$absolute_path = untrailingslashit( $absolute_path );
2080
		$files = array();
2081
		if ( ! $dir = @opendir( $absolute_path ) ) {
2082
			return $files;
2083
		}
2084
2085
		while ( false !== $file = readdir( $dir ) ) {
2086
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2087
				continue;
2088
			}
2089
2090
			$file = "$absolute_path/$file";
2091
2092
			if ( ! is_file( $file ) ) {
2093
				continue;
2094
			}
2095
2096
			$files[] = $file;
2097
		}
2098
2099
		closedir( $dir );
2100
2101
		return $files;
2102
	}
2103
2104
	public static function activate_new_modules( $redirect = false ) {
2105
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2106
			return;
2107
		}
2108
2109
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2110 View Code Duplication
		if ( ! $jetpack_old_version ) {
2111
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2112
			/** This action is documented in class.jetpack.php */
2113
			do_action( 'updating_jetpack_version', $version, false );
2114
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2115
		}
2116
2117
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2118
2119
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2120
			return;
2121
		}
2122
2123
		$active_modules     = Jetpack::get_active_modules();
2124
		$reactivate_modules = array();
2125
		foreach ( $active_modules as $active_module ) {
2126
			$module = Jetpack::get_module( $active_module );
2127
			if ( ! isset( $module['changed'] ) ) {
2128
				continue;
2129
			}
2130
2131
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2132
				continue;
2133
			}
2134
2135
			$reactivate_modules[] = $active_module;
2136
			Jetpack::deactivate_module( $active_module );
2137
		}
2138
2139
		$new_version = JETPACK__VERSION . ':' . time();
2140
		/** This action is documented in class.jetpack.php */
2141
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2142
		Jetpack_Options::update_options(
2143
			array(
2144
				'version'     => $new_version,
2145
				'old_version' => $jetpack_old_version,
2146
			)
2147
		);
2148
2149
		Jetpack::state( 'message', 'modules_activated' );
2150
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2151
2152
		if ( $redirect ) {
2153
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2154
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2155
				$page = $_GET['page'];
2156
			}
2157
2158
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2159
			exit;
2160
		}
2161
	}
2162
2163
	/**
2164
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2165
	 * Make sure to tuck away module "library" files in a sub-directory.
2166
	 */
2167
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2168
		static $modules = null;
2169
2170
		if ( ! isset( $modules ) ) {
2171
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2172
			// Use the cache if we're on the front-end and it's available...
2173
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2174
				$modules = $available_modules_option[ JETPACK__VERSION ];
2175
			} else {
2176
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2177
2178
				$modules = array();
2179
2180
				foreach ( $files as $file ) {
2181
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2182
						continue;
2183
					}
2184
2185
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2186
				}
2187
2188
				Jetpack_Options::update_option( 'available_modules', array(
2189
					JETPACK__VERSION => $modules,
2190
				) );
2191
			}
2192
		}
2193
2194
		/**
2195
		 * Filters the array of modules available to be activated.
2196
		 *
2197
		 * @since 2.4.0
2198
		 *
2199
		 * @param array $modules Array of available modules.
2200
		 * @param string $min_version Minimum version number required to use modules.
2201
		 * @param string $max_version Maximum version number required to use modules.
2202
		 */
2203
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2204
2205
		if ( ! $min_version && ! $max_version ) {
2206
			return array_keys( $mods );
2207
		}
2208
2209
		$r = array();
2210
		foreach ( $mods as $slug => $introduced ) {
2211
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2212
				continue;
2213
			}
2214
2215
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2216
				continue;
2217
			}
2218
2219
			$r[] = $slug;
2220
		}
2221
2222
		return $r;
2223
	}
2224
2225
	/**
2226
	 * Default modules loaded on activation.
2227
	 */
2228
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2229
		$return = array();
2230
2231
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2232
			$module_data = Jetpack::get_module( $module );
2233
2234
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2235
				case 'yes' :
2236
					$return[] = $module;
2237
					break;
2238
				case 'public' :
2239
					if ( Jetpack_Options::get_option( 'public' ) ) {
2240
						$return[] = $module;
2241
					}
2242
					break;
2243
				case 'no' :
2244
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2245
					break;
2246
			}
2247
		}
2248
		/**
2249
		 * Filters the array of default modules.
2250
		 *
2251
		 * @since 2.5.0
2252
		 *
2253
		 * @param array $return Array of default modules.
2254
		 * @param string $min_version Minimum version number required to use modules.
2255
		 * @param string $max_version Maximum version number required to use modules.
2256
		 */
2257
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2258
	}
2259
2260
	/**
2261
	 * Checks activated modules during auto-activation to determine
2262
	 * if any of those modules are being deprecated.  If so, close
2263
	 * them out, and add any replacement modules.
2264
	 *
2265
	 * Runs at priority 99 by default.
2266
	 *
2267
	 * This is run late, so that it can still activate a module if
2268
	 * the new module is a replacement for another that the user
2269
	 * currently has active, even if something at the normal priority
2270
	 * would kibosh everything.
2271
	 *
2272
	 * @since 2.6
2273
	 * @uses jetpack_get_default_modules filter
2274
	 * @param array $modules
2275
	 * @return array
2276
	 */
2277
	function handle_deprecated_modules( $modules ) {
2278
		$deprecated_modules = array(
2279
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2280
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2281
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2282
		);
2283
2284
		// Don't activate SSO if they never completed activating WPCC.
2285
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2286
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2287
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2288
				$deprecated_modules['wpcc'] = null;
2289
			}
2290
		}
2291
2292
		foreach ( $deprecated_modules as $module => $replacement ) {
2293
			if ( Jetpack::is_module_active( $module ) ) {
2294
				self::deactivate_module( $module );
2295
				if ( $replacement ) {
2296
					$modules[] = $replacement;
2297
				}
2298
			}
2299
		}
2300
2301
		return array_unique( $modules );
2302
	}
2303
2304
	/**
2305
	 * Checks activated plugins during auto-activation to determine
2306
	 * if any of those plugins are in the list with a corresponding module
2307
	 * that is not compatible with the plugin. The module will not be allowed
2308
	 * to auto-activate.
2309
	 *
2310
	 * @since 2.6
2311
	 * @uses jetpack_get_default_modules filter
2312
	 * @param array $modules
2313
	 * @return array
2314
	 */
2315
	function filter_default_modules( $modules ) {
2316
2317
		$active_plugins = self::get_active_plugins();
2318
2319
		if ( ! empty( $active_plugins ) ) {
2320
2321
			// For each module we'd like to auto-activate...
2322
			foreach ( $modules as $key => $module ) {
2323
				// If there are potential conflicts for it...
2324
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2325
					// For each potential conflict...
2326
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2327
						// If that conflicting plugin is active...
2328
						if ( in_array( $plugin, $active_plugins ) ) {
2329
							// Remove that item from being auto-activated.
2330
							unset( $modules[ $key ] );
2331
						}
2332
					}
2333
				}
2334
			}
2335
		}
2336
2337
		return $modules;
2338
	}
2339
2340
	/**
2341
	 * Extract a module's slug from its full path.
2342
	 */
2343
	public static function get_module_slug( $file ) {
2344
		return str_replace( '.php', '', basename( $file ) );
2345
	}
2346
2347
	/**
2348
	 * Generate a module's path from its slug.
2349
	 */
2350
	public static function get_module_path( $slug ) {
2351
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2352
	}
2353
2354
	/**
2355
	 * Load module data from module file. Headers differ from WordPress
2356
	 * plugin headers to avoid them being identified as standalone
2357
	 * plugins on the WordPress plugins page.
2358
	 */
2359
	public static function get_module( $module ) {
2360
		$headers = array(
2361
			'name'                      => 'Module Name',
2362
			'description'               => 'Module Description',
2363
			'jumpstart_desc'            => 'Jumpstart Description',
2364
			'sort'                      => 'Sort Order',
2365
			'recommendation_order'      => 'Recommendation Order',
2366
			'introduced'                => 'First Introduced',
2367
			'changed'                   => 'Major Changes In',
2368
			'deactivate'                => 'Deactivate',
2369
			'free'                      => 'Free',
2370
			'requires_connection'       => 'Requires Connection',
2371
			'auto_activate'             => 'Auto Activate',
2372
			'module_tags'               => 'Module Tags',
2373
			'feature'                   => 'Feature',
2374
			'additional_search_queries' => 'Additional Search Queries',
2375
		);
2376
2377
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2378
2379
		$mod = Jetpack::get_file_data( $file, $headers );
2380
		if ( empty( $mod['name'] ) ) {
2381
			return false;
2382
		}
2383
2384
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2385
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2386
		$mod['deactivate']              = empty( $mod['deactivate'] );
2387
		$mod['free']                    = empty( $mod['free'] );
2388
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2389
2390
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2391
			$mod['auto_activate'] = 'No';
2392
		} else {
2393
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2394
		}
2395
2396
		if ( $mod['module_tags'] ) {
2397
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2398
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2399
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2400
		} else {
2401
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2402
		}
2403
2404
		if ( $mod['feature'] ) {
2405
			$mod['feature'] = explode( ',', $mod['feature'] );
2406
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2407
		} else {
2408
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2409
		}
2410
2411
		/**
2412
		 * Filters the feature array on a module.
2413
		 *
2414
		 * This filter allows you to control where each module is filtered: Recommended,
2415
		 * Jumpstart, and the default "Other" listing.
2416
		 *
2417
		 * @since 3.5.0
2418
		 *
2419
		 * @param array   $mod['feature'] The areas to feature this module:
2420
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2421
		 *     'Recommended' shows on the main Jetpack admin screen.
2422
		 *     'Other' should be the default if no other value is in the array.
2423
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2424
		 * @param array   $mod All the currently assembled module data.
2425
		 */
2426
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2427
2428
		/**
2429
		 * Filter the returned data about a module.
2430
		 *
2431
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2432
		 * so please be careful.
2433
		 *
2434
		 * @since 3.6.0
2435
		 *
2436
		 * @param array   $mod    The details of the requested module.
2437
		 * @param string  $module The slug of the module, e.g. sharedaddy
2438
		 * @param string  $file   The path to the module source file.
2439
		 */
2440
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2441
	}
2442
2443
	/**
2444
	 * Like core's get_file_data implementation, but caches the result.
2445
	 */
2446
	public static function get_file_data( $file, $headers ) {
2447
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2448
		$file_name = basename( $file );
2449
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2450
		$key              = md5( $file_name . serialize( $headers ) );
2451
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2452
2453
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2454
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2455
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2456
		}
2457
2458
		$data = get_file_data( $file, $headers );
2459
2460
		// Strip out any old Jetpack versions that are cluttering the option.
2461
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2462
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2463
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2464
2465
		return $data;
2466
	}
2467
2468
	/**
2469
	 * Return translated module tag.
2470
	 *
2471
	 * @param string $tag Tag as it appears in each module heading.
2472
	 *
2473
	 * @return mixed
2474
	 */
2475
	public static function translate_module_tag( $tag ) {
2476
		return jetpack_get_module_i18n_tag( $tag );
2477
	}
2478
2479
	/**
2480
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2481
	 *
2482
	 * @since 3.9.2
2483
	 *
2484
	 * @param array $modules
2485
	 *
2486
	 * @return string|void
2487
	 */
2488
	public static function get_translated_modules( $modules ) {
2489
		foreach ( $modules as $index => $module ) {
2490
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2491
			if ( isset( $module['name'] ) ) {
2492
				$modules[ $index ]['name'] = $i18n_module['name'];
2493
			}
2494
			if ( isset( $module['description'] ) ) {
2495
				$modules[ $index ]['description'] = $i18n_module['description'];
2496
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2497
			}
2498
		}
2499
		return $modules;
2500
	}
2501
2502
	/**
2503
	 * Get a list of activated modules as an array of module slugs.
2504
	 */
2505
	public static function get_active_modules() {
2506
		$active = Jetpack_Options::get_option( 'active_modules' );
2507
		if ( ! is_array( $active ) )
2508
			$active = array();
2509
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2510
			$active[] = 'vaultpress';
2511
		} else {
2512
			$active = array_diff( $active, array( 'vaultpress' ) );
2513
		}
2514
2515
		//If protect is active on the main site of a multisite, it should be active on all sites.
2516
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2517
			$active[] = 'protect';
2518
		}
2519
2520
		return array_unique( $active );
2521
	}
2522
2523
	/**
2524
	 * Check whether or not a Jetpack module is active.
2525
	 *
2526
	 * @param string $module The slug of a Jetpack module.
2527
	 * @return bool
2528
	 *
2529
	 * @static
2530
	 */
2531
	public static function is_module_active( $module ) {
2532
		return in_array( $module, self::get_active_modules() );
2533
	}
2534
2535
	public static function is_module( $module ) {
2536
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2537
	}
2538
2539
	/**
2540
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2541
	 *
2542
	 * @param bool $catch True to start catching, False to stop.
2543
	 *
2544
	 * @static
2545
	 */
2546
	public static function catch_errors( $catch ) {
2547
		static $display_errors, $error_reporting;
2548
2549
		if ( $catch ) {
2550
			$display_errors  = @ini_set( 'display_errors', 1 );
2551
			$error_reporting = @error_reporting( E_ALL );
2552
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2553
		} else {
2554
			@ini_set( 'display_errors', $display_errors );
2555
			@error_reporting( $error_reporting );
2556
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2557
		}
2558
	}
2559
2560
	/**
2561
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2562
	 */
2563
	public static function catch_errors_on_shutdown() {
2564
		Jetpack::state( 'php_errors', ob_get_clean() );
2565
	}
2566
2567
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2568
		$jetpack = Jetpack::init();
2569
2570
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2571
		$modules = array_merge( $other_modules, $modules );
2572
2573
		// Look for standalone plugins and disable if active.
2574
2575
		$to_deactivate = array();
2576
		foreach ( $modules as $module ) {
2577
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2578
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2579
			}
2580
		}
2581
2582
		$deactivated = array();
2583
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2584
			list( $probable_file, $probable_title ) = $deactivate_me;
2585
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2586
				$deactivated[] = $module;
2587
			}
2588
		}
2589
2590
		if ( $deactivated && $redirect ) {
2591
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2592
2593
			$url = add_query_arg(
2594
				array(
2595
					'action'   => 'activate_default_modules',
2596
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2597
				),
2598
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2599
			);
2600
			wp_safe_redirect( $url );
2601
			exit;
2602
		}
2603
2604
		/**
2605
		 * Fires before default modules are activated.
2606
		 *
2607
		 * @since 1.9.0
2608
		 *
2609
		 * @param string $min_version Minimum version number required to use modules.
2610
		 * @param string $max_version Maximum version number required to use modules.
2611
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2612
		 */
2613
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2614
2615
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2616
		Jetpack::restate();
2617
		Jetpack::catch_errors( true );
2618
2619
		$active = Jetpack::get_active_modules();
2620
2621
		foreach ( $modules as $module ) {
2622
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2623
				$active[] = $module;
2624
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2625
				continue;
2626
			}
2627
2628
			if ( in_array( $module, $active ) ) {
2629
				$module_info = Jetpack::get_module( $module );
2630
				if ( ! $module_info['deactivate'] ) {
2631
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2632 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2633
						$active_state = explode( ',', $active_state );
2634
					} else {
2635
						$active_state = array();
2636
					}
2637
					$active_state[] = $module;
2638
					Jetpack::state( $state, implode( ',', $active_state ) );
2639
				}
2640
				continue;
2641
			}
2642
2643
			$file = Jetpack::get_module_path( $module );
2644
			if ( ! file_exists( $file ) ) {
2645
				continue;
2646
			}
2647
2648
			// we'll override this later if the plugin can be included without fatal error
2649
			if ( $redirect ) {
2650
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2651
			}
2652
			Jetpack::state( 'error', 'module_activation_failed' );
2653
			Jetpack::state( 'module', $module );
2654
			ob_start();
2655
			require $file;
2656
			/**
2657
			 * Fires when a specific module is activated.
2658
			 *
2659
			 * @since 1.9.0
2660
			 *
2661
			 * @param string $module Module slug.
2662
			 */
2663
			do_action( 'jetpack_activate_module', $module );
2664
			$active[] = $module;
2665
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2666 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2667
				$active_state = explode( ',', $active_state );
2668
			} else {
2669
				$active_state = array();
2670
			}
2671
			$active_state[] = $module;
2672
			Jetpack::state( $state, implode( ',', $active_state ) );
2673
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2674
			ob_end_clean();
2675
		}
2676
		Jetpack::state( 'error', false );
2677
		Jetpack::state( 'module', false );
2678
		Jetpack::catch_errors( false );
2679
		/**
2680
		 * Fires when default modules are activated.
2681
		 *
2682
		 * @since 1.9.0
2683
		 *
2684
		 * @param string $min_version Minimum version number required to use modules.
2685
		 * @param string $max_version Maximum version number required to use modules.
2686
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2687
		 */
2688
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2689
	}
2690
2691
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2692
		/**
2693
		 * Fires before a module is activated.
2694
		 *
2695
		 * @since 2.6.0
2696
		 *
2697
		 * @param string $module Module slug.
2698
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2699
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2700
		 */
2701
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2702
2703
		$jetpack = Jetpack::init();
2704
2705
		if ( ! strlen( $module ) )
2706
			return false;
2707
2708
		if ( ! Jetpack::is_module( $module ) )
2709
			return false;
2710
2711
		// If it's already active, then don't do it again
2712
		$active = Jetpack::get_active_modules();
2713
		foreach ( $active as $act ) {
2714
			if ( $act == $module )
2715
				return true;
2716
		}
2717
2718
		$module_data = Jetpack::get_module( $module );
2719
2720
		if ( ! Jetpack::is_active() ) {
2721
			if ( !Jetpack::is_development_mode() )
2722
				return false;
2723
2724
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2725
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2726
				return false;
2727
		}
2728
2729
		// Check and see if the old plugin is active
2730
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2731
			// Deactivate the old plugin
2732
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2733
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2734
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2735
				Jetpack::state( 'deactivated_plugins', $module );
2736
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2737
				exit;
2738
			}
2739
		}
2740
2741
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2742
		Jetpack::state( 'module', $module );
2743
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2744
2745
		Jetpack::catch_errors( true );
2746
		ob_start();
2747
		require Jetpack::get_module_path( $module );
2748
		/** This action is documented in class.jetpack.php */
2749
		do_action( 'jetpack_activate_module', $module );
2750
		$active[] = $module;
2751
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2752
		Jetpack::state( 'error', false ); // the override
2753
		Jetpack::state( 'message', 'module_activated' );
2754
		Jetpack::state( 'module', $module );
2755
		ob_end_clean();
2756
		Jetpack::catch_errors( false );
2757
2758
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2759 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2760
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2761
2762
			//Jump start is being dismissed send data to MC Stats
2763
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2764
2765
			$jetpack->do_stats( 'server_side' );
2766
		}
2767
2768
		if ( $redirect ) {
2769
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2770
		}
2771
		if ( $exit ) {
2772
			exit;
2773
		}
2774
		return true;
2775
	}
2776
2777
	function activate_module_actions( $module ) {
2778
		/**
2779
		 * Fires when a module is activated.
2780
		 * The dynamic part of the filter, $module, is the module slug.
2781
		 *
2782
		 * @since 1.9.0
2783
		 *
2784
		 * @param string $module Module slug.
2785
		 */
2786
		do_action( "jetpack_activate_module_$module", $module );
2787
2788
		$this->sync->sync_all_module_options( $module );
2789
	}
2790
2791
	public static function deactivate_module( $module ) {
2792
		/**
2793
		 * Fires when a module is deactivated.
2794
		 *
2795
		 * @since 1.9.0
2796
		 *
2797
		 * @param string $module Module slug.
2798
		 */
2799
		do_action( 'jetpack_pre_deactivate_module', $module );
2800
2801
		$jetpack = Jetpack::init();
2802
2803
		$active = Jetpack::get_active_modules();
2804
		$new    = array_filter( array_diff( $active, (array) $module ) );
2805
2806
		/**
2807
		 * Fires when a module is deactivated.
2808
		 * The dynamic part of the filter, $module, is the module slug.
2809
		 *
2810
		 * @since 1.9.0
2811
		 *
2812
		 * @param string $module Module slug.
2813
		 */
2814
		do_action( "jetpack_deactivate_module_$module", $module );
2815
2816
		// A flag for Jump Start so it's not shown again.
2817 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2818
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2819
2820
			//Jump start is being dismissed send data to MC Stats
2821
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2822
2823
			$jetpack->do_stats( 'server_side' );
2824
		}
2825
2826
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2827
	}
2828
2829
	public static function enable_module_configurable( $module ) {
2830
		$module = Jetpack::get_module_slug( $module );
2831
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2832
	}
2833
2834
	public static function module_configuration_url( $module ) {
2835
		$module = Jetpack::get_module_slug( $module );
2836
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2837
	}
2838
2839
	public static function module_configuration_load( $module, $method ) {
2840
		$module = Jetpack::get_module_slug( $module );
2841
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2842
	}
2843
2844
	public static function module_configuration_head( $module, $method ) {
2845
		$module = Jetpack::get_module_slug( $module );
2846
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2847
	}
2848
2849
	public static function module_configuration_screen( $module, $method ) {
2850
		$module = Jetpack::get_module_slug( $module );
2851
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2852
	}
2853
2854
	public static function module_configuration_activation_screen( $module, $method ) {
2855
		$module = Jetpack::get_module_slug( $module );
2856
		add_action( 'display_activate_module_setting_' . $module, $method );
2857
	}
2858
2859
/* Installation */
2860
2861
	public static function bail_on_activation( $message, $deactivate = true ) {
2862
?>
2863
<!doctype html>
2864
<html>
2865
<head>
2866
<meta charset="<?php bloginfo( 'charset' ); ?>">
2867
<style>
2868
* {
2869
	text-align: center;
2870
	margin: 0;
2871
	padding: 0;
2872
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2873
}
2874
p {
2875
	margin-top: 1em;
2876
	font-size: 18px;
2877
}
2878
</style>
2879
<body>
2880
<p><?php echo esc_html( $message ); ?></p>
2881
</body>
2882
</html>
2883
<?php
2884
		if ( $deactivate ) {
2885
			$plugins = get_option( 'active_plugins' );
2886
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2887
			$update  = false;
2888
			foreach ( $plugins as $i => $plugin ) {
2889
				if ( $plugin === $jetpack ) {
2890
					$plugins[$i] = false;
2891
					$update = true;
2892
				}
2893
			}
2894
2895
			if ( $update ) {
2896
				update_option( 'active_plugins', array_filter( $plugins ) );
2897
			}
2898
		}
2899
		exit;
2900
	}
2901
2902
	/**
2903
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2904
	 * @static
2905
	 */
2906
	public static function plugin_activation( $network_wide ) {
2907
		Jetpack_Options::update_option( 'activated', 1 );
2908
2909
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2910
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2911
		}
2912
2913
		if ( $network_wide )
2914
			Jetpack::state( 'network_nag', true );
2915
2916
		Jetpack::plugin_initialize();
2917
	}
2918
	/**
2919
	 * Runs before bumping version numbers up to a new version
2920
	 * @param  (string) $version    Version:timestamp
2921
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2922
	 * @return null              [description]
2923
	 */
2924
	public static function do_version_bump( $version, $old_version ) {
2925
2926
		if ( ! $old_version ) { // For new sites
2927
			// Setting up jetpack manage
2928
			Jetpack::activate_manage();
2929
		}
2930
	}
2931
2932
	/**
2933
	 * Sets the internal version number and activation state.
2934
	 * @static
2935
	 */
2936
	public static function plugin_initialize() {
2937
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2938
			Jetpack_Options::update_option( 'activated', 2 );
2939
		}
2940
2941 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2942
			$version = $old_version = JETPACK__VERSION . ':' . time();
2943
			/** This action is documented in class.jetpack.php */
2944
			do_action( 'updating_jetpack_version', $version, false );
2945
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2946
		}
2947
2948
		Jetpack::load_modules();
2949
2950
		Jetpack_Options::delete_option( 'do_activate' );
2951
	}
2952
2953
	/**
2954
	 * Removes all connection options
2955
	 * @static
2956
	 */
2957
	public static function plugin_deactivation( ) {
2958
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2959
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2960
			Jetpack_Network::init()->deactivate();
2961
		} else {
2962
			Jetpack::disconnect( false );
2963
			//Jetpack_Heartbeat::init()->deactivate();
2964
		}
2965
	}
2966
2967
	/**
2968
	 * Disconnects from the Jetpack servers.
2969
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2970
	 * @static
2971
	 */
2972
	public static function disconnect( $update_activated_state = true ) {
2973
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2974
		Jetpack::clean_nonces( true );
2975
2976
		Jetpack::load_xml_rpc_client();
2977
		$xml = new Jetpack_IXR_Client();
2978
		$xml->query( 'jetpack.deregister' );
2979
2980
		Jetpack_Options::delete_option(
2981
			array(
2982
				'register',
2983
				'blog_token',
2984
				'user_token',
2985
				'user_tokens',
2986
				'master_user',
2987
				'time_diff',
2988
				'fallback_no_verify_ssl_certs',
2989
			)
2990
		);
2991
2992
		if ( $update_activated_state ) {
2993
			Jetpack_Options::update_option( 'activated', 4 );
2994
		}
2995
2996
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2997
		// Check then record unique disconnection if site has never been disconnected previously
2998
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2999
			$jetpack_unique_connection['disconnected'] = 1;
3000
		}
3001
		else {
3002
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3003
				//track unique disconnect
3004
				$jetpack = Jetpack::init();
3005
3006
				$jetpack->stat( 'connections', 'unique-disconnect' );
3007
				$jetpack->do_stats( 'server_side' );
3008
			}
3009
			// increment number of times disconnected
3010
			$jetpack_unique_connection['disconnected'] += 1;
3011
		}
3012
3013
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3014
3015
		// Disable the Heartbeat cron
3016
		Jetpack_Heartbeat::init()->deactivate();
3017
	}
3018
3019
	/**
3020
	 * Unlinks the current user from the linked WordPress.com user
3021
	 */
3022
	public static function unlink_user( $user_id = null ) {
3023
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3024
			return false;
3025
3026
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3027
3028
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3029
			return false;
3030
3031
		if ( ! isset( $tokens[ $user_id ] ) )
3032
			return false;
3033
3034
		Jetpack::load_xml_rpc_client();
3035
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3036
		$xml->query( 'jetpack.unlink_user', $user_id );
3037
3038
		unset( $tokens[ $user_id ] );
3039
3040
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3041
3042
		/**
3043
		 * Fires after the current user has been unlinked from WordPress.com.
3044
		 *
3045
		 * @since 4.1.0
3046
		 *
3047
		 * @param int $user_id The current user's ID.
3048
		 */
3049
		do_action( 'jetpack_unlinked_user', $user_id );
3050
3051
		return true;
3052
	}
3053
3054
	/**
3055
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3056
	 */
3057
	public static function try_registration() {
3058
		// Let's get some testing in beta versions and such.
3059
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3060
			// Before attempting to connect, let's make sure that the domains are viable.
3061
			$domains_to_check = array_unique( array(
3062
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3063
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3064
			) );
3065
			foreach ( $domains_to_check as $domain ) {
3066
				$result = Jetpack_Data::is_usable_domain( $domain );
3067
				if ( is_wp_error( $result ) ) {
3068
					return $result;
3069
				}
3070
			}
3071
		}
3072
3073
		$result = Jetpack::register();
3074
3075
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3076
		if ( ! $result || is_wp_error( $result ) ) {
3077
			return $result;
3078
		} else {
3079
			return true;
3080
		}
3081
	}
3082
3083
	/**
3084
	 * Tracking an internal event log. Try not to put too much chaff in here.
3085
	 *
3086
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3087
	 */
3088
	public static function log( $code, $data = null ) {
3089
		// only grab the latest 200 entries
3090
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3091
3092
		// Append our event to the log
3093
		$log_entry = array(
3094
			'time'    => time(),
3095
			'user_id' => get_current_user_id(),
3096
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3097
			'code'    => $code,
3098
		);
3099
		// Don't bother storing it unless we've got some.
3100
		if ( ! is_null( $data ) ) {
3101
			$log_entry['data'] = $data;
3102
		}
3103
		$log[] = $log_entry;
3104
3105
		// Try add_option first, to make sure it's not autoloaded.
3106
		// @todo: Add an add_option method to Jetpack_Options
3107
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3108
			Jetpack_Options::update_option( 'log', $log );
3109
		}
3110
3111
		/**
3112
		 * Fires when Jetpack logs an internal event.
3113
		 *
3114
		 * @since 3.0.0
3115
		 *
3116
		 * @param array $log_entry {
3117
		 *	Array of details about the log entry.
3118
		 *
3119
		 *	@param string time Time of the event.
3120
		 *	@param int user_id ID of the user who trigerred the event.
3121
		 *	@param int blog_id Jetpack Blog ID.
3122
		 *	@param string code Unique name for the event.
3123
		 *	@param string data Data about the event.
3124
		 * }
3125
		 */
3126
		do_action( 'jetpack_log_entry', $log_entry );
3127
	}
3128
3129
	/**
3130
	 * Get the internal event log.
3131
	 *
3132
	 * @param $event (string) - only return the specific log events
3133
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3134
	 *
3135
	 * @return array of log events || WP_Error for invalid params
3136
	 */
3137
	public static function get_log( $event = false, $num = false ) {
3138
		if ( $event && ! is_string( $event ) ) {
3139
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3140
		}
3141
3142
		if ( $num && ! is_numeric( $num ) ) {
3143
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3144
		}
3145
3146
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3147
3148
		// If nothing set - act as it did before, otherwise let's start customizing the output
3149
		if ( ! $num && ! $event ) {
3150
			return $entire_log;
3151
		} else {
3152
			$entire_log = array_reverse( $entire_log );
3153
		}
3154
3155
		$custom_log_output = array();
3156
3157
		if ( $event ) {
3158
			foreach ( $entire_log as $log_event ) {
3159
				if ( $event == $log_event[ 'code' ] ) {
3160
					$custom_log_output[] = $log_event;
3161
				}
3162
			}
3163
		} else {
3164
			$custom_log_output = $entire_log;
3165
		}
3166
3167
		if ( $num ) {
3168
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3169
		}
3170
3171
		return $custom_log_output;
3172
	}
3173
3174
	/**
3175
	 * Log modification of important settings.
3176
	 */
3177
	public static function log_settings_change( $option, $old_value, $value ) {
3178
		switch( $option ) {
3179
			case 'jetpack_sync_non_public_post_stati':
3180
				self::log( $option, $value );
3181
				break;
3182
		}
3183
	}
3184
3185
	/**
3186
	 * Return stat data for WPCOM sync
3187
	 */
3188
	function get_stat_data() {
3189
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3190
		$additional_data = $this->get_additional_stat_data();
3191
3192
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3193
	}
3194
3195
	/**
3196
	 * Get additional stat data to sync to WPCOM
3197
	 */
3198
	function get_additional_stat_data( $prefix = '' ) {
3199
		$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...
3200
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3201
		$return["{$prefix}users"]          = count_users();
3202
		$return["{$prefix}site-count"]     = 0;
3203
		if ( function_exists( 'get_blog_count' ) ) {
3204
			$return["{$prefix}site-count"] = get_blog_count();
3205
		}
3206
		return $return;
3207
	}
3208
3209
	/* Admin Pages */
3210
3211
	function admin_init() {
3212
		// If the plugin is not connected, display a connect message.
3213
		if (
3214
			// the plugin was auto-activated and needs its candy
3215
			Jetpack_Options::get_option( 'do_activate' )
3216
		||
3217
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3218
			! Jetpack_Options::get_option( 'activated' )
3219
		) {
3220
			Jetpack::plugin_initialize();
3221
		}
3222
3223
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3224
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3225
				// Show connect notice on dashboard and plugins pages
3226
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3227
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3228
			}
3229
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3230
			// Upgrade: 1.1 -> 1.1.1
3231
			// Check and see if host can verify the Jetpack servers' SSL certificate
3232
			$args = array();
3233
			Jetpack_Client::_wp_remote_request(
3234
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3235
				$args,
3236
				true
3237
			);
3238
		} else {
3239
			// Show the notice on the Dashboard only for now
3240
3241
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3242
3243
			// Identity crisis notices
3244
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3245
		}
3246
3247
		// If the plugin has just been disconnected from WP.com, show the survey notice
3248
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3249
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3250
		}
3251
3252
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3253
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3254
		}
3255
3256
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3257
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3258
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3259
3260
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3261
			// Artificially throw errors in certain whitelisted cases during plugin activation
3262
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3263
3264
			// Kick off synchronization of user role when it changes
3265
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3266
		}
3267
3268
		// Jetpack Manage Activation Screen from .com
3269
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3270
	}
3271
3272
	function admin_body_class( $admin_body_class = '' ) {
3273
		$classes = explode( ' ', trim( $admin_body_class ) );
3274
3275
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3276
3277
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3278
		return " $admin_body_class ";
3279
	}
3280
3281
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3282
		return $admin_body_class . ' jetpack-pagestyles ';
3283
	}
3284
3285
	function prepare_connect_notice() {
3286
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3287
3288
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3289
3290
		if ( Jetpack::state( 'network_nag' ) )
3291
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3292
	}
3293
	/**
3294
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3295
	 *
3296
	 * @return null
3297
	 */
3298
	function prepare_manage_jetpack_notice() {
3299
3300
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3301
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3302
	}
3303
3304
	function manage_activate_screen() {
3305
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3306
	}
3307
	/**
3308
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3309
	 * This function artificially throws errors for such cases (whitelisted).
3310
	 *
3311
	 * @param string $plugin The activated plugin.
3312
	 */
3313
	function throw_error_on_activate_plugin( $plugin ) {
3314
		$active_modules = Jetpack::get_active_modules();
3315
3316
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3317
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3318
			$throw = false;
3319
3320
			// Try and make sure it really was the stats plugin
3321
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3322
				if ( 'stats.php' == basename( $plugin ) ) {
3323
					$throw = true;
3324
				}
3325
			} else {
3326
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3327
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3328
					$throw = true;
3329
				}
3330
			}
3331
3332
			if ( $throw ) {
3333
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3334
			}
3335
		}
3336
	}
3337
3338
	function intercept_plugin_error_scrape_init() {
3339
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3340
	}
3341
3342
	function intercept_plugin_error_scrape( $action, $result ) {
3343
		if ( ! $result ) {
3344
			return;
3345
		}
3346
3347
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3348
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3349
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3350
			}
3351
		}
3352
	}
3353
3354
	function add_remote_request_handlers() {
3355
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3356
	}
3357
3358
	function remote_request_handlers() {
3359
		switch ( current_filter() ) {
3360
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3361
			$response = $this->upload_handler();
3362
			break;
3363
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
3364
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3365
			break;
3366
		}
3367
3368
		if ( ! $response ) {
3369
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3370
		}
3371
3372
		if ( is_wp_error( $response ) ) {
3373
			$status_code       = $response->get_error_data();
3374
			$error             = $response->get_error_code();
3375
			$error_description = $response->get_error_message();
3376
3377
			if ( ! is_int( $status_code ) ) {
3378
				$status_code = 400;
3379
			}
3380
3381
			status_header( $status_code );
3382
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3383
		}
3384
3385
		status_header( 200 );
3386
		if ( true === $response ) {
3387
			exit;
3388
		}
3389
3390
		die( json_encode( (object) $response ) );
3391
	}
3392
3393
	function upload_handler() {
3394
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3395
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3396
		}
3397
3398
		$user = wp_authenticate( '', '' );
3399
		if ( ! $user || is_wp_error( $user ) ) {
3400
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3401
		}
3402
3403
		wp_set_current_user( $user->ID );
3404
3405
		if ( ! current_user_can( 'upload_files' ) ) {
3406
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3407
		}
3408
3409
		if ( empty( $_FILES ) ) {
3410
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3411
		}
3412
3413
		foreach ( array_keys( $_FILES ) as $files_key ) {
3414
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3415
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3416
			}
3417
		}
3418
3419
		$media_keys = array_keys( $_FILES['media'] );
3420
3421
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3422
		if ( ! $token || is_wp_error( $token ) ) {
3423
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3424
		}
3425
3426
		$uploaded_files = array();
3427
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3428
		unset( $GLOBALS['post'] );
3429
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3430
			$file = array();
3431
			foreach ( $media_keys as $media_key ) {
3432
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3433
			}
3434
3435
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3436
3437
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3438
			if ( $hmac_provided !== $hmac_file ) {
3439
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3440
				continue;
3441
			}
3442
3443
			$_FILES['.jetpack.upload.'] = $file;
3444
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3445
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3446
				$post_id = 0;
3447
			}
3448
			$attachment_id = media_handle_upload(
3449
				'.jetpack.upload.',
3450
				$post_id,
3451
				array(),
3452
				array(
3453
					'action' => 'jetpack_upload_file',
3454
				)
3455
			);
3456
3457
			if ( ! $attachment_id ) {
3458
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3459
			} elseif ( is_wp_error( $attachment_id ) ) {
3460
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3461
			} else {
3462
				$attachment = get_post( $attachment_id );
3463
				$uploaded_files[$index] = (object) array(
3464
					'id'   => (string) $attachment_id,
3465
					'file' => $attachment->post_title,
3466
					'url'  => wp_get_attachment_url( $attachment_id ),
3467
					'type' => $attachment->post_mime_type,
3468
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3469
				);
3470
			}
3471
		}
3472
		if ( ! is_null( $global_post ) ) {
3473
			$GLOBALS['post'] = $global_post;
3474
		}
3475
3476
		return $uploaded_files;
3477
	}
3478
3479
	/**
3480
	 * Add help to the Jetpack page
3481
	 *
3482
	 * @since Jetpack (1.2.3)
3483
	 * @return false if not the Jetpack page
3484
	 */
3485
	function admin_help() {
3486
		$current_screen = get_current_screen();
3487
3488
		// Overview
3489
		$current_screen->add_help_tab(
3490
			array(
3491
				'id'		=> 'home',
3492
				'title'		=> __( 'Home', 'jetpack' ),
3493
				'content'	=>
3494
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3495
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3496
					'<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>',
3497
			)
3498
		);
3499
3500
		// Screen Content
3501
		if ( current_user_can( 'manage_options' ) ) {
3502
			$current_screen->add_help_tab(
3503
				array(
3504
					'id'		=> 'settings',
3505
					'title'		=> __( 'Settings', 'jetpack' ),
3506
					'content'	=>
3507
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3508
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3509
						'<ol>' .
3510
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3511
							'<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>' .
3512
						'</ol>' .
3513
						'<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>'
3514
				)
3515
			);
3516
		}
3517
3518
		// Help Sidebar
3519
		$current_screen->set_help_sidebar(
3520
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3521
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3522
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3523
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3524
		);
3525
	}
3526
3527
	function admin_menu_css() {
3528
		wp_enqueue_style( 'jetpack-icons' );
3529
	}
3530
3531
	function admin_menu_order() {
3532
		return true;
3533
	}
3534
3535 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3536
		$jp_menu_order = array();
3537
3538
		foreach ( $menu_order as $index => $item ) {
3539
			if ( $item != 'jetpack' ) {
3540
				$jp_menu_order[] = $item;
3541
			}
3542
3543
			if ( $index == 0 ) {
3544
				$jp_menu_order[] = 'jetpack';
3545
			}
3546
		}
3547
3548
		return $jp_menu_order;
3549
	}
3550
3551
	function admin_head() {
3552 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3553
			/** This action is documented in class.jetpack-admin-page.php */
3554
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3555
	}
3556
3557
	function admin_banner_styles() {
3558
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3559
3560
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3561
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3562
		wp_style_add_data( 'jetpack', 'suffix', $min );
3563
	}
3564
3565
	function admin_scripts() {
3566
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3567
		wp_localize_script(
3568
			'jetpack-js',
3569
			'jetpackL10n',
3570
			array(
3571
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3572
				'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?",
3573
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3574
			)
3575
		);
3576
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3577
	}
3578
3579
	function plugin_action_links( $actions ) {
3580
3581
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3582
3583
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3584
			return array_merge(
3585
				$jetpack_home,
3586
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3587
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3588
				$actions
3589
				);
3590
			}
3591
3592
		return array_merge( $jetpack_home, $actions );
3593
	}
3594
3595
	function admin_connect_notice() {
3596
		// Don't show the connect notice anywhere but the plugins.php after activating
3597
		$current = get_current_screen();
3598
		if ( 'plugins' !== $current->parent_base )
3599
			return;
3600
3601
		if ( ! current_user_can( 'jetpack_connect' ) )
3602
			return;
3603
3604
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3605
		?>
3606
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3607
			<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>
3608
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3609
				<div class="jp-banner__content is-connection">
3610
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3611
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3612
				</div>
3613
				<div class="jp-banner__action-container is-connection">
3614
						<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3615
				</div>
3616 View Code Duplication
			<?php else : ?>
3617
				<div class="jp-banner__content">
3618
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3619
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3620
				</div>
3621
				<div class="jp-banner__action-container">
3622
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3623
				</div>
3624
			<?php endif; ?>
3625
		</div>
3626
3627
		<?php
3628
	}
3629
3630
	/**
3631
	 * This is the first banner
3632
	 * It should be visible only to user that can update the option
3633
	 * Are not connected
3634
	 *
3635
	 * @return null
3636
	 */
3637
	function admin_jetpack_manage_notice() {
3638
		$screen = get_current_screen();
3639
3640
		// Don't show the connect notice on the jetpack settings page.
3641
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3642
			return;
3643
3644
		// Only show it if don't have the managment option set.
3645
		// And not dismissed it already.
3646
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3647
			return;
3648
		}
3649
3650
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3651
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3652
		/**
3653
		 * I think it would be great to have different wordsing depending on where you are
3654
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3655
		 * etc..
3656
		 */
3657
3658
		?>
3659
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3660
			<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>
3661
			<div class="jp-banner__content">
3662
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3663
				<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>
3664
			</div>
3665
			<div class="jp-banner__action-container is-opt-in">
3666
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3667
			</div>
3668
		</div>
3669
		<?php
3670
	}
3671
3672
	/**
3673
	 * Returns the url that the user clicks to remove the notice for the big banner
3674
	 * @return (string)
3675
	 */
3676
	function opt_out_jetpack_manage_url() {
3677
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3678
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3679
	}
3680
	/**
3681
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3682
	 * @return (string)
3683
	 */
3684
	function opt_in_jetpack_manage_url() {
3685
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3686
	}
3687
3688
	function opt_in_jetpack_manage_notice() {
3689
		?>
3690
		<div class="wrap">
3691
			<div id="message" class="jetpack-message is-opt-in">
3692
				<?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' ); ?>
3693
			</div>
3694
		</div>
3695
		<?php
3696
3697
	}
3698
	/**
3699
	 * Determines whether to show the notice of not true = display notice
3700
	 * @return (bool)
3701
	 */
3702
	function can_display_jetpack_manage_notice() {
3703
		// never display the notice to users that can't do anything about it anyways
3704
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3705
			return false;
3706
3707
		// don't display if we are in development more
3708
		if( Jetpack::is_development_mode() ) {
3709
			return false;
3710
		}
3711
		// don't display if the site is private
3712
		if(  ! Jetpack_Options::get_option( 'public' ) )
3713
			return false;
3714
3715
		/**
3716
		 * Should the Jetpack Remote Site Management notice be displayed.
3717
		 *
3718
		 * @since 3.3.0
3719
		 *
3720
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3721
		 */
3722
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3723
	}
3724
3725
	function network_connect_notice() {
3726
		?>
3727
		<div id="message" class="updated jetpack-message">
3728
			<div class="squeezer">
3729
				<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>
3730
			</div>
3731
		</div>
3732
		<?php
3733
	}
3734
3735
	public static function jetpack_comment_notice() {
3736
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3737
			return '';
3738
		}
3739
3740
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3741
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3742
3743
		if ( $jetpack_old_version ) {
3744
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3745
				return '';
3746
			}
3747
		}
3748
3749
		if ( $jetpack_new_version ) {
3750
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3751
				return '';
3752
			}
3753
		}
3754
3755
		return '<br /><br />' . sprintf(
3756
			__( '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' ),
3757
			wp_nonce_url(
3758
				Jetpack::admin_url(
3759
					array(
3760
						'page'   => 'jetpack',
3761
						'action' => 'activate',
3762
						'module' => 'comments',
3763
					)
3764
				),
3765
				'jetpack_activate-comments'
3766
			),
3767
			__( 'click here', 'jetpack' )
3768
		);
3769
	}
3770
3771
	/**
3772
	 * Show the survey link when the user has just disconnected Jetpack.
3773
	 */
3774
	function disconnect_survey_notice() {
3775
		?>
3776
		<div class="wrap">
3777
			<div id="message" class="jetpack-message stay-visible">
3778
				<div class="squeezer">
3779
					<h2>
3780
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3781
						<br />
3782
						<?php echo sprintf(
3783
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3784
							'https://jetpack.com/survey-disconnected/',
3785
							'_blank'
3786
						); ?>
3787
					</h2>
3788
				</div>
3789
			</div>
3790
		</div>
3791
		<?php
3792
	}
3793
3794
	/*
3795
	 * Registration flow:
3796
	 * 1 - ::admin_page_load() action=register
3797
	 * 2 - ::try_registration()
3798
	 * 3 - ::register()
3799
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3800
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3801
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3802
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3803
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3804
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3805
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3806
	 *       jetpack_id, jetpack_secret, jetpack_public
3807
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3808
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3809
	 * 5 - user logs in with WP.com account
3810
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3811
	 *		- Jetpack_Client_Server::authorize()
3812
	 *		- Jetpack_Client_Server::get_token()
3813
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3814
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3815
	 *			- which responds with access_token, token_type, scope
3816
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3817
	 *		- Jetpack::activate_default_modules()
3818
	 *     		- Deactivates deprecated plugins
3819
	 *     		- Activates all default modules
3820
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3821
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3822
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3823
	 *     Done!
3824
	 */
3825
3826
	/**
3827
	 * Handles the page load events for the Jetpack admin page
3828
	 */
3829
	function admin_page_load() {
3830
		$error = false;
3831
3832
		// Make sure we have the right body class to hook stylings for subpages off of.
3833
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3834
3835
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3836
			// Should only be used in intermediate redirects to preserve state across redirects
3837
			Jetpack::restate();
3838
		}
3839
3840
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3841
			// User clicked in the iframe to link their accounts
3842
			if ( ! Jetpack::is_user_connected() ) {
3843
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3844
				if ( isset( $_GET['notes_iframe'] ) )
3845
					$connect_url .= '&notes_iframe';
3846
				wp_redirect( $connect_url );
3847
				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...
3848
			} else {
3849
				Jetpack::state( 'message', 'already_authorized' );
3850
				wp_safe_redirect( Jetpack::admin_url() );
3851
				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...
3852
			}
3853
		}
3854
3855
3856
		if ( isset( $_GET['action'] ) ) {
3857
			switch ( $_GET['action'] ) {
3858
			case 'authorize':
3859
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3860
					Jetpack::state( 'message', 'already_authorized' );
3861
					wp_safe_redirect( Jetpack::admin_url() );
3862
					exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3863
				}
3864
				Jetpack::log( 'authorize' );
3865
				$client_server = new Jetpack_Client_Server;
3866
				$client_server->client_authorize();
3867
				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...
3868
			case 'register' :
3869
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3870
					$error = 'cheatin';
3871
					break;
3872
				}
3873
				check_admin_referer( 'jetpack-register' );
3874
				Jetpack::log( 'register' );
3875
				Jetpack::maybe_set_version_option();
3876
				$registered = Jetpack::try_registration();
3877
				if ( is_wp_error( $registered ) ) {
3878
					$error = $registered->get_error_code();
3879
					Jetpack::state( 'error_description', $registered->get_error_message() );
3880
					break;
3881
				}
3882
3883
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3884
3885
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3886
				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...
3887
			case 'activate' :
3888
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3889
					$error = 'cheatin';
3890
					break;
3891
				}
3892
3893
				$module = stripslashes( $_GET['module'] );
3894
				check_admin_referer( "jetpack_activate-$module" );
3895
				Jetpack::log( 'activate', $module );
3896
				Jetpack::activate_module( $module );
3897
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3898
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3899
				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...
3900
			case 'activate_default_modules' :
3901
				check_admin_referer( 'activate_default_modules' );
3902
				Jetpack::log( 'activate_default_modules' );
3903
				Jetpack::restate();
3904
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3905
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3906
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3907
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3908
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3909
				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...
3910
			case 'disconnect' :
3911
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3912
					$error = 'cheatin';
3913
					break;
3914
				}
3915
3916
				check_admin_referer( 'jetpack-disconnect' );
3917
				Jetpack::log( 'disconnect' );
3918
				Jetpack::disconnect();
3919
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3920
				exit;
3921
			case 'reconnect' :
3922
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3923
					$error = 'cheatin';
3924
					break;
3925
				}
3926
3927
				check_admin_referer( 'jetpack-reconnect' );
3928
				Jetpack::log( 'reconnect' );
3929
				$this->disconnect();
3930
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3931
				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...
3932 View Code Duplication
			case 'deactivate' :
3933
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3934
					$error = 'cheatin';
3935
					break;
3936
				}
3937
3938
				$modules = stripslashes( $_GET['module'] );
3939
				check_admin_referer( "jetpack_deactivate-$modules" );
3940
				foreach ( explode( ',', $modules ) as $module ) {
3941
					Jetpack::log( 'deactivate', $module );
3942
					Jetpack::deactivate_module( $module );
3943
					Jetpack::state( 'message', 'module_deactivated' );
3944
				}
3945
				Jetpack::state( 'module', $modules );
3946
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3947
				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...
3948
			case 'unlink' :
3949
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3950
				check_admin_referer( 'jetpack-unlink' );
3951
				Jetpack::log( 'unlink' );
3952
				$this->unlink_user();
3953
				Jetpack::state( 'message', 'unlinked' );
3954
				if ( 'sub-unlink' == $redirect ) {
3955
					wp_safe_redirect( admin_url() );
3956
				} else {
3957
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3958
				}
3959
				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...
3960
			default:
3961
				/**
3962
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3963
				 *
3964
				 * @since 2.6.0
3965
				 *
3966
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3967
				 */
3968
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3969
			}
3970
		}
3971
3972
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3973
			self::activate_new_modules( true );
3974
		}
3975
3976
		switch ( $error ) {
3977
		case 'cheatin' :
3978
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3979
			break;
3980
		case 'access_denied' :
3981
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'http://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
3982
			break;
3983
		case 'wrong_state' :
3984
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3985
			break;
3986
		case 'invalid_client' :
3987
			// @todo re-register instead of deactivate/reactivate
3988
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3989
			break;
3990
		case 'invalid_grant' :
3991
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3992
			break;
3993
		case 'site_inaccessible' :
3994
		case 'site_requires_authorization' :
3995
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3996
			break;
3997
		case 'module_activation_failed' :
3998
			$module = Jetpack::state( 'module' );
3999
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4000
				$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'] );
4001
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
4002
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
4003
				}
4004
			} else {
4005
				$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' );
4006
			}
4007
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
4008
				$this->error .= "<br />\n";
4009
				$this->error .= $php_errors;
4010
			}
4011
			break;
4012
		case 'master_user_required' :
4013
			$module = Jetpack::state( 'module' );
4014
			$module_name = '';
4015
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
4016
				$module_name = $mod['name'];
4017
			}
4018
4019
			$master_user = Jetpack_Options::get_option( 'master_user' );
4020
			$master_userdata = get_userdata( $master_user ) ;
4021
			if ( $master_userdata ) {
4022
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
4023
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
4024
				} else {
4025
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
4026
				}
4027
				$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 ) );
4028
4029
			} else {
4030
				$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 );
4031
			}
4032
			break;
4033
		case 'not_public' :
4034
			$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' );
4035
			break;
4036
		case 'wpcom_408' :
4037
		case 'wpcom_5??' :
4038
		case 'wpcom_bad_response' :
4039
		case 'wpcom_outage' :
4040
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
4041
			break;
4042
		case 'register_http_request_failed' :
4043
		case 'token_http_request_failed' :
4044
			$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>" );
4045
			break;
4046
		default :
4047
			if ( empty( $error ) ) {
4048
				break;
4049
			}
4050
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
4051
			// no break: fall through
4052
		case 'no_role' :
4053
		case 'no_cap' :
4054
		case 'no_code' :
4055
		case 'no_state' :
4056
		case 'invalid_state' :
4057
		case 'invalid_request' :
4058
		case 'invalid_scope' :
4059
		case 'unsupported_response_type' :
4060
		case 'invalid_token' :
4061
		case 'no_token' :
4062
		case 'missing_secrets' :
4063
		case 'home_missing' :
4064
		case 'siteurl_missing' :
4065
		case 'gmt_offset_missing' :
4066
		case 'site_name_missing' :
4067
		case 'secret_1_missing' :
4068
		case 'secret_2_missing' :
4069
		case 'site_lang_missing' :
4070
		case 'home_malformed' :
4071
		case 'siteurl_malformed' :
4072
		case 'gmt_offset_malformed' :
4073
		case 'timezone_string_malformed' :
4074
		case 'site_name_malformed' :
4075
		case 'secret_1_malformed' :
4076
		case 'secret_2_malformed' :
4077
		case 'site_lang_malformed' :
4078
		case 'secrets_mismatch' :
4079
		case 'verify_secret_1_missing' :
4080
		case 'verify_secret_1_malformed' :
4081
		case 'verify_secrets_missing' :
4082
		case 'verify_secrets_mismatch' :
4083
			$error = esc_html( $error );
4084
			$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>" );
4085
			if ( ! Jetpack::is_active() ) {
4086
				$this->error .= '<br />';
4087
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4088
			}
4089
			break;
4090
		}
4091
4092
		$message_code = Jetpack::state( 'message' );
4093
4094
		$active_state = Jetpack::state( 'activated_modules' );
4095
		if ( ! empty( $active_state ) ) {
4096
			$available    = Jetpack::get_available_modules();
4097
			$active_state = explode( ',', $active_state );
4098
			$active_state = array_intersect( $active_state, $available );
4099
			if ( count( $active_state ) ) {
4100
				foreach ( $active_state as $mod ) {
4101
					$this->stat( 'module-activated', $mod );
4102
				}
4103
			} else {
4104
				$active_state = false;
4105
			}
4106
		}
4107
		if( Jetpack::state( 'optin-manage' ) ) {
4108
			$activated_manage = $message_code;
4109
			$message_code = 'jetpack-manage';
4110
4111
		}
4112
		switch ( $message_code ) {
4113
		case 'modules_activated' :
4114
			$this->message = sprintf(
4115
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4116
				JETPACK__VERSION
4117
			);
4118
4119
			if ( $active_state ) {
4120
				$titles = array();
4121 View Code Duplication
				foreach ( $active_state as $mod ) {
4122
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4123
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4124
					}
4125
				}
4126
				if ( $titles ) {
4127
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4128
				}
4129
			}
4130
4131
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4132
				$titles = array();
4133 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4134
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4135
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4136
					}
4137
				}
4138
				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...
4139
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4140
				}
4141
			}
4142
4143
			$this->message .= Jetpack::jetpack_comment_notice();
4144
			break;
4145
		case 'jetpack-manage':
4146
			$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>';
4147
			if ( $activated_manage ) {
4148
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4149
			}
4150
			break;
4151
		case 'module_activated' :
4152
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4153
				$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'] );
4154
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4155
			}
4156
			break;
4157
4158
		case 'module_deactivated' :
4159
			$modules = Jetpack::state( 'module' );
4160
			if ( ! $modules ) {
4161
				break;
4162
			}
4163
4164
			$module_names = array();
4165
			foreach ( explode( ',', $modules ) as $module_slug ) {
4166
				$module = Jetpack::get_module( $module_slug );
4167
				if ( $module ) {
4168
					$module_names[] = $module['name'];
4169
				}
4170
4171
				$this->stat( 'module-deactivated', $module_slug );
4172
			}
4173
4174
			if ( ! $module_names ) {
4175
				break;
4176
			}
4177
4178
			$this->message = wp_sprintf(
4179
				_nx(
4180
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4181
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4182
					count( $module_names ),
4183
					'%l = list of Jetpack module/feature names',
4184
					'jetpack'
4185
				),
4186
				$module_names
4187
			);
4188
			break;
4189
4190
		case 'module_configured' :
4191
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4192
			break;
4193
4194
		case 'already_authorized' :
4195
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4196
			break;
4197
4198
		case 'authorized' :
4199
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4200
			$this->message .= Jetpack::jetpack_comment_notice();
4201
			break;
4202
4203
		case 'linked' :
4204
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4205
			$this->message .= Jetpack::jetpack_comment_notice();
4206
			break;
4207
4208
		case 'unlinked' :
4209
			$user = wp_get_current_user();
4210
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4211
			break;
4212
4213
		case 'switch_master' :
4214
			global $current_user;
4215
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4216
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4217
			if ( $is_master_user ) {
4218
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4219
			} else {
4220
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4221
			}
4222
			break;
4223
		}
4224
4225
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4226
4227
		if ( ! empty( $deactivated_plugins ) ) {
4228
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4229
			$deactivated_titles  = array();
4230
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4231
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4232
					continue;
4233
				}
4234
4235
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4236
			}
4237
4238
			if ( $deactivated_titles ) {
4239
				if ( $this->message ) {
4240
					$this->message .= "<br /><br />\n";
4241
				}
4242
4243
				$this->message .= wp_sprintf(
4244
					_n(
4245
						'Jetpack contains the most recent version of the old %l plugin.',
4246
						'Jetpack contains the most recent versions of the old %l plugins.',
4247
						count( $deactivated_titles ),
4248
						'jetpack'
4249
					),
4250
					$deactivated_titles
4251
				);
4252
4253
				$this->message .= "<br />\n";
4254
4255
				$this->message .= _n(
4256
					'The old version has been deactivated and can be removed from your site.',
4257
					'The old versions have been deactivated and can be removed from your site.',
4258
					count( $deactivated_titles ),
4259
					'jetpack'
4260
				);
4261
			}
4262
		}
4263
4264
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4265
4266
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4267
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4268
		}
4269
4270 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4271
			/**
4272
			 * Fires when a module configuration page is loaded.
4273
			 * The dynamic part of the hook is the configure parameter from the URL.
4274
			 *
4275
			 * @since 1.1.0
4276
			 */
4277
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4278
		}
4279
4280
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4281
	}
4282
4283
	function admin_notices() {
4284
4285
		if ( $this->error ) {
4286
?>
4287
<div id="message" class="jetpack-message jetpack-err">
4288
	<div class="squeezer">
4289
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4290
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4291
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4292
<?php	endif; ?>
4293
	</div>
4294
</div>
4295
<?php
4296
		}
4297
4298
		if ( $this->message ) {
4299
?>
4300
<div id="message" class="jetpack-message">
4301
	<div class="squeezer">
4302
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4303
	</div>
4304
</div>
4305
<?php
4306
		}
4307
4308
		if ( $this->privacy_checks ) :
4309
			$module_names = $module_slugs = array();
4310
4311
			$privacy_checks = explode( ',', $this->privacy_checks );
4312
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4313
			foreach ( $privacy_checks as $module_slug ) {
4314
				$module = Jetpack::get_module( $module_slug );
4315
				if ( ! $module ) {
4316
					continue;
4317
				}
4318
4319
				$module_slugs[] = $module_slug;
4320
				$module_names[] = "<strong>{$module['name']}</strong>";
4321
			}
4322
4323
			$module_slugs = join( ',', $module_slugs );
4324
?>
4325
<div id="message" class="jetpack-message jetpack-err">
4326
	<div class="squeezer">
4327
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4328
		<p><?php
4329
			echo wp_kses(
4330
				wptexturize(
4331
					wp_sprintf(
4332
						_nx(
4333
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4334
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4335
							count( $privacy_checks ),
4336
							'%l = list of Jetpack module/feature names',
4337
							'jetpack'
4338
						),
4339
						$module_names
4340
					)
4341
				),
4342
				array( 'strong' => true )
4343
			);
4344
4345
			echo "\n<br />\n";
4346
4347
			echo wp_kses(
4348
				sprintf(
4349
					_nx(
4350
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4351
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4352
						count( $privacy_checks ),
4353
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4354
						'jetpack'
4355
					),
4356
					wp_nonce_url(
4357
						Jetpack::admin_url(
4358
							array(
4359
								'page'   => 'jetpack',
4360
								'action' => 'deactivate',
4361
								'module' => urlencode( $module_slugs ),
4362
							)
4363
						),
4364
						"jetpack_deactivate-$module_slugs"
4365
					),
4366
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4367
				),
4368
				array( 'a' => array( 'href' => true, 'title' => true ) )
4369
			);
4370
		?></p>
4371
	</div>
4372
</div>
4373
<?php endif;
4374
	// only display the notice if the other stuff is not there
4375
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4376
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4377
			$this->opt_in_jetpack_manage_notice();
4378
		}
4379
	}
4380
4381
	/**
4382
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4383
	 */
4384
	function stat( $group, $detail ) {
4385
		if ( ! isset( $this->stats[ $group ] ) )
4386
			$this->stats[ $group ] = array();
4387
		$this->stats[ $group ][] = $detail;
4388
	}
4389
4390
	/**
4391
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4392
	 */
4393
	function do_stats( $method = '' ) {
4394
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4395
			foreach ( $this->stats as $group => $stats ) {
4396
				if ( is_array( $stats ) && count( $stats ) ) {
4397
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4398
					if ( 'server_side' === $method ) {
4399
						self::do_server_side_stat( $args );
4400
					} else {
4401
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4402
					}
4403
				}
4404
				unset( $this->stats[ $group ] );
4405
			}
4406
		}
4407
	}
4408
4409
	/**
4410
	 * Runs stats code for a one-off, server-side.
4411
	 *
4412
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4413
	 *
4414
	 * @return bool If it worked.
4415
	 */
4416
	static function do_server_side_stat( $args ) {
4417
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4418
		if ( is_wp_error( $response ) )
4419
			return false;
4420
4421
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4422
			return false;
4423
4424
		return true;
4425
	}
4426
4427
	/**
4428
	 * Builds the stats url.
4429
	 *
4430
	 * @param $args array|string The arguments to append to the URL.
4431
	 *
4432
	 * @return string The URL to be pinged.
4433
	 */
4434
	static function build_stats_url( $args ) {
4435
		$defaults = array(
4436
			'v'    => 'wpcom2',
4437
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4438
		);
4439
		$args     = wp_parse_args( $args, $defaults );
4440
		/**
4441
		 * Filter the URL used as the Stats tracking pixel.
4442
		 *
4443
		 * @since 2.3.2
4444
		 *
4445
		 * @param string $url Base URL used as the Stats tracking pixel.
4446
		 */
4447
		$base_url = apply_filters(
4448
			'jetpack_stats_base_url',
4449
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4450
		);
4451
		$url      = add_query_arg( $args, $base_url );
4452
		return $url;
4453
	}
4454
4455
	function translate_current_user_to_role() {
4456
		foreach ( $this->capability_translations as $role => $cap ) {
4457
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4458
				return $role;
4459
			}
4460
		}
4461
4462
		return false;
4463
	}
4464
4465
	function translate_role_to_cap( $role ) {
4466
		if ( ! isset( $this->capability_translations[$role] ) ) {
4467
			return false;
4468
		}
4469
4470
		return $this->capability_translations[$role];
4471
	}
4472
4473
	function sign_role( $role ) {
4474
		if ( ! $user_id = (int) get_current_user_id() ) {
4475
			return false;
4476
		}
4477
4478
		$token = Jetpack_Data::get_access_token();
4479
		if ( ! $token || is_wp_error( $token ) ) {
4480
			return false;
4481
		}
4482
4483
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4484
	}
4485
4486
4487
	/**
4488
	 * Builds a URL to the Jetpack connection auth page
4489
	 *
4490
	 * @since 3.9.5
4491
	 *
4492
	 * @param bool $raw If true, URL will not be escaped.
4493
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4494
	 *                              If string, will be a custom redirect.
4495
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4496
	 *
4497
	 * @return string Connect URL
4498
	 */
4499
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4500
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4501
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4502
			if( is_network_admin() ) {
4503
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4504
			    'admin.php?page=jetpack-settings' ), $url );
4505
			}
4506
		} else {
4507
			require_once JETPACK__GLOTPRESS_LOCALES_PATH;
4508
			$role = $this->translate_current_user_to_role();
4509
			$signed_role = $this->sign_role( $role );
4510
4511
			$user = wp_get_current_user();
4512
4513
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4514
4515
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4516
4517
			if( isset( $_REQUEST['is_multisite'] ) ) {
4518
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4519
			}
4520
4521
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4522
			@list( $secret ) = explode( ':', $secrets );
4523
4524
			$args = urlencode_deep(
4525
				array(
4526
					'response_type' => 'code',
4527
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4528
					'redirect_uri'  => add_query_arg(
4529
						array(
4530
							'action'   => 'authorize',
4531
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4532
							'redirect' => urlencode( $redirect ),
4533
						),
4534
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4535
					),
4536
					'state'         => $user->ID,
4537
					'scope'         => $signed_role,
4538
					'user_email'    => $user->user_email,
4539
					'user_login'    => $user->user_login,
4540
					'is_active'     => Jetpack::is_active(),
4541
					'jp_version'    => JETPACK__VERSION,
4542
					'auth_type'     => 'calypso',
4543
					'secret'        => $secret,
4544
					'locale'        => isset( $gp_locale->slug ) ? $gp_locale->slug : '',
4545
					'blogname'      => get_option( 'blogname' ),
4546
				)
4547
			);
4548
4549
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4550
		}
4551
4552
		if ( $from ) {
4553
			$url = add_query_arg( 'from', $from, $url );
4554
		}
4555
4556
		if ( isset( $_GET['calypso_env'] ) ) {
4557
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4558
		}
4559
4560
		return $raw ? $url : esc_url( $url );
4561
	}
4562
4563
	function build_reconnect_url( $raw = false ) {
4564
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4565
		return $raw ? $url : esc_url( $url );
4566
	}
4567
4568
	public static function admin_url( $args = null ) {
4569
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4570
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4571
		return $url;
4572
	}
4573
4574
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4575
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4576
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4577
	}
4578
4579
	function dismiss_jetpack_notice() {
4580
4581
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4582
			return;
4583
		}
4584
4585
		switch( $_GET['jetpack-notice'] ) {
4586
			case 'dismiss':
4587
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4588
4589
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4590
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4591
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4592
				}
4593
				break;
4594 View Code Duplication
			case 'jetpack-manage-opt-out':
4595
4596
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4597
					// Don't show the banner again
4598
4599
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4600
					// redirect back to the page that had the notice
4601
					if ( wp_get_referer() ) {
4602
						wp_safe_redirect( wp_get_referer() );
4603
					} else {
4604
						// Take me to Jetpack
4605
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4606
					}
4607
				}
4608
				break;
4609 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4610
4611
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4612
					// Don't show the banner again
4613
4614
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4615
					// redirect back to the page that had the notice
4616
					if ( wp_get_referer() ) {
4617
						wp_safe_redirect( wp_get_referer() );
4618
					} else {
4619
						// Take me to Jetpack
4620
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4621
					}
4622
				}
4623
				break;
4624
			case 'jetpack-manage-opt-in':
4625
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4626
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4627
4628
					$redirection_url = Jetpack::admin_url();
4629
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4630
4631
					// Don't redirect form the Jetpack Setting Page
4632
					$referer_parsed = parse_url ( wp_get_referer() );
4633
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4634
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4635
						// Take the user to Jetpack home except when on the setting page
4636
						$redirection_url = wp_get_referer();
4637
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4638
					}
4639
					// Also update the JSON API FULL MANAGEMENT Option
4640
					Jetpack::activate_module( 'manage', false, false );
4641
4642
					// Special Message when option in.
4643
					Jetpack::state( 'optin-manage', 'true' );
4644
					// Activate the Module if not activated already
4645
4646
					// Redirect properly
4647
					wp_safe_redirect( $redirection_url );
4648
4649
				}
4650
				break;
4651
		}
4652
	}
4653
4654
	function debugger_page() {
4655
		nocache_headers();
4656
		if ( ! current_user_can( 'manage_options' ) ) {
4657
			die( '-1' );
4658
		}
4659
		Jetpack_Debugger::jetpack_debug_display_handler();
4660
		exit;
4661
	}
4662
4663
	public static function admin_screen_configure_module( $module_id ) {
4664
4665
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4666
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4667
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4668
				/**
4669
				 * Fires to diplay a custom module activation screen.
4670
				 *
4671
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4672
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4673
				 *
4674
				 * @module manage
4675
				 *
4676
				 * @since 3.8.0
4677
				 *
4678
				 * @param int $module_id Module ID.
4679
				 */
4680
				do_action( 'display_activate_module_setting_' . $module_id );
4681
			} else {
4682
				self::display_activate_module_link( $module_id );
4683
			}
4684
4685
			return false;
4686
		} ?>
4687
4688
		<div id="jp-settings-screen" style="position: relative">
4689
			<h3>
4690
			<?php
4691
				$module = Jetpack::get_module( $module_id );
4692
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4693
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4694
			?>
4695
			</h3>
4696
			<?php
4697
				/**
4698
				 * Fires within the displayed message when a feature configuation is updated.
4699
				 *
4700
				 * @since 3.4.0
4701
				 *
4702
				 * @param int $module_id Module ID.
4703
				 */
4704
				do_action( 'jetpack_notices_update_settings', $module_id );
4705
				/**
4706
				 * Fires when a feature configuation screen is loaded.
4707
				 * The dynamic part of the hook, $module_id, is the module ID.
4708
				 *
4709
				 * @since 1.1.0
4710
				 */
4711
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4712
			?>
4713
		</div><?php
4714
	}
4715
4716
	/**
4717
	 * Display link to activate the module to see the settings screen.
4718
	 * @param  string $module_id
4719
	 * @return null
4720
	 */
4721
	public static function display_activate_module_link( $module_id ) {
4722
4723
		$info =  Jetpack::get_module( $module_id );
4724
		$extra = '';
4725
		$activate_url = wp_nonce_url(
4726
				Jetpack::admin_url(
4727
					array(
4728
						'page'   => 'jetpack',
4729
						'action' => 'activate',
4730
						'module' => $module_id,
4731
					)
4732
				),
4733
				"jetpack_activate-$module_id"
4734
			);
4735
4736
		?>
4737
4738
		<div class="wrap configure-module">
4739
			<div id="jp-settings-screen">
4740
				<?php
4741
				if ( $module_id == 'json-api' ) {
4742
4743
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4744
4745
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4746
4747
					$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' );
4748
4749
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4750
				} ?>
4751
4752
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4753
				<div class="narrow">
4754
					<p><?php echo  $info['description']; ?></p>
4755
					<?php if( $extra ) { ?>
4756
					<p><?php echo esc_html( $extra ); ?></p>
4757
					<?php } ?>
4758
					<p>
4759
						<?php
4760
						if( wp_get_referer() ) {
4761
							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() );
4762
						} else {
4763
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4764
						} ?>
4765
					</p>
4766
				</div>
4767
4768
			</div>
4769
		</div>
4770
4771
		<?php
4772
	}
4773
4774
	public static function sort_modules( $a, $b ) {
4775
		if ( $a['sort'] == $b['sort'] )
4776
			return 0;
4777
4778
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4779
	}
4780
4781 View Code Duplication
	function sync_reindex_trigger() {
4782
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4783
			echo json_encode( $this->sync->reindex_trigger() );
4784
		} else {
4785
			echo '{"status":"ERROR"}';
4786
		}
4787
		exit;
4788
	}
4789
4790 View Code Duplication
	function sync_reindex_status(){
4791
		if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
4792
			echo json_encode( $this->sync->reindex_status() );
4793
		} else {
4794
			echo '{"status":"ERROR"}';
4795
		}
4796
		exit;
4797
	}
4798
4799
/* Client API */
4800
4801
	/**
4802
	 * Returns the requested Jetpack API URL
4803
	 *
4804
	 * @return string
4805
	 */
4806
	public static function api_url( $relative_url ) {
4807
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4808
	}
4809
4810
	/**
4811
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4812
	 */
4813
	public static function fix_url_for_bad_hosts( $url ) {
4814
		if ( 0 !== strpos( $url, 'https://' ) ) {
4815
			return $url;
4816
		}
4817
4818
		switch ( JETPACK_CLIENT__HTTPS ) {
4819
			case 'ALWAYS' :
4820
				return $url;
4821
			case 'NEVER' :
4822
				return set_url_scheme( $url, 'http' );
4823
			// default : case 'AUTO' :
4824
		}
4825
4826
		// we now return the unmodified SSL URL by default, as a security precaution
4827
		return $url;
4828
	}
4829
4830
	/**
4831
	 * Checks to see if the URL is using SSL to connect with Jetpack
4832
	 *
4833
	 * @since 2.3.3
4834
	 * @return boolean
4835
	 */
4836
	public static function permit_ssl( $force_recheck = false ) {
4837
		// Do some fancy tests to see if ssl is being supported
4838
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4839
			$message = '';
4840
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4841
				$ssl = 0;
4842
			} else {
4843
				switch ( JETPACK_CLIENT__HTTPS ) {
4844
					case 'NEVER':
4845
						$ssl = 0;
4846
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4847
						break;
4848
					case 'ALWAYS':
4849
					case 'AUTO':
4850
					default:
4851
						$ssl = 1;
4852
						break;
4853
				}
4854
4855
				// If it's not 'NEVER', test to see
4856
				if ( $ssl ) {
4857
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4858
						$ssl = 0;
4859
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4860
					} else {
4861
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4862
						if ( is_wp_error( $response ) ) {
4863
							$ssl = 0;
4864
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4865
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4866
							$ssl = 0;
4867
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4868
						}
4869
					}
4870
				}
4871
			}
4872
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4873
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4874
		}
4875
4876
		return (bool) $ssl;
4877
	}
4878
4879
	/*
4880
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4881
	 */
4882
	public function alert_auto_ssl_fail() {
4883
		if ( ! current_user_can( 'manage_options' ) )
4884
			return;
4885
		?>
4886
4887
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4888
			<div class="jp-banner__content">
4889
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4890
				<p><?php _e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
4891
				<p>
4892
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4893
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4894
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4895
				</p>
4896
				<p>
4897
					<?php printf( __( 'For more help, try our <a href="$1%s">connection debugger</a> or <a href="$2%s" target="_blank">troubleshooting tips</a>', 'jetpack' ), 
4898
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4899
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4900
				</p>
4901
			</div>
4902
		</div>
4903
		<style>
4904
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4905
		</style>
4906
		<script type="text/javascript">
4907
			jQuery( document ).ready( function( $ ) {
4908
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4909
					var $this = $( this );
4910
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4911
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4912
					e.preventDefault();
4913
					$.post( '/wp-json/jetpack/v4/recheck-ssl' )
4914
					  .done( function( response ) {
4915
					  	if ( response.enabled ) {
4916
					  		$( '#jetpack-ssl-warning' ).hide();
4917
					  	} else {
4918
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4919
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4920
					  	}
4921
					  }.bind( $this ) );
4922
				} );
4923
			} );
4924
		</script>
4925
4926
		<?php
4927
	}
4928
4929
	/**
4930
	 * Returns the Jetpack XML-RPC API
4931
	 *
4932
	 * @return string
4933
	 */
4934
	public static function xmlrpc_api_url() {
4935
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4936
		return untrailingslashit( $base ) . '/xmlrpc.php';
4937
	}
4938
4939
	/**
4940
	 * Creates two secret tokens and the end of life timestamp for them.
4941
	 *
4942
	 * Note these tokens are unique per call, NOT static per site for connecting.
4943
	 *
4944
	 * @since 2.6
4945
	 * @return array
4946
	 */
4947
	public function generate_secrets( $action ) {
4948
	    $secret = wp_generate_password( 32, false ) // secret_1
4949
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4950
	    		. ':' . ( time() + 600 ) // eol ( End of Life )
4951
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4952
		Jetpack_Options::update_option( $action, $secret );
4953
4954
	    return Jetpack_Options::get_option( $action );
4955
	}
4956
4957
	/**
4958
	 * Builds the timeout limit for queries talking with the wpcom servers.
4959
	 *
4960
	 * Based on local php max_execution_time in php.ini
4961
	 *
4962
	 * @since 2.6
4963
	 * @return int
4964
	 **/
4965
	public function get_remote_query_timeout_limit() {
4966
	    $timeout = (int) ini_get( 'max_execution_time' );
4967
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4968
		$timeout = 30;
4969
	    return intval( $timeout / 2 );
4970
	}
4971
4972
4973
	/**
4974
	 * Takes the response from the Jetpack register new site endpoint and
4975
	 * verifies it worked properly.
4976
	 *
4977
	 * @since 2.6
4978
	 * @return true or Jetpack_Error
4979
	 **/
4980
	public function validate_remote_register_response( $response ) {
4981
	    	if ( is_wp_error( $response ) ) {
4982
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4983
		}
4984
4985
		$code   = wp_remote_retrieve_response_code( $response );
4986
		$entity = wp_remote_retrieve_body( $response );
4987
		if ( $entity )
4988
			$json = json_decode( $entity );
4989
		else
4990
			$json = false;
4991
4992
		$code_type = intval( $code / 100 );
4993
		if ( 5 == $code_type ) {
4994
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4995
		} elseif ( 408 == $code ) {
4996
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4997
		} elseif ( ! empty( $json->error ) ) {
4998
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4999
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
5000
		} elseif ( 200 != $code ) {
5001
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5002
		}
5003
5004
		// Jetpack ID error block
5005
		if ( empty( $json->jetpack_id ) ) {
5006
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5007
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
5008
			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 );
5009
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
5010
			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 );
5011
		}
5012
5013
	    return true;
5014
	}
5015
	/**
5016
	 * @return bool|WP_Error
5017
	 */
5018
	public static function register() {
5019
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5020
		$secrets = Jetpack::init()->generate_secrets( 'register' );
5021
5022
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
5023 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
5024
			return new Jetpack_Error( 'missing_secrets' );
5025
		}
5026
5027
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
5028
5029
		$gmt_offset = get_option( 'gmt_offset' );
5030
		if ( ! $gmt_offset ) {
5031
			$gmt_offset = 0;
5032
		}
5033
5034
		$stats_options = get_option( 'stats_options' );
5035
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5036
5037
		$args = array(
5038
			'method'  => 'POST',
5039
			'body'    => array(
5040
				'siteurl'         => site_url(),
5041
				'home'            => home_url(),
5042
				'gmt_offset'      => $gmt_offset,
5043
				'timezone_string' => (string) get_option( 'timezone_string' ),
5044
				'site_name'       => (string) get_option( 'blogname' ),
5045
				'secret_1'        => $secret_1,
5046
				'secret_2'        => $secret_2,
5047
				'site_lang'       => get_locale(),
5048
				'timeout'         => $timeout,
5049
				'stats_id'        => $stats_id,
5050
				'state'           => get_current_user_id(),
5051
			),
5052
			'headers' => array(
5053
				'Accept' => 'application/json',
5054
			),
5055
			'timeout' => $timeout,
5056
		);
5057
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5058
5059
5060
		// Make sure the response is valid and does not contain any Jetpack errors
5061
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
5062
		if( is_wp_error( $valid_response ) || !$valid_response ) {
5063
		    return $valid_response;
5064
		}
5065
5066
		// Grab the response values to work with
5067
		$code   = wp_remote_retrieve_response_code( $response );
5068
		$entity = wp_remote_retrieve_body( $response );
5069
5070
		if ( $entity )
5071
			$json = json_decode( $entity );
5072
		else
5073
			$json = false;
5074
5075 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
5076
			return new Jetpack_Error( 'jetpack_secret', '', $code );
5077
5078
		if ( isset( $json->jetpack_public ) ) {
5079
			$jetpack_public = (int) $json->jetpack_public;
5080
		} else {
5081
			$jetpack_public = false;
5082
		}
5083
5084
		Jetpack_Options::update_options(
5085
			array(
5086
				'id'         => (int)    $json->jetpack_id,
5087
				'blog_token' => (string) $json->jetpack_secret,
5088
				'public'     => $jetpack_public,
5089
			)
5090
		);
5091
5092
		/**
5093
		 * Fires when a site is registered on WordPress.com.
5094
		 *
5095
		 * @since 3.7.0
5096
		 *
5097
		 * @param int $json->jetpack_id Jetpack Blog ID.
5098
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5099
		 * @param int|bool $jetpack_public Is the site public.
5100
		 */
5101
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
5102
5103
		// Initialize Jump Start for the first and only time.
5104
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5105
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5106
5107
			$jetpack = Jetpack::init();
5108
5109
			$jetpack->stat( 'jumpstart', 'unique-views' );
5110
			$jetpack->do_stats( 'server_side' );
5111
		};
5112
5113
		return true;
5114
	}
5115
5116
	/**
5117
	 * If the db version is showing something other that what we've got now, bump it to current.
5118
	 *
5119
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5120
	 */
5121
	public static function maybe_set_version_option() {
5122
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5123
		if ( JETPACK__VERSION != $version ) {
5124
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5125
			return true;
5126
		}
5127
		return false;
5128
	}
5129
5130
/* Client Server API */
5131
5132
	/**
5133
	 * Loads the Jetpack XML-RPC client
5134
	 */
5135
	public static function load_xml_rpc_client() {
5136
		require_once ABSPATH . WPINC . '/class-IXR.php';
5137
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5138
	}
5139
5140
	function verify_xml_rpc_signature() {
5141
		if ( $this->xmlrpc_verification ) {
5142
			return $this->xmlrpc_verification;
5143
		}
5144
5145
		// It's not for us
5146
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5147
			return false;
5148
		}
5149
5150
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
5151
		if (
5152
			empty( $token_key )
5153
		||
5154
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5155
		) {
5156
			return false;
5157
		}
5158
5159
		if ( '0' === $user_id ) {
5160
			$token_type = 'blog';
5161
			$user_id = 0;
5162
		} else {
5163
			$token_type = 'user';
5164
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5165
				return false;
5166
			}
5167
			$user_id = (int) $user_id;
5168
5169
			$user = new WP_User( $user_id );
5170
			if ( ! $user || ! $user->exists() ) {
5171
				return false;
5172
			}
5173
		}
5174
5175
		$token = Jetpack_Data::get_access_token( $user_id );
5176
		if ( ! $token ) {
5177
			return false;
5178
		}
5179
5180
		$token_check = "$token_key.";
5181
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5182
			return false;
5183
		}
5184
5185
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5186
5187
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5188
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5189
			$post_data   = $_POST;
5190
			$file_hashes = array();
5191
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5192
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5193
					continue;
5194
				}
5195
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5196
				$file_hashes[$post_data_key] = $post_data_value;
5197
			}
5198
5199
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5200
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5201
				$post_data[$post_data_key] = $post_data_value;
5202
			}
5203
5204
			ksort( $post_data );
5205
5206
			$body = http_build_query( stripslashes_deep( $post_data ) );
5207
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5208
			$body = file_get_contents( 'php://input' );
5209
		} else {
5210
			$body = null;
5211
		}
5212
		$signature = $jetpack_signature->sign_current_request(
5213
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5214
		);
5215
5216
		if ( ! $signature ) {
5217
			return false;
5218
		} else if ( is_wp_error( $signature ) ) {
5219
			return $signature;
5220
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5221
			return false;
5222
		}
5223
5224
		$timestamp = (int) $_GET['timestamp'];
5225
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5226
5227
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5228
			return false;
5229
		}
5230
5231
		$this->xmlrpc_verification = array(
5232
			'type'    => $token_type,
5233
			'user_id' => $token->external_user_id,
5234
		);
5235
5236
		return $this->xmlrpc_verification;
5237
	}
5238
5239
	/**
5240
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5241
	 */
5242
	function authenticate_jetpack( $user, $username, $password ) {
5243
		if ( is_a( $user, 'WP_User' ) ) {
5244
			return $user;
5245
		}
5246
5247
		$token_details = $this->verify_xml_rpc_signature();
5248
5249
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5250
			return $user;
5251
		}
5252
5253
		if ( 'user' !== $token_details['type'] ) {
5254
			return $user;
5255
		}
5256
5257
		if ( ! $token_details['user_id'] ) {
5258
			return $user;
5259
		}
5260
5261
		nocache_headers();
5262
5263
		return new WP_User( $token_details['user_id'] );
5264
	}
5265
5266
	function add_nonce( $timestamp, $nonce ) {
5267
		global $wpdb;
5268
		static $nonces_used_this_request = array();
5269
5270
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5271
			return $nonces_used_this_request["$timestamp:$nonce"];
5272
		}
5273
5274
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5275
		$timestamp = (int) $timestamp;
5276
		$nonce     = esc_sql( $nonce );
5277
5278
		// Raw query so we can avoid races: add_option will also update
5279
		$show_errors = $wpdb->show_errors( false );
5280
5281
		$old_nonce = $wpdb->get_row(
5282
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5283
		);
5284
5285
		if ( is_null( $old_nonce ) ) {
5286
			$return = $wpdb->query(
5287
				$wpdb->prepare(
5288
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5289
					"jetpack_nonce_{$timestamp}_{$nonce}",
5290
					time(),
5291
					'no'
5292
				)
5293
			);
5294
		} else {
5295
			$return = false;
5296
		}
5297
5298
		$wpdb->show_errors( $show_errors );
5299
5300
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5301
5302
		return $return;
5303
	}
5304
5305
	/**
5306
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5307
	 * Capture it here so we can verify the signature later.
5308
	 */
5309
	function xmlrpc_methods( $methods ) {
5310
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5311
		return $methods;
5312
	}
5313
5314
	function public_xmlrpc_methods( $methods ) {
5315
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5316
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5317
		}
5318
		return $methods;
5319
	}
5320
5321
	function jetpack_getOptions( $args ) {
5322
		global $wp_xmlrpc_server;
5323
5324
		$wp_xmlrpc_server->escape( $args );
5325
5326
		$username	= $args[1];
5327
		$password	= $args[2];
5328
5329
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5330
			return $wp_xmlrpc_server->error;
5331
		}
5332
5333
		$options = array();
5334
		$user_data = $this->get_connected_user_data();
5335
		if ( is_array( $user_data ) ) {
5336
			$options['jetpack_user_id'] = array(
5337
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5338
				'readonly'      => true,
5339
				'value'         => $user_data['ID'],
5340
			);
5341
			$options['jetpack_user_login'] = array(
5342
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5343
				'readonly'      => true,
5344
				'value'         => $user_data['login'],
5345
			);
5346
			$options['jetpack_user_email'] = array(
5347
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5348
				'readonly'      => true,
5349
				'value'         => $user_data['email'],
5350
			);
5351
			$options['jetpack_user_site_count'] = array(
5352
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5353
				'readonly'      => true,
5354
				'value'         => $user_data['site_count'],
5355
			);
5356
		}
5357
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5358
		$args = stripslashes_deep( $args );
5359
		return $wp_xmlrpc_server->wp_getOptions( $args );
5360
	}
5361
5362
	function xmlrpc_options( $options ) {
5363
		$jetpack_client_id = false;
5364
		if ( self::is_active() ) {
5365
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5366
		}
5367
		$options['jetpack_version'] = array(
5368
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5369
				'readonly'      => true,
5370
				'value'         => JETPACK__VERSION,
5371
		);
5372
5373
		$options['jetpack_client_id'] = array(
5374
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5375
				'readonly'      => true,
5376
				'value'         => $jetpack_client_id,
5377
		);
5378
		return $options;
5379
	}
5380
5381
	public static function clean_nonces( $all = false ) {
5382
		global $wpdb;
5383
5384
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5385
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
5386
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5387
		} else {
5388
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
5389
		}
5390
5391
		if ( true !== $all ) {
5392
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5393
			$sql_args[] = time() - 3600;
5394
		}
5395
5396
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5397
5398
		$sql = $wpdb->prepare( $sql, $sql_args );
5399
5400
		for ( $i = 0; $i < 1000; $i++ ) {
5401
			if ( ! $wpdb->query( $sql ) ) {
5402
				break;
5403
			}
5404
		}
5405
	}
5406
5407
	/**
5408
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5409
	 * SET: state( $key, $value );
5410
	 * GET: $value = state( $key );
5411
	 *
5412
	 * @param string $key
5413
	 * @param string $value
5414
	 * @param bool $restate private
5415
	 */
5416
	public static function state( $key = null, $value = null, $restate = false ) {
5417
		static $state = array();
5418
		static $path, $domain;
5419
		if ( ! isset( $path ) ) {
5420
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5421
			$admin_url = Jetpack::admin_url();
5422
			$bits      = parse_url( $admin_url );
5423
5424
			if ( is_array( $bits ) ) {
5425
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5426
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5427
			} else {
5428
				$path = $domain = null;
5429
			}
5430
		}
5431
5432
		// Extract state from cookies and delete cookies
5433
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5434
			$yum = $_COOKIE[ 'jetpackState' ];
5435
			unset( $_COOKIE[ 'jetpackState' ] );
5436
			foreach ( $yum as $k => $v ) {
5437
				if ( strlen( $v ) )
5438
					$state[ $k ] = $v;
5439
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5440
			}
5441
		}
5442
5443
		if ( $restate ) {
5444
			foreach ( $state as $k => $v ) {
5445
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5446
			}
5447
			return;
5448
		}
5449
5450
		// Get a state variable
5451
		if ( isset( $key ) && ! isset( $value ) ) {
5452
			if ( array_key_exists( $key, $state ) )
5453
				return $state[ $key ];
5454
			return null;
5455
		}
5456
5457
		// Set a state variable
5458
		if ( isset ( $key ) && isset( $value ) ) {
5459
			if( is_array( $value ) && isset( $value[0] ) ) {
5460
				$value = $value[0];
5461
			}
5462
			$state[ $key ] = $value;
5463
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5464
		}
5465
	}
5466
5467
	public static function restate() {
5468
		Jetpack::state( null, null, true );
5469
	}
5470
5471
	public static function check_privacy( $file ) {
5472
		static $is_site_publicly_accessible = null;
5473
5474
		if ( is_null( $is_site_publicly_accessible ) ) {
5475
			$is_site_publicly_accessible = false;
5476
5477
			Jetpack::load_xml_rpc_client();
5478
			$rpc = new Jetpack_IXR_Client();
5479
5480
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5481
			if ( $success ) {
5482
				$response = $rpc->getResponse();
5483
				if ( $response ) {
5484
					$is_site_publicly_accessible = true;
5485
				}
5486
			}
5487
5488
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5489
		}
5490
5491
		if ( $is_site_publicly_accessible ) {
5492
			return;
5493
		}
5494
5495
		$module_slug = self::get_module_slug( $file );
5496
5497
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5498
		if ( ! $privacy_checks ) {
5499
			$privacy_checks = $module_slug;
5500
		} else {
5501
			$privacy_checks .= ",$module_slug";
5502
		}
5503
5504
		Jetpack::state( 'privacy_checks', $privacy_checks );
5505
	}
5506
5507
	/**
5508
	 * Helper method for multicall XMLRPC.
5509
	 */
5510
	public static function xmlrpc_async_call() {
5511
		global $blog_id;
5512
		static $clients = array();
5513
5514
		$client_blog_id = is_multisite() ? $blog_id : 0;
5515
5516
		if ( ! isset( $clients[$client_blog_id] ) ) {
5517
			Jetpack::load_xml_rpc_client();
5518
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5519
			if ( function_exists( 'ignore_user_abort' ) ) {
5520
				ignore_user_abort( true );
5521
			}
5522
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5523
		}
5524
5525
		$args = func_get_args();
5526
5527
		if ( ! empty( $args[0] ) ) {
5528
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5529
		} elseif ( is_multisite() ) {
5530
			foreach ( $clients as $client_blog_id => $client ) {
5531
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5532
					continue;
5533
				}
5534
5535
				$switch_success = switch_to_blog( $client_blog_id, true );
5536
				if ( ! $switch_success ) {
5537
					continue;
5538
				}
5539
5540
				flush();
5541
				$client->query();
5542
5543
				restore_current_blog();
5544
			}
5545
		} else {
5546
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5547
				flush();
5548
				$clients[0]->query();
5549
			}
5550
		}
5551
	}
5552
5553
	public static function staticize_subdomain( $url ) {
5554
5555
		// Extract hostname from URL
5556
		$host = parse_url( $url, PHP_URL_HOST );
5557
5558
		// Explode hostname on '.'
5559
		$exploded_host = explode( '.', $host );
5560
5561
		// Retrieve the name and TLD
5562
		if ( count( $exploded_host ) > 1 ) {
5563
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5564
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5565
			// Rebuild domain excluding subdomains
5566
			$domain = $name . '.' . $tld;
5567
		} else {
5568
			$domain = $host;
5569
		}
5570
		// Array of Automattic domains
5571
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5572
5573
		// Return $url if not an Automattic domain
5574
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5575
			return $url;
5576
		}
5577
5578
		if ( is_ssl() ) {
5579
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5580
		}
5581
5582
		srand( crc32( basename( $url ) ) );
5583
		$static_counter = rand( 0, 2 );
5584
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5585
5586
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5587
	}
5588
5589
/* JSON API Authorization */
5590
5591
	/**
5592
	 * Handles the login action for Authorizing the JSON API
5593
	 */
5594
	function login_form_json_api_authorization() {
5595
		$this->verify_json_api_authorization_request();
5596
5597
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5598
5599
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5600
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5601
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5602
	}
5603
5604
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5605
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5606
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5607
			return $url;
5608
		}
5609
5610
		$parsed_url = parse_url( $url );
5611
		$url = strtok( $url, '?' );
5612
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5613
		if ( ! empty( $parsed_url['query'] ) )
5614
			$url .= "&{$parsed_url['query']}";
5615
5616
		return $url;
5617
	}
5618
5619
	// Make sure the POSTed request is handled by the same action
5620
	function preserve_action_in_login_form_for_json_api_authorization() {
5621
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5622
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5623
	}
5624
5625
	// If someone logs in to approve API access, store the Access Code in usermeta
5626
	function store_json_api_authorization_token( $user_login, $user ) {
5627
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5628
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5629
		$token = wp_generate_password( 32, false );
5630
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5631
	}
5632
5633
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5634
	function allow_wpcom_public_api_domain( $domains ) {
5635
		$domains[] = 'public-api.wordpress.com';
5636
		return $domains;
5637
	}
5638
5639
	// Add the Access Code details to the public-api.wordpress.com redirect
5640
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5641
		return add_query_arg(
5642
			urlencode_deep(
5643
				array(
5644
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5645
					'jetpack-user-id' => (int) $user->ID,
5646
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5647
				)
5648
			),
5649
			$redirect_to
5650
		);
5651
	}
5652
5653
	// Verifies the request by checking the signature
5654
	function verify_json_api_authorization_request() {
5655
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5656
5657
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5658
		if ( ! $token || empty( $token->secret ) ) {
5659
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5660
		}
5661
5662
		$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' );
5663
5664
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5665
5666
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5667
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5668
		} else {
5669
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5670
		}
5671
5672
		if ( ! $signature ) {
5673
			wp_die( $die_error );
5674
		} else if ( is_wp_error( $signature ) ) {
5675
			wp_die( $die_error );
5676
		} else if ( $signature !== $_GET['signature'] ) {
5677
			if ( is_ssl() ) {
5678
				// 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
5679
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5680
				if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
5681
					wp_die( $die_error );
5682
				}
5683
			} else {
5684
				wp_die( $die_error );
5685
			}
5686
		}
5687
5688
		$timestamp = (int) $_GET['timestamp'];
5689
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5690
5691
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5692
			// De-nonce the nonce, at least for 5 minutes.
5693
			// 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)
5694
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5695
			if ( $old_nonce_time < time() - 300 ) {
5696
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5697
			}
5698
		}
5699
5700
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5701
		$data_filters = array(
5702
			'state'        => 'opaque',
5703
			'client_id'    => 'int',
5704
			'client_title' => 'string',
5705
			'client_image' => 'url',
5706
		);
5707
5708
		foreach ( $data_filters as $key => $sanitation ) {
5709
			if ( ! isset( $data->$key ) ) {
5710
				wp_die( $die_error );
5711
			}
5712
5713
			switch ( $sanitation ) {
5714
			case 'int' :
5715
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5716
				break;
5717
			case 'opaque' :
5718
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5719
				break;
5720
			case 'string' :
5721
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5722
				break;
5723
			case 'url' :
5724
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5725
				break;
5726
			}
5727
		}
5728
5729
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5730
			wp_die( $die_error );
5731
		}
5732
	}
5733
5734
	function login_message_json_api_authorization( $message ) {
5735
		return '<p class="message">' . sprintf(
5736
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5737
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5738
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5739
	}
5740
5741
	/**
5742
	 * Get $content_width, but with a <s>twist</s> filter.
5743
	 */
5744
	public static function get_content_width() {
5745
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5746
		/**
5747
		 * Filter the Content Width value.
5748
		 *
5749
		 * @since 2.2.3
5750
		 *
5751
		 * @param string $content_width Content Width value.
5752
		 */
5753
		return apply_filters( 'jetpack_content_width', $content_width );
5754
	}
5755
5756
	/**
5757
	 * Centralize the function here until it gets added to core.
5758
	 *
5759
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5760
	 * @param int $size Size of the avatar image
5761
	 * @param string $default URL to a default image to use if no avatar is available
5762
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5763
	 *
5764
	 * @return array First element is the URL, second is the class.
5765
	 */
5766
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5767
		// Don't bother adding the __return_true filter if it's already there.
5768
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5769
5770
		if ( $force_display && ! $has_filter )
5771
			add_filter( 'pre_option_show_avatars', '__return_true' );
5772
5773
		$avatar = get_avatar( $id_or_email, $size, $default );
5774
5775
		if ( $force_display && ! $has_filter )
5776
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5777
5778
		// If no data, fail out.
5779
		if ( is_wp_error( $avatar ) || ! $avatar )
5780
			return array( null, null );
5781
5782
		// Pull out the URL.  If it's not there, fail out.
5783
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5784
			return array( null, null );
5785
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5786
5787
		// Pull out the class, but it's not a big deal if it's missing.
5788
		$class = '';
5789
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5790
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5791
5792
		return array( $url, $class );
5793
	}
5794
5795
	/**
5796
	 * Pings the WordPress.com Mirror Site for the specified options.
5797
	 *
5798
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5799
	 *
5800
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5801
	 */
5802
	public function get_cloud_site_options( $option_names ) {
5803
		$option_names = array_filter( (array) $option_names, 'is_string' );
5804
5805
		Jetpack::load_xml_rpc_client();
5806
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5807
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5808
		if ( $xml->isError() ) {
5809
			return array(
5810
				'error_code' => $xml->getErrorCode(),
5811
				'error_msg'  => $xml->getErrorMessage(),
5812
			);
5813
		}
5814
		$cloud_site_options = $xml->getResponse();
5815
5816
		return $cloud_site_options;
5817
	}
5818
5819
	/**
5820
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5821
	 *
5822
	 * @return array An array of options to check.
5823
	 */
5824
	public static function identity_crisis_options_to_check() {
5825
		return array(
5826
			'siteurl',
5827
			'home',
5828
		);
5829
	}
5830
5831
	/**
5832
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5833
	 *
5834
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5835
	 *
5836
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5837
	 */
5838
	public static function check_identity_crisis( $force_recheck = false ) {
5839
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5840
			return false;
5841
5842
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5843
			$options_to_check = self::identity_crisis_options_to_check();
5844
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5845
			$errors        = array();
5846
5847
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5848
5849
				// If it's not the same as the local value...
5850
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5851
5852
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5853
					if ( 'error_code' == $cloud_key ) {
5854
						$errors[ $cloud_key ] = $cloud_value;
5855
						break;
5856
					}
5857
5858
					$parsed_cloud_value = parse_url( $cloud_value );
5859
					// If the current options is an IP address
5860
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5861
						// Give the new value a Jetpack to fly in to the clouds
5862
						Jetpack::resolve_identity_crisis( $cloud_key );
5863
						continue;
5864
					}
5865
5866
					// And it's not been added to the whitelist...
5867
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5868
						/*
5869
						 * This should be a temporary hack until a cleaner solution is found.
5870
						 *
5871
						 * The siteurl and home can be set to use http in General > Settings
5872
						 * however some constants can be defined that can force https in wp-admin
5873
						 * when this happens wpcom can confuse wporg with a fake identity
5874
						 * crisis with a mismatch of http vs https when it should be allowed.
5875
						 * we need to check that here.
5876
						 *
5877
						 * @see https://github.com/Automattic/jetpack/issues/1006
5878
						 */
5879
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5880
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5881
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5882
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5883
							continue;
5884
						}
5885
5886
5887
						// Then kick an error!
5888
						$errors[ $cloud_key ] = $cloud_value;
5889
					}
5890
				}
5891
			}
5892
		}
5893
5894
		/**
5895
		 * Filters the errors returned when checking for an Identity Crisis.
5896
		 *
5897
		 * @since 2.3.2
5898
		 *
5899
		 * @param array $errors Array of Identity Crisis errors.
5900
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5901
		 */
5902
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5903
	}
5904
5905
	/*
5906
	 * Resolve ID crisis
5907
	 *
5908
	 * If the URL has changed, but the rest of the options are the same (i.e. blog/user tokens)
5909
	 * The user has the option to update the shadow site with the new URL before a new
5910
	 * token is created.
5911
	 *
5912
	 * @param $key : Which option to sync.  null defautlts to home and siteurl
5913
	 */
5914
	public static function resolve_identity_crisis( $key = null ) {
5915
		if ( $key ) {
5916
			$identity_options = array( $key );
5917
		} else {
5918
			$identity_options = self::identity_crisis_options_to_check();
5919
		}
5920
5921
		if ( is_array( $identity_options ) ) {
5922
			foreach( $identity_options as $identity_option ) {
5923
				Jetpack_Sync::sync_options( __FILE__, $identity_option );
5924
5925
				/**
5926
				 * Fires when a shadow site option is updated.
5927
				 * These options are updated via the Identity Crisis UI.
5928
				 * $identity_option is the option that gets updated.
5929
				 *
5930
				 * @since 3.7.0
5931
				 */
5932
				do_action( "update_option_{$identity_option}" );
5933
			}
5934
		}
5935
	}
5936
5937
	/*
5938
	 * Whitelist URL
5939
	 *
5940
	 * Ignore the URL differences between the blog and the shadow site.
5941
	 */
5942
	public static function whitelist_current_url() {
5943
		$options_to_check = Jetpack::identity_crisis_options_to_check();
5944
		$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5945
5946
		foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5947
			Jetpack::whitelist_identity_crisis_value( $cloud_key, $cloud_value );
5948
		}
5949
	}
5950
5951
	/*
5952
	 * Ajax callbacks for ID crisis resolutions
5953
	 *
5954
	 * Things that could happen here:
5955
	 *  - site_migrated : Update the URL on the shadow blog to match new domain
5956
	 *  - whitelist     : Ignore the URL difference
5957
	 *  - default       : Error message
5958
	 */
5959
	public static function resolve_identity_crisis_ajax_callback() {
5960
		check_ajax_referer( 'resolve-identity-crisis', 'ajax-nonce' );
5961
5962
		switch ( $_POST[ 'crisis_resolution_action' ] ) {
5963
			case 'site_migrated':
5964
				Jetpack::resolve_identity_crisis();
5965
				echo 'resolved';
5966
				break;
5967
5968
			case 'whitelist':
5969
				Jetpack::whitelist_current_url();
5970
				echo 'whitelisted';
5971
				break;
5972
5973
			case 'reset_connection':
5974
				// Delete the options first so it doesn't get confused which site to disconnect dotcom-side
5975
				Jetpack_Options::delete_option(
5976
					array(
5977
						'register',
5978
						'blog_token',
5979
						'user_token',
5980
						'user_tokens',
5981
						'master_user',
5982
						'time_diff',
5983
						'fallback_no_verify_ssl_certs',
5984
						'id',
5985
					)
5986
				);
5987
				delete_transient( 'jetpack_has_identity_crisis' );
5988
5989
				echo 'reset-connection-success';
5990
				break;
5991
5992
			default:
5993
				echo 'missing action';
5994
				break;
5995
		}
5996
5997
		wp_die();
5998
	}
5999
6000
	/**
6001
	 * Adds a value to the whitelist for the specified key.
6002
	 *
6003
	 * @param string $key The option name that we're whitelisting the value for.
6004
	 * @param string $value The value that we're intending to add to the whitelist.
6005
	 *
6006
	 * @return bool Whether the value was added to the whitelist, or false if it was already there.
6007
	 */
6008
	public static function whitelist_identity_crisis_value( $key, $value ) {
6009
		if ( Jetpack::is_identity_crisis_value_whitelisted( $key, $value ) ) {
6010
			return false;
6011
		}
6012
6013
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6014
		if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
6015
			$whitelist[ $key ] = array();
6016
		}
6017
		array_push( $whitelist[ $key ], $value );
6018
6019
		Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
6020
		return true;
6021
	}
6022
6023
	/**
6024
	 * Checks whether a value is already whitelisted.
6025
	 *
6026
	 * @param string $key The option name that we're checking the value for.
6027
	 * @param string $value The value that we're curious to see if it's on the whitelist.
6028
	 *
6029
	 * @return bool Whether the value is whitelisted.
6030
	 */
6031
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
6032
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
6033
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
6034
			return true;
6035
		}
6036
		return false;
6037
	}
6038
6039
	/**
6040
	 * Checks whether the home and siteurl specifically are whitelisted
6041
	 * Written so that we don't have re-check $key and $value params every time
6042
	 * we want to check if this site is whitelisted, for example in footer.php
6043
	 *
6044
	 * @return bool True = already whitelsisted False = not whitelisted
6045
	 */
6046
	public static function is_staging_site() {
6047
		$is_staging = false;
6048
6049
		$current_whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist' );
6050
		if ( $current_whitelist ) {
6051
			$options_to_check  = Jetpack::identity_crisis_options_to_check();
6052
			$cloud_options     = Jetpack::init()->get_cloud_site_options( $options_to_check );
6053
6054
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
6055
				if ( self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
6056
					$is_staging = true;
6057
					break;
6058
				}
6059
			}
6060
		}
6061
		$known_staging = array(
6062
			'urls' => array(
6063
				'#\.staging\.wpengine\.com$#i',
6064
				),
6065
			'constants' => array(
6066
				'IS_WPE_SNAPSHOT',
6067
				'KINSTA_DEV_ENV',
6068
				'JETPACK_STAGING_MODE',
6069
				)
6070
			);
6071
		/**
6072
		 * Filters the flags of known staging sites.
6073
		 *
6074
		 * @since 3.9.0
6075
		 *
6076
		 * @param array $known_staging {
6077
		 *     An array of arrays that each are used to check if the current site is staging.
6078
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6079
		 *     @type array $cosntants PHP constants of known staging/developement environments.
6080
		 *  }
6081
		 */
6082
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6083
6084
		if ( isset( $known_staging['urls'] ) ) {
6085
			foreach ( $known_staging['urls'] as $url ){
6086
				if ( preg_match( $url, site_url() ) ) {
6087
					$is_staging = true;
6088
					break;
6089
				}
6090
			}
6091
		}
6092
6093
		if ( isset( $known_staging['constants'] ) ) {
6094
			foreach ( $known_staging['constants'] as $constant ) {
6095
				if ( defined( $constant ) && constant( $constant ) ) {
6096
					$is_staging = true;
6097
				}
6098
			}
6099
		}
6100
6101
		/**
6102
		 * Filters is_staging_site check.
6103
		 *
6104
		 * @since 3.9.0
6105
		 *
6106
		 * @param bool $is_staging If the current site is a staging site.
6107
		 */
6108
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6109
	}
6110
6111
	public function identity_crisis_js( $nonce ) {
6112
?>
6113
<script>
6114
(function( $ ) {
6115
	var SECOND_IN_MS = 1000;
6116
6117
	function contactSupport( e ) {
6118
		e.preventDefault();
6119
		$( '.jp-id-crisis-question' ).hide();
6120
		$( '#jp-id-crisis-contact-support' ).show();
6121
	}
6122
6123
	function autodismissSuccessBanner() {
6124
		$( '.jp-identity-crisis' ).fadeOut(600); //.addClass( 'dismiss' );
6125
	}
6126
6127
	var data = { action: 'jetpack_resolve_identity_crisis', 'ajax-nonce': '<?php echo $nonce; ?>' };
6128
6129
	$( document ).ready(function() {
6130
6131
		// Site moved: Update the URL on the shadow blog
6132
		$( '.site-moved' ).click(function( e ) {
6133
			e.preventDefault();
6134
			data.crisis_resolution_action = 'site_migrated';
6135
			$( '#jp-id-crisis-question-1 .spinner' ).show();
6136
			$.post( ajaxurl, data, function() {
6137
				$( '.jp-id-crisis-question' ).hide();
6138
				$( '.banner-title' ).hide();
6139
				$( '#jp-id-crisis-success' ).show();
6140
				setTimeout( autodismissSuccessBanner, 6 * SECOND_IN_MS );
6141
			});
6142
6143
		});
6144
6145
		// URL hasn't changed, next question please.
6146
		$( '.site-not-moved' ).click(function( e ) {
6147
			e.preventDefault();
6148
			$( '.jp-id-crisis-question' ).hide();
6149
			$( '#jp-id-crisis-question-2' ).show();
6150
		});
6151
6152
		// Reset connection: two separate sites.
6153
		$( '.reset-connection' ).click(function( e ) {
6154
			data.crisis_resolution_action = 'reset_connection';
6155
			$.post( ajaxurl, data, function( response ) {
6156
				if ( 'reset-connection-success' === response ) {
6157
					window.location.replace( '<?php echo Jetpack::admin_url(); ?>' );
6158
				}
6159
			});
6160
		});
6161
6162
		// It's a dev environment.  Ignore.
6163
		$( '.is-dev-env' ).click(function( e ) {
6164
			data.crisis_resolution_action = 'whitelist';
6165
			$( '#jp-id-crisis-question-2 .spinner' ).show();
6166
			$.post( ajaxurl, data, function() {
6167
				$( '.jp-id-crisis-question' ).hide();
6168
				$( '.banner-title' ).hide();
6169
				$( '#jp-id-crisis-success' ).show();
6170
				setTimeout( autodismissSuccessBanner, 4 * SECOND_IN_MS );
6171
			});
6172
		});
6173
6174
		$( '.not-reconnecting' ).click(contactSupport);
6175
		$( '.not-staging-or-dev' ).click(contactSupport);
6176
	});
6177
})( jQuery );
6178
</script>
6179
<?php
6180
	}
6181
6182
	/**
6183
	 * Displays an admin_notice, alerting the user to an identity crisis.
6184
	 */
6185
	public function alert_identity_crisis() {
6186
		// @todo temporary killing of feature in 3.8.1 as it revealed a number of scenarios not foreseen.
6187
		if ( ! Jetpack::is_development_version() ) {
6188
			return;
6189
		}
6190
6191
		// @todo temporary copout for dealing with domain mapping
6192
		// @see https://github.com/Automattic/jetpack/issues/2702
6193
		if ( is_multisite() && defined( 'SUNRISE' ) && ! Jetpack::is_development_version() ) {
6194
			return;
6195
		}
6196
6197
		if ( ! current_user_can( 'jetpack_disconnect' ) ) {
6198
			return;
6199
		}
6200
6201
		if ( ! $errors = self::check_identity_crisis() ) {
6202
			return;
6203
		}
6204
6205
		// Only show on dashboard and jetpack pages
6206
		$screen = get_current_screen();
6207
		if ( 'dashboard' !== $screen->base && ! did_action( 'jetpack_notices' ) ) {
6208
			return;
6209
		}
6210
6211
		// Include the js!
6212
		$ajax_nonce = wp_create_nonce( 'resolve-identity-crisis' );
6213
		$this->identity_crisis_js( $ajax_nonce );
6214
6215
		// Include the CSS!
6216
		if ( ! wp_script_is( 'jetpack', 'done' ) ) {
6217
			$this->admin_banner_styles();
6218
		}
6219
6220
		if ( ! array_key_exists( 'error_code', $errors ) ) {
6221
			$key = 'siteurl';
6222
			if ( ! $errors[ $key ] ) {
6223
				$key = 'home';
6224
			}
6225
		} else {
6226
			$key = 'error_code';
6227
			// 401 is the only error we care about.  Any other errors should not trigger the alert.
6228
			if ( 401 !== $errors[ $key ] ) {
6229
				return;
6230
			}
6231
		}
6232
6233
		?>
6234
6235
		<style>
6236
			.jp-identity-crisis .jp-btn-group {
6237
					margin: 15px 0;
6238
				}
6239
			.jp-identity-crisis strong {
6240
					color: #518d2a;
6241
				}
6242
			.jp-identity-crisis.dismiss {
6243
				display: none;
6244
			}
6245
			.jp-identity-crisis .button {
6246
				margin-right: 4px;
6247
			}
6248
		</style>
6249
6250
		<div id="message" class="error jetpack-message jp-identity-crisis stay-visible">
6251
			<div class="service-mark"></div>
6252
			<div class="jp-id-banner__content">
6253
				<!-- <h3 class="banner-title"><?php _e( 'Something\'s not quite right with your Jetpack connection! Let\'s fix that.', 'jetpack' ); ?></h3> -->
6254
6255
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-1">
6256
					<?php
6257
					// 401 means that this site has been disconnected from wpcom, but the remote site still thinks it's connected.
6258
					if ( 'error_code' == $key && '401' == $errors[ $key ] ) : ?>
6259
						<div class="banner-content">
6260
							<p><?php
6261
								/* translators: %s is a URL */
6262
								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/' );
6263
							?></p>
6264
						</div>
6265
						<div class="jp-btn-group">
6266
							<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a>
6267
							<span class="idc-separator">|</span>
6268
							<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=dismiss' ), 'jetpack-deactivate' ) ); ?>"><?php _e( 'Deactivate Jetpack', 'jetpack' ); ?></a>
6269
						</div>
6270
					<?php else : ?>
6271
							<div class="banner-content">
6272
							<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>
6273
							</div>
6274
						<div class="jp-btn-group">
6275
							<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>
6276
							<span class="spinner"></span>
6277
						</div>
6278
					<?php endif ; ?>
6279
				</div>
6280
6281
				<div class="jp-id-crisis-question" id="jp-id-crisis-question-2" style="display: none;">
6282
					<div class="banner-content">
6283
						<p><?php printf(
6284
							/* translators: %1$s, %2$s and %3$s are URLs */
6285
							__(
6286
								'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>',
6287
								'jetpack'
6288
							),
6289
							$errors[ $key ],
6290
							(string) get_option( $key ),
6291
							'https://jetpack.com/support/what-does-resetting-the-connection-mean/'
6292
						); ?></p>
6293
					</div>
6294
					<div class="jp-btn-group">
6295
						<a href="#" class="reset-connection"><?php _e( 'Reset the connection', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6296
						<a href="#" class="is-dev-env"><?php _e( 'This is a development environment', 'jetpack' ); ?></a> <span class="idc-separator">|</span>
6297
						<a href="https://jetpack.com/contact-support/" class="contact-support"><?php _e( 'Submit a support ticket', 'jetpack' ); ?></a>
6298
						<span class="spinner"></span>
6299
					</div>
6300
				</div>
6301
6302
				<div class="jp-id-crisis-success" id="jp-id-crisis-success" style="display: none;">
6303
					<h3 class="success-notice"><?php printf( __( 'Thanks for taking the time to sort things out. We&#039;ve updated our records accordingly!', 'jetpack' ) ); ?></h3>
6304
				</div>
6305
			</div>
6306
		</div>
6307
6308
		<?php
6309
	}
6310
6311
	/**
6312
	 * Maybe Use a .min.css stylesheet, maybe not.
6313
	 *
6314
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6315
	 */
6316
	public static function maybe_min_asset( $url, $path, $plugin ) {
6317
		// Short out on things trying to find actual paths.
6318
		if ( ! $path || empty( $plugin ) ) {
6319
			return $url;
6320
		}
6321
6322
		// Strip out the abspath.
6323
		$base = dirname( plugin_basename( $plugin ) );
6324
6325
		// Short out on non-Jetpack assets.
6326
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6327
			return $url;
6328
		}
6329
6330
		// File name parsing.
6331
		$file              = "{$base}/{$path}";
6332
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6333
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6334
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6335
		$extension         = array_shift( $file_name_parts_r );
6336
6337
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6338
			// Already pointing at the minified version.
6339
			if ( 'min' === $file_name_parts_r[0] ) {
6340
				return $url;
6341
			}
6342
6343
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6344
			if ( file_exists( $min_full_path ) ) {
6345
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6346
			}
6347
		}
6348
6349
		return $url;
6350
	}
6351
6352
	/**
6353
	 * Maybe inlines a stylesheet.
6354
	 *
6355
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6356
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6357
	 *
6358
	 * Attached to `style_loader_tag` filter.
6359
	 *
6360
	 * @param string $tag The tag that would link to the external asset.
6361
	 * @param string $handle The registered handle of the script in question.
6362
	 *
6363
	 * @return string
6364
	 */
6365
	public static function maybe_inline_style( $tag, $handle ) {
6366
		global $wp_styles;
6367
		$item = $wp_styles->registered[ $handle ];
6368
6369
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6370
			return $tag;
6371
		}
6372
6373
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6374
			$href = $matches[1];
6375
			// Strip off query string
6376
			if ( $pos = strpos( $href, '?' ) ) {
6377
				$href = substr( $href, 0, $pos );
6378
			}
6379
			// Strip off fragment
6380
			if ( $pos = strpos( $href, '#' ) ) {
6381
				$href = substr( $href, 0, $pos );
6382
			}
6383
		} else {
6384
			return $tag;
6385
		}
6386
6387
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6388
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6389
			return $tag;
6390
		}
6391
6392
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6393
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6394
			// And this isn't the pass that actually deals with the RTL version...
6395
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6396
				// Short out, as the RTL version will deal with it in a moment.
6397
				return $tag;
6398
			}
6399
		}
6400
6401
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6402
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6403
		if ( $css ) {
6404
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6405
			if ( empty( $item->extra['after'] ) ) {
6406
				wp_add_inline_style( $handle, $css );
6407
			} else {
6408
				array_unshift( $item->extra['after'], $css );
6409
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6410
			}
6411
		}
6412
6413
		return $tag;
6414
	}
6415
6416
	/**
6417
	 * Loads a view file from the views
6418
	 *
6419
	 * Data passed in with the $data parameter will be available in the
6420
	 * template file as $data['value']
6421
	 *
6422
	 * @param string $template - Template file to load
6423
	 * @param array $data - Any data to pass along to the template
6424
	 * @return boolean - If template file was found
6425
	 **/
6426
	public function load_view( $template, $data = array() ) {
6427
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6428
6429
		if( file_exists( $views_dir . $template ) ) {
6430
			require_once( $views_dir . $template );
6431
			return true;
6432
		}
6433
6434
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6435
		return false;
6436
	}
6437
6438
	/**
6439
	 * Sends a ping to the Jetpack servers to toggle on/off remote portions
6440
	 * required by some modules.
6441
	 *
6442
	 * @param string $module_slug
6443
	 */
6444
	public function toggle_module_on_wpcom( $module_slug ) {
6445
		Jetpack::init()->sync->register( 'noop' );
6446
6447
		if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
6448
			self::check_privacy( $module_slug );
6449
		}
6450
6451
	}
6452
6453
	/**
6454
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6455
	 */
6456
	public function deprecated_hooks() {
6457
		global $wp_filter;
6458
6459
		/*
6460
		 * Format:
6461
		 * deprecated_filter_name => replacement_name
6462
		 *
6463
		 * If there is no replacement us null for replacement_name
6464
		 */
6465
		$deprecated_list = array(
6466
			'jetpack_bail_on_shortcode'                => 'jetpack_shortcodes_to_include',
6467
			'wpl_sharing_2014_1'                       => null,
6468
			'jetpack-tools-to-include'                 => 'jetpack_tools_to_include',
6469
			'jetpack_identity_crisis_options_to_check' => null,
6470
		);
6471
6472
		// This is a silly loop depth. Better way?
6473
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6474
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
6475
				foreach( $wp_filter[$hook] AS $func => $values ) {
6476
					foreach( $values AS $hooked ) {
6477
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
6478
					}
6479
				}
6480
			}
6481
		}
6482
	}
6483
6484
	/**
6485
	 * Converts any url in a stylesheet, to the correct absolute url.
6486
	 *
6487
	 * Considerations:
6488
	 *  - Normal, relative URLs     `feh.png`
6489
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6490
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6491
	 *  - Absolute URLs             `http://domain.com/feh.png`
6492
	 *  - Domain root relative URLs `/feh.png`
6493
	 *
6494
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6495
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6496
	 *
6497
	 * @return mixed|string
6498
	 */
6499
	public static function absolutize_css_urls( $css, $css_file_url ) {
6500
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6501
		$css_dir = dirname( $css_file_url );
6502
		$p       = parse_url( $css_dir );
6503
		$domain  = sprintf(
6504
					'%1$s//%2$s%3$s%4$s',
6505
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6506
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6507
					$p['host'],
6508
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6509
				);
6510
6511
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6512
			$find = $replace = array();
6513
			foreach ( $matches as $match ) {
6514
				$url = trim( $match['path'], "'\" \t" );
6515
6516
				// If this is a data url, we don't want to mess with it.
6517
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6518
					continue;
6519
				}
6520
6521
				// If this is an absolute or protocol-agnostic url,
6522
				// we don't want to mess with it.
6523
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6524
					continue;
6525
				}
6526
6527
				switch ( substr( $url, 0, 1 ) ) {
6528
					case '/':
6529
						$absolute = $domain . $url;
6530
						break;
6531
					default:
6532
						$absolute = $css_dir . '/' . $url;
6533
				}
6534
6535
				$find[]    = $match[0];
6536
				$replace[] = sprintf( 'url("%s")', $absolute );
6537
			}
6538
			$css = str_replace( $find, $replace, $css );
6539
		}
6540
6541
		return $css;
6542
	}
6543
6544
	/**
6545
	 * This method checks to see if SSL is required by the site in
6546
	 * order to visit it in some way other than only setting the
6547
	 * https value in the home or siteurl values.
6548
	 *
6549
	 * @since 3.2
6550
	 * @return boolean
6551
	 **/
6552
	private function is_ssl_required_to_visit_site() {
6553
		global $wp_version;
6554
		$ssl = is_ssl();
6555
6556
		if ( force_ssl_admin() ) {
6557
			$ssl = true;
6558
		}
6559
		return $ssl;
6560
	}
6561
6562
	/**
6563
	 * This methods removes all of the registered css files on the frontend
6564
	 * from Jetpack in favor of using a single file. In effect "imploding"
6565
	 * all the files into one file.
6566
	 *
6567
	 * Pros:
6568
	 * - Uses only ONE css asset connection instead of 15
6569
	 * - Saves a minimum of 56k
6570
	 * - Reduces server load
6571
	 * - Reduces time to first painted byte
6572
	 *
6573
	 * Cons:
6574
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6575
	 *		should not cause any issues with themes.
6576
	 * - Plugins/themes dequeuing styles no longer do anything. See
6577
	 *		jetpack_implode_frontend_css filter for a workaround
6578
	 *
6579
	 * For some situations developers may wish to disable css imploding and
6580
	 * instead operate in legacy mode where each file loads seperately and
6581
	 * can be edited individually or dequeued. This can be accomplished with
6582
	 * the following line:
6583
	 *
6584
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6585
	 *
6586
	 * @since 3.2
6587
	 **/
6588
	public function implode_frontend_css( $travis_test = false ) {
6589
		$do_implode = true;
6590
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6591
			$do_implode = false;
6592
		}
6593
6594
		/**
6595
		 * Allow CSS to be concatenated into a single jetpack.css file.
6596
		 *
6597
		 * @since 3.2.0
6598
		 *
6599
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6600
		 */
6601
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6602
6603
		// Do not use the imploded file when default behaviour was altered through the filter
6604
		if ( ! $do_implode ) {
6605
			return;
6606
		}
6607
6608
		// We do not want to use the imploded file in dev mode, or if not connected
6609
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6610
			if ( ! $travis_test ) {
6611
				return;
6612
			}
6613
		}
6614
6615
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6616
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6617
			return;
6618
		}
6619
6620
		/*
6621
		 * Now we assume Jetpack is connected and able to serve the single
6622
		 * file.
6623
		 *
6624
		 * In the future there will be a check here to serve the file locally
6625
		 * or potentially from the Jetpack CDN
6626
		 *
6627
		 * For now:
6628
		 * - Enqueue a single imploded css file
6629
		 * - Zero out the style_loader_tag for the bundled ones
6630
		 * - Be happy, drink scotch
6631
		 */
6632
6633
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6634
6635
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6636
6637
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6638
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6639
	}
6640
6641
	function concat_remove_style_loader_tag( $tag, $handle ) {
6642
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6643
			$tag = '';
6644
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6645
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6646
			}
6647
		}
6648
6649
		return $tag;
6650
	}
6651
6652
	/*
6653
	 * Check the heartbeat data
6654
	 *
6655
	 * Organizes the heartbeat data by severity.  For example, if the site
6656
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6657
	 *
6658
	 * Data will be added to "caution" array, if it either:
6659
	 *  - Out of date Jetpack version
6660
	 *  - Out of date WP version
6661
	 *  - Out of date PHP version
6662
	 *
6663
	 * $return array $filtered_data
6664
	 */
6665
	public static function jetpack_check_heartbeat_data() {
6666
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6667
6668
		$good    = array();
6669
		$caution = array();
6670
		$bad     = array();
6671
6672
		foreach ( $raw_data as $stat => $value ) {
6673
6674
			// Check jetpack version
6675
			if ( 'version' == $stat ) {
6676
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6677
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6678
					continue;
6679
				}
6680
			}
6681
6682
			// Check WP version
6683
			if ( 'wp-version' == $stat ) {
6684
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6685
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6686
					continue;
6687
				}
6688
			}
6689
6690
			// Check PHP version
6691
			if ( 'php-version' == $stat ) {
6692
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6693
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6694
					continue;
6695
				}
6696
			}
6697
6698
			// Check ID crisis
6699
			if ( 'identitycrisis' == $stat ) {
6700
				if ( 'yes' == $value ) {
6701
					$bad[ $stat ] = $value;
6702
					continue;
6703
				}
6704
			}
6705
6706
			// The rest are good :)
6707
			$good[ $stat ] = $value;
6708
		}
6709
6710
		$filtered_data = array(
6711
			'good'    => $good,
6712
			'caution' => $caution,
6713
			'bad'     => $bad
6714
		);
6715
6716
		return $filtered_data;
6717
	}
6718
6719
6720
	/*
6721
	 * This method is used to organize all options that can be reset
6722
	 * without disconnecting Jetpack.
6723
	 *
6724
	 * It is used in class.jetpack-cli.php to reset options
6725
	 *
6726
	 * @return array of options to delete.
6727
	 */
6728
	public static function get_jetpack_options_for_reset() {
6729
		$jetpack_options            = Jetpack_Options::get_option_names();
6730
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6731
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6732
6733
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6734
6735
		// A manual build of the wp options
6736
		$wp_options = array(
6737
			'sharing-options',
6738
			'disabled_likes',
6739
			'disabled_reblogs',
6740
			'jetpack_comments_likes_enabled',
6741
			'wp_mobile_excerpt',
6742
			'wp_mobile_featured_images',
6743
			'wp_mobile_app_promos',
6744
			'stats_options',
6745
			'stats_dashboard_widget',
6746
			'safecss_preview_rev',
6747
			'safecss_rev',
6748
			'safecss_revision_migrated',
6749
			'nova_menu_order',
6750
			'jetpack_portfolio',
6751
			'jetpack_portfolio_posts_per_page',
6752
			'jetpack_testimonial',
6753
			'jetpack_testimonial_posts_per_page',
6754
			'wp_mobile_custom_css',
6755
			'sharedaddy_disable_resources',
6756
			'sharing-options',
6757
			'sharing-services',
6758
			'site_icon_temp_data',
6759
			'featured-content',
6760
			'site_logo',
6761
		);
6762
6763
		// Flag some Jetpack options as unsafe
6764
		$unsafe_options = array(
6765
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6766
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6767
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6768
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6769
6770
			// non_compact
6771
			'activated',
6772
6773
			// private
6774
			'register',
6775
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6776
			'user_token',                  // (string) The User Token of this site. (deprecated)
6777
			'user_tokens'
6778
		);
6779
6780
		// Remove the unsafe Jetpack options
6781
		foreach ( $unsafe_options as $unsafe_option ) {
6782
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6783
				unset( $all_jp_options[ $key ] );
6784
			}
6785
		}
6786
6787
		$options = array(
6788
			'jp_options' => $all_jp_options,
6789
			'wp_options' => $wp_options
6790
		);
6791
6792
		return $options;
6793
	}
6794
6795
	/**
6796
	 * Check if an option of a Jetpack module has been updated.
6797
	 *
6798
	 * If any module option has been updated before Jump Start has been dismissed,
6799
	 * update the 'jumpstart' option so we can hide Jump Start.
6800
	 *
6801
	 * @param string $option_name
6802
	 *
6803
	 * @return bool
6804
	 */
6805
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6806
		// Bail if Jump Start has already been dismissed
6807
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6808
			return false;
6809
		}
6810
6811
		$jetpack = Jetpack::init();
6812
6813
		// Manual build of module options
6814
		$option_names = self::get_jetpack_options_for_reset();
6815
6816
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6817
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6818
6819
			//Jump start is being dismissed send data to MC Stats
6820
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6821
6822
			$jetpack->do_stats( 'server_side' );
6823
		}
6824
6825
	}
6826
6827
	/*
6828
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6829
	 * so we can bring them directly to their site in calypso.
6830
	 *
6831
	 * @param string | url
6832
	 * @return string | url without the guff
6833
	 */
6834
	public static function build_raw_urls( $url ) {
6835
		$strip_http = '/.*?:\/\//i';
6836
		$url = preg_replace( $strip_http, '', $url  );
6837
		$url = str_replace( '/', '::', $url );
6838
		return $url;
6839
	}
6840
6841
	/**
6842
	 * Stores and prints out domains to prefetch for page speed optimization.
6843
	 *
6844
	 * @param mixed $new_urls
6845
	 */
6846
	public static function dns_prefetch( $new_urls = null ) {
6847
		static $prefetch_urls = array();
6848
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6849
			echo "\r\n";
6850
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6851
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6852
			}
6853
		} elseif ( ! empty( $new_urls ) ) {
6854
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6855
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6856
			}
6857
			foreach ( (array) $new_urls as $this_new_url ) {
6858
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6859
			}
6860
			$prefetch_urls = array_unique( $prefetch_urls );
6861
		}
6862
	}
6863
6864
	public function wp_dashboard_setup() {
6865
		if ( self::is_active() ) {
6866
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6867
			$widget_title = __( 'Site Stats', 'jetpack' );
6868
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6869
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6870
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6871
		}
6872
6873
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6874
			wp_add_dashboard_widget(
6875
				'jetpack_summary_widget',
6876
				$widget_title,
6877
				array( __CLASS__, 'dashboard_widget' )
6878
			);
6879
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6880
6881
			// If we're inactive and not in development mode, sort our box to the top.
6882
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6883
				global $wp_meta_boxes;
6884
6885
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6886
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6887
6888
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6889
			}
6890
		}
6891
	}
6892
6893
	/**
6894
	 * @param mixed $result Value for the user's option
6895
	 * @return mixed
6896
	 */
6897
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6898
		if ( ! is_array( $sorted ) ) {
6899
			return $sorted;
6900
		}
6901
6902
		foreach ( $sorted as $box_context => $ids ) {
6903
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6904
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6905
				continue;
6906
			}
6907
6908
			$ids_array = explode( ',', $ids );
6909
			$key = array_search( 'dashboard_stats', $ids_array );
6910
6911
			if ( false !== $key ) {
6912
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6913
				$ids_array[ $key ] = 'jetpack_summary_widget';
6914
				$sorted[ $box_context ] = implode( ',', $ids_array );
6915
				// We've found it, stop searching, and just return.
6916
				break;
6917
			}
6918
		}
6919
6920
		return $sorted;
6921
	}
6922
6923
	public static function dashboard_widget() {
6924
		/**
6925
		 * Fires when the dashboard is loaded.
6926
		 *
6927
		 * @since 3.4.0
6928
		 */
6929
		do_action( 'jetpack_dashboard_widget' );
6930
	}
6931
6932
	public static function dashboard_widget_footer() {
6933
		?>
6934
		<footer>
6935
6936
		<div class="protect">
6937
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6938
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6939
				<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>
6940
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6941
				<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' ); ?>">
6942
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6943
				</a>
6944
			<?php else : ?>
6945
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6946
			<?php endif; ?>
6947
		</div>
6948
6949
		<div class="akismet">
6950
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6951
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6952
				<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>
6953 View Code Duplication
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6954
				<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">
6955
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6956
				</a>
6957
			<?php else : ?>
6958
				<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>
6959
			<?php endif; ?>
6960
		</div>
6961
6962
6963 View Code Duplication
		<?php if ( ! current_user_can( 'edit_posts' ) && self::is_user_connected() ) : ?>
6964
			<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>
6965
		<?php endif; ?>
6966
6967
		</footer>
6968
		<?php
6969
	}
6970
6971
	public function dashboard_widget_connect_to_wpcom() {
6972
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6973
			return;
6974
		}
6975
		?>
6976
		<div class="wpcom-connect">
6977
			<div class="jp-emblem">
6978
			<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">
6979
				<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"/>
6980
			</svg>
6981
			</div>
6982
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6983
			<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>
6984
6985
			<div class="actions">
6986
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6987
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6988
				</a>
6989
			</div>
6990
		</div>
6991
		<?php
6992
	}
6993
6994
	/*
6995
	 * A graceful transition to using Core's site icon.
6996
	 *
6997
	 * All of the hard work has already been done with the image
6998
	 * in all_done_page(). All that needs to be done now is update
6999
	 * the option and display proper messaging.
7000
	 *
7001
	 * @todo remove when WP 4.3 is minimum
7002
	 *
7003
	 * @since 3.6.1
7004
	 *
7005
	 * @return bool false = Core's icon not available || true = Core's icon is available
7006
	 */
7007
	public static function jetpack_site_icon_available_in_core() {
7008
		global $wp_version;
7009
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
7010
7011
		if ( ! $core_icon_available ) {
7012
			return false;
7013
		}
7014
7015
		// No need for Jetpack's site icon anymore if core's is already set
7016
		if ( has_site_icon() ) {
7017
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
7018
				Jetpack::log( 'deactivate', 'site-icon' );
7019
				Jetpack::deactivate_module( 'site-icon' );
7020
			}
7021
			return true;
7022
		}
7023
7024
		// Transfer Jetpack's site icon to use core.
7025
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
7026
		if ( $site_icon_id ) {
7027
			// Update core's site icon
7028
			update_option( 'site_icon', $site_icon_id );
7029
7030
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
7031
			delete_option( 'site_icon_id' );
7032
		}
7033
7034
		// No need for Jetpack's site icon anymore
7035
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
7036
			Jetpack::log( 'deactivate', 'site-icon' );
7037
			Jetpack::deactivate_module( 'site-icon' );
7038
		}
7039
7040
		return true;
7041
	}
7042
7043
}
7044