Completed
Push — update/core-version-upgrade-ro... ( 3d6e97...e1c6f7 )
by
unknown
76:14 queued 66:29
created

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