Completed
Push — branch-4.2 ( 4e1bd6...94f02f )
by Jeremy
27:29 queued 18:39
created

class.jetpack.php (15 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'tiled-gallery',
46
		'widget-conditions',
47
		'jetpack_display_posts_widget',
48
		'gravatar-profile-widget',
49
		'widget-grid-and-list',
50
		'jetpack-widgets',
51
		'goodreads-widget',
52
		'jetpack_social_media_icons_widget',
53
	);
54
55
	public $plugins_to_deactivate = array(
56
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
57
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
63
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
64
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
65
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
66
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
67
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
68
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
69
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
70
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
71
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
72
	);
73
74
	public $capability_translations = array(
75
		'administrator' => 'manage_options',
76
		'editor'        => 'edit_others_posts',
77
		'author'        => 'publish_posts',
78
		'contributor'   => 'edit_posts',
79
		'subscriber'    => 'read',
80
	);
81
82
	/**
83
	 * Map of modules that have conflicts with plugins and should not be auto-activated
84
	 * if the plugins are active.  Used by filter_default_modules
85
	 *
86
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
87
	 * change `module-slug` and add this to your plugin:
88
	 *
89
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
90
	 * function my_jetpack_get_default_modules( $modules ) {
91
	 *     return array_diff( $modules, array( 'module-slug' ) );
92
	 * }
93
	 *
94
	 * @var array
95
	 */
96
	private $conflicting_plugins = array(
97
		'comments'          => array(
98
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
99
			'Disqus'                               => 'disqus-comment-system/disqus.php',
100
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
101
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
102
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
103
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
104
		),
105
		'contact-form'      => array(
106
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
107
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
108
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
109
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
110
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
111
		),
112
		'minileven'         => array(
113
			'WPtouch'                              => 'wptouch/wptouch.php',
114
		),
115
		'latex'             => array(
116
			'LaTeX for WordPress'                  => 'latex/latex.php',
117
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
118
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
119
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
120
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
121
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
122
		),
123
		'protect'           => array(
124
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
125
			'Captcha'                              => 'captcha/captcha.php',
126
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
127
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
128
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
129
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
130
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
131
			'Security-protection'                  => 'security-protection/security-protection.php',
132
			'Login Security'                       => 'login-security/login-security.php',
133
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
134
			'Wordfence Security'                   => 'wordfence/wordfence.php',
135
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
136
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
137
		),
138
		'random-redirect'   => array(
139
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
140
		),
141
		'related-posts'     => array(
142
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
143
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
144
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
145
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
146
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
147
			'outbrain'                             => 'outbrain/outbrain.php',
148
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
149
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
150
		),
151
		'sharedaddy'        => array(
152
			'AddThis'                              => 'addthis/addthis_social_widget.php',
153
			'Add To Any'                           => 'add-to-any/add-to-any.php',
154
			'ShareThis'                            => 'share-this/sharethis.php',
155
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
156
		),
157
		'verification-tools' => array(
158
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
159
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
160
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
161
		),
162
		'widget-visibility' => array(
163
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
164
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
165
		),
166
		'sitemaps' => array(
167
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
168
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
169
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
170
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
171
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
172
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
173
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
174
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
175
			'Sitemap'                              => 'sitemap/sitemap.php',
176
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
177
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
178
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
179
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
180
		),
181
	);
182
183
	/**
184
	 * Plugins for which we turn off our Facebook OG Tags implementation.
185
	 *
186
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
187
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
188
	 *
189
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
190
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
191
	 */
192
	private $open_graph_conflicting_plugins = array(
193
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
194
		                                                         // 2 Click Social Media Buttons
195
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
196
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
197
		'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
	 * Allows us to build a temporary security report
283
	 *
284
	 * @var array
285
	 */
286
	static $security_report = array();
287
288
	/**
289
	 * Jetpack_Sync object
290
	 */
291
	public $sync;
292
293
	/**
294
	 * Verified data for JSON authorization request
295
	 */
296
	public $json_api_authorization_request = array();
297
298
	/**
299
	 * Holds the singleton instance of this class
300
	 * @since 2.3.3
301
	 * @var Jetpack
302
	 */
303
	static $instance = false;
304
305
	/**
306
	 * Singleton
307
	 * @static
308
	 */
309
	public static function init() {
310
		if ( ! self::$instance ) {
311
			if ( did_action( 'plugins_loaded' ) )
312
				self::plugin_textdomain();
313
			else
314
				add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
315
316
			self::$instance = new Jetpack;
317
318
			self::$instance->plugin_upgrade();
319
320
		}
321
322
		return self::$instance;
323
	}
324
325
	/**
326
	 * Must never be called statically
327
	 */
328
	function plugin_upgrade() {
329
		if ( Jetpack::is_active() ) {
330
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
331
			if ( JETPACK__VERSION != $version ) {
332
333
				// Check which active modules actually exist and remove others from active_modules list
334
				$unfiltered_modules = Jetpack::get_active_modules();
335
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
336
				if ( array_diff( $unfiltered_modules, $modules ) ) {
337
					Jetpack_Options::update_option( 'active_modules', $modules );
338
				}
339
340
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
341
				/**
342
				 * Fires when synchronizing all registered options and constants.
343
				 *
344
				 * @since 3.3.0
345
				 */
346
				do_action( 'jetpack_sync_all_registered_options' );
347
348
				Jetpack::maybe_set_version_option();
349
			}
350
		}
351
	}
352
353
	static function activate_manage( ) {
354
355
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
356
			self::activate_module( 'manage', false, false );
357
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
358
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
359
		}
360
361
	}
362
363
	/**
364
	 * Constructor.  Initializes WordPress hooks
365
	 */
366
	private function __construct() {
367
		/*
368
		 * Check for and alert any deprecated hooks
369
		 */
370
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
371
372
373
		/*
374
		 * Load things that should only be in Network Admin.
375
		 *
376
		 * For now blow away everything else until a more full
377
		 * understanding of what is needed at the network level is
378
		 * available
379
		 */
380
		if( is_multisite() ) {
381
			Jetpack_Network::init();
382
		}
383
384
		// Unlink user before deleting the user from .com
385
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
386
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
387
388
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
389
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
390
391
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
392
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
393
394
			$this->require_jetpack_authentication();
395
396
			if ( Jetpack::is_active() ) {
397
				// Hack to preserve $HTTP_RAW_POST_DATA
398
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
399
400
				$signed = $this->verify_xml_rpc_signature();
401
				if ( $signed && ! is_wp_error( $signed ) ) {
402
					// The actual API methods.
403
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
404
				} else {
405
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
406
					// active Jetpack connection, so that additional users can link their account.
407
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
408
				}
409
			} else {
410
				// The bootstrap API methods.
411
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
412
			}
413
414
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
415
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
416
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
417
			$this->require_jetpack_authentication();
418
			$this->add_remote_request_handlers();
419
		} else {
420
			if ( Jetpack::is_active() ) {
421
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
422
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
423
			}
424
		}
425
426
		if ( Jetpack::is_active() ) {
427
			Jetpack_Heartbeat::init();
428
		}
429
430
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
431
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
432
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
433
		}
434
435
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
436
437
		add_action( 'admin_init', array( $this, 'admin_init' ) );
438
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
439
440
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
441
442
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
443
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
444
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
445
446
		// returns HTTPS support status
447
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
448
449
		// Jump Start AJAX callback function
450
		add_action( 'wp_ajax_jetpack_jumpstart_ajax',  array( $this, 'jetpack_jumpstart_ajax_callback' ) );
451
452
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
453
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
454
455
		// Identity Crisis AJAX callback function
456
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
457
458
		// JITM AJAX callback function
459
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
460
461
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
462
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
463
464
		// Universal ajax callback for all tracking events triggered via js
465
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
466
467
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
468
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
469
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
470
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
471
472
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
473
474
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
475
476
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
477
478
		/**
479
		 * These actions run checks to load additional files.
480
		 * They check for external files or plugins, so they need to run as late as possible.
481
		 */
482
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
483
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
484
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
485
486
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
487
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
488
489
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
490
491
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
492
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
493
494
		// A filter to control all just in time messages
495
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
496
497
		/**
498
		 * This is the hack to concatinate all css files into one.
499
		 * For description and reasoning see the implode_frontend_css method
500
		 *
501
		 * Super late priority so we catch all the registered styles
502
		 */
503
		if( !is_admin() ) {
504
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
505
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
506
		}
507
508
	}
509
	
510
	function jetpack_admin_ajax_tracks_callback() {
511
		// Check for nonce
512
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
513
			wp_die( 'Permissions check failed.' );
514
		}
515
516
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
517
			wp_die( 'No valid event name or type.' );
518
		}
519
520
		$tracks_data = array();
521
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
522
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
523
		}
524
525
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
526
		wp_send_json_success();
527
		wp_die();
528
	}
529
530
	function jetpack_admin_ajax_callback() {
531
		// Check for nonce
532 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
533
			wp_die( 'permissions check failed' );
534
		}
535
536
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
537
			$slug = $_REQUEST['thisModuleSlug'];
538
539
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
540
				wp_die( 'That is not a Jetpack module slug' );
541
			}
542
543
			if ( Jetpack::is_module_active( $slug ) ) {
544
				Jetpack::deactivate_module( $slug );
545
			} else {
546
				Jetpack::activate_module( $slug, false, false );
547
			}
548
549
			$modules = Jetpack_Admin::init()->get_modules();
550
			echo json_encode( $modules[ $slug ] );
551
552
			exit;
553
		}
554
555
		wp_die();
556
	}
557
558
	/*
559
	 * Sometimes we need to refresh the data,
560
	 * especially if the page is visited via a 'history'
561
	 * event like back/forward
562
	 */
563
	function jetpack_admin_ajax_refresh_data() {
564
		// Check for nonce
565 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
566
			wp_die( 'permissions check failed' );
567
		}
568
569
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
570
			$modules = Jetpack_Admin::init()->get_modules();
571
			echo json_encode( $modules );
572
			exit;
573
		}
574
575
		wp_die();
576
	}
577
578
	/**
579
	 * The callback for the Jump Start ajax requests.
580
	 */
581
	function jetpack_jumpstart_ajax_callback() {
582
		// Check for nonce
583
		if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
584
			wp_die( 'permissions check failed' );
585
586
		if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
587
			// Update the jumpstart option
588
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
589
				Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
590
			}
591
592
			// Loops through the requested "Jump Start" modules, and activates them.
593
			// Custom 'no_message' state, so that no message will be shown on reload.
594
			$modules = $_REQUEST['jumpstartModSlug'];
595
			$module_slugs = array();
596
			foreach( $modules as $module => $value ) {
597
				$module_slugs[] = $value['module_slug'];
598
			}
599
600
			// Check for possible conflicting plugins
601
			$module_slugs_filtered = $this->filter_default_modules( $module_slugs );
602
603
			foreach ( $module_slugs_filtered as $module_slug ) {
604
				Jetpack::log( 'activate', $module_slug );
605
				Jetpack::activate_module( $module_slug, false, false );
606
				Jetpack::state( 'message', 'no_message' );
607
			}
608
609
			// Set the default sharing buttons and set to display on posts if none have been set.
610
			$sharing_services = get_option( 'sharing-services' );
611
			$sharing_options  = get_option( 'sharing-options' );
612
			if ( empty( $sharing_services['visible'] ) ) {
613
				// Default buttons to set
614
				$visible = array(
615
					'twitter',
616
					'facebook',
617
					'google-plus-1',
618
				);
619
				$hidden = array();
620
621
				// Set some sharing settings
622
				$sharing = new Sharing_Service();
623
				$sharing_options['global'] = array(
624
					'button_style'  => 'icon',
625
					'sharing_label' => $sharing->default_sharing_label,
626
					'open_links'    => 'same',
627
					'show'          => array( 'post' ),
628
					'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
629
				);
630
631
				update_option( 'sharing-options', $sharing_options );
632
633
				// Send a success response so that we can display an error message.
634
				$success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
635
				echo json_encode( $success );
636
				exit;
637
			}
638
639
		} elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
640
			// If dismissed, flag the jumpstart option as such.
641
			// Send a success response so that we can display an error message.
642
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
643
				$success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
644
				echo json_encode( $success );
645
				exit;
646
			}
647
648
		} elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
649
650
			// FOR TESTING ONLY
651
			// @todo remove
652
			$modules = (array) $_REQUEST['jumpstartModSlug'];
653
			foreach( $modules as $module => $value ) {
654
				if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
655
					Jetpack::log( 'deactivate', $value['module_slug'] );
656
					Jetpack::deactivate_module( $value['module_slug'] );
657
					Jetpack::state( 'message', 'no_message' );
658
				} else {
659
					Jetpack::log( 'activate', $value['module_slug'] );
660
					Jetpack::activate_module( $value['module_slug'], false, false );
661
					Jetpack::state( 'message', 'no_message' );
662
				}
663
			}
664
665
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
666
			echo "reload the page";
667
		}
668
669
		wp_die();
670
	}
671
672
	/**
673
	 * The callback for the JITM ajax requests.
674
	 */
675
	function jetpack_jitm_ajax_callback() {
676
		// Check for nonce
677
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
678
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
679
		}
680
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
681
			$module_slug = $_REQUEST['jitmModule'];
682
			Jetpack::log( 'activate', $module_slug );
683
			Jetpack::activate_module( $module_slug, false, false );
684
			Jetpack::state( 'message', 'no_message' );
685
686
			//A Jetpack module is being activated through a JITM, track it
687
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
688
			$this->do_stats( 'server_side' );
689
690
			wp_send_json_success();
691
		}
692
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
693
			// get the hide_jitm options array
694
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
695
			$module_slug = $_REQUEST['jitmModule'];
696
697
			if( ! $jetpack_hide_jitm ) {
698
				$jetpack_hide_jitm = array(
699
					$module_slug => 'hide'
700
				);
701
			} else {
702
				$jetpack_hide_jitm[$module_slug] = 'hide';
703
			}
704
705
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
706
707
			//jitm is being dismissed forever, track it
708
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
709
			$this->do_stats( 'server_side' );
710
711
			wp_send_json_success();
712
		}
713 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
714
			$module_slug = $_REQUEST['jitmModule'];
715
716
			// User went to WordPress.com, track this
717
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
718
			$this->do_stats( 'server_side' );
719
720
			wp_send_json_success();
721
		}
722 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
723
			$track = $_REQUEST['jitmModule'];
724
725
			// User is viewing JITM, track it.
726
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
727
			$this->do_stats( 'server_side' );
728
729
			wp_send_json_success();
730
		}
731
	}
732
733
	/**
734
	 * If there are any stats that need to be pushed, but haven't been, push them now.
735
	 */
736
	function __destruct() {
737
		if ( ! empty( $this->stats ) ) {
738
			$this->do_stats( 'server_side' );
739
		}
740
	}
741
742
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
743
		switch( $cap ) {
744
			case 'jetpack_connect' :
745
			case 'jetpack_reconnect' :
746
				if ( Jetpack::is_development_mode() ) {
747
					$caps = array( 'do_not_allow' );
748
					break;
749
				}
750
				/**
751
				 * Pass through. If it's not development mode, these should match disconnect.
752
				 * Let users disconnect if it's development mode, just in case things glitch.
753
				 */
754
			case 'jetpack_disconnect' :
755
				/**
756
				 * In multisite, can individual site admins manage their own connection?
757
				 *
758
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
759
				 */
760
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
761
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
762
						/**
763
						 * We need to update the option name -- it's terribly unclear which
764
						 * direction the override goes.
765
						 *
766
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
767
						 */
768
						$caps = array( 'do_not_allow' );
769
						break;
770
					}
771
				}
772
773
				$caps = array( 'manage_options' );
774
				break;
775
			case 'jetpack_manage_modules' :
776
			case 'jetpack_activate_modules' :
777
			case 'jetpack_deactivate_modules' :
778
				$caps = array( 'manage_options' );
779
				break;
780
			case 'jetpack_configure_modules' :
781
				$caps = array( 'manage_options' );
782
				break;
783
			case 'jetpack_network_admin_page':
784
			case 'jetpack_network_settings_page':
785
				$caps = array( 'manage_network_plugins' );
786
				break;
787
			case 'jetpack_network_sites_page':
788
				$caps = array( 'manage_sites' );
789
				break;
790
			case 'jetpack_admin_page' :
791
				if ( Jetpack::is_development_mode() ) {
792
					$caps = array( 'manage_options' );
793
					break;
794
				} else {
795
					$caps = array( 'read' );
796
				}
797
				break;
798
			case 'jetpack_connect_user' :
799
				if ( Jetpack::is_development_mode() ) {
800
					$caps = array( 'do_not_allow' );
801
					break;
802
				}
803
				$caps = array( 'read' );
804
				break;
805
		}
806
		return $caps;
807
	}
808
809
	function require_jetpack_authentication() {
810
		// Don't let anyone authenticate
811
		$_COOKIE = array();
812
		remove_all_filters( 'authenticate' );
813
814
		/**
815
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
816
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
817
		 * generate false-positives.
818
		 */
819
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
820
821
		if ( Jetpack::is_active() ) {
822
			// Allow Jetpack authentication
823
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
824
		}
825
	}
826
827
	/**
828
	 * Load language files
829
	 */
830
	public static function plugin_textdomain() {
831
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
832
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
833
	}
834
835
	/**
836
	 * Register assets for use in various modules and the Jetpack admin page.
837
	 *
838
	 * @uses wp_script_is, wp_register_script, plugins_url
839
	 * @action wp_loaded
840
	 * @return null
841
	 */
842
	public function register_assets() {
843
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
844
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
845
		}
846
847 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
848
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
849
		}
850
851 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
852
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
853
		}
854
855 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
856
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
857
		}
858
859
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
860
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
861
862
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
863
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
864
			if ( ! is_numeric( $fb_app_id ) ) {
865
				$fb_app_id = '';
866
			}
867
			wp_localize_script(
868
				'jetpack-facebook-embed',
869
				'jpfbembed',
870
				array(
871
					'appid' => $fb_app_id,
872
					'locale' => $this->get_locale(),
873
				)
874
			);
875
		}
876
877
		/**
878
		 * As jetpack_register_genericons is by default fired off a hook,
879
		 * the hook may have already fired by this point.
880
		 * So, let's just trigger it manually.
881
		 */
882
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
883
		jetpack_register_genericons();
884
885
		/**
886
		 * Register the social logos 
887
		 */
888
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
889
		jetpack_register_social_logos();
890
891 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
892
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
893
	}
894
895
	/**
896
	 * Guess locale from language code.
897
	 *
898
	 * @param string $lang Language code.
899
	 * @return string|bool
900
	 */
901 View Code Duplication
	function guess_locale_from_lang( $lang ) {
902
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
903
			return 'en_US';
904
		}
905
906
		if ( ! class_exists( 'GP_Locales' ) ) {
907
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
908
				return false;
909
			}
910
911
			require JETPACK__GLOTPRESS_LOCALES_PATH;
912
		}
913
914
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
915
			// WP.com: get_locale() returns 'it'
916
			$locale = GP_Locales::by_slug( $lang );
917
		} else {
918
			// Jetpack: get_locale() returns 'it_IT';
919
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
920
		}
921
922
		if ( ! $locale ) {
923
			return false;
924
		}
925
926
		if ( empty( $locale->facebook_locale ) ) {
927
			if ( empty( $locale->wp_locale ) ) {
928
				return false;
929
			} else {
930
				// Facebook SDK is smart enough to fall back to en_US if a
931
				// locale isn't supported. Since supported Facebook locales
932
				// can fall out of sync, we'll attempt to use the known
933
				// wp_locale value and rely on said fallback.
934
				return $locale->wp_locale;
935
			}
936
		}
937
938
		return $locale->facebook_locale;
939
	}
940
941
	/**
942
	 * Get the locale.
943
	 *
944
	 * @return string|bool
945
	 */
946
	function get_locale() {
947
		$locale = $this->guess_locale_from_lang( get_locale() );
948
949
		if ( ! $locale ) {
950
			$locale = 'en_US';
951
		}
952
953
		return $locale;
954
	}
955
956
	/**
957
	 * Device Pixels support
958
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
959
	 */
960
	function devicepx() {
961
		if ( Jetpack::is_active() ) {
962
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
963
		}
964
	}
965
966
	/**
967
	 * Return the network_site_url so that .com knows what network this site is a part of.
968
	 * @param  bool $option
969
	 * @return string
970
	 */
971
	public function jetpack_main_network_site_option( $option ) {
972
		return network_site_url();
973
	}
974
	/**
975
	 * Network Name.
976
	 */
977
	static function network_name( $option = null ) {
978
		global $current_site;
979
		return $current_site->site_name;
980
	}
981
	/**
982
	 * Does the network allow new user and site registrations.
983
	 * @return string
984
	 */
985
	static function network_allow_new_registrations( $option = null ) {
986
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
987
	}
988
	/**
989
	 * Does the network allow admins to add new users.
990
	 * @return boolian
991
	 */
992
	static function network_add_new_users( $option = null ) {
993
		return (bool) get_site_option( 'add_new_users' );
994
	}
995
	/**
996
	 * File upload psace left per site in MB.
997
	 *  -1 means NO LIMIT.
998
	 * @return number
999
	 */
1000
	static function network_site_upload_space( $option = null ) {
1001
		// value in MB
1002
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1003
	}
1004
1005
	/**
1006
	 * Network allowed file types.
1007
	 * @return string
1008
	 */
1009
	static function network_upload_file_types( $option = null ) {
1010
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1011
	}
1012
1013
	/**
1014
	 * Maximum file upload size set by the network.
1015
	 * @return number
1016
	 */
1017
	static function network_max_upload_file_size( $option = null ) {
1018
		// value in KB
1019
		return get_site_option( 'fileupload_maxk', 300 );
1020
	}
1021
1022
	/**
1023
	 * Lets us know if a site allows admins to manage the network.
1024
	 * @return array
1025
	 */
1026
	static function network_enable_administration_menus( $option = null ) {
1027
		return get_site_option( 'menu_items' );
1028
	}
1029
1030
	/**
1031
	 * Return whether we are dealing with a multi network setup or not.
1032
	 * The reason we are type casting this is because we want to avoid the situation where
1033
	 * the result is false since when is_main_network_option return false it cases
1034
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1035
	 * database which could be set to anything as opposed to what this function returns.
1036
	 * @param  bool  $option
1037
	 *
1038
	 * @return boolean
1039
	 */
1040
	public function is_main_network_option( $option ) {
1041
		// return '1' or ''
1042
		return (string) (bool) Jetpack::is_multi_network();
1043
	}
1044
1045
	/**
1046
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1047
	 *
1048
	 * @param  string  $option
1049
	 * @return boolean
1050
	 */
1051
	public function is_multisite( $option ) {
1052
		return (string) (bool) is_multisite();
1053
	}
1054
1055
	/**
1056
	 * Implemented since there is no core is multi network function
1057
	 * Right now there is no way to tell if we which network is the dominant network on the system
1058
	 *
1059
	 * @since  3.3
1060
	 * @return boolean
1061
	 */
1062
	public static function is_multi_network() {
1063
		global  $wpdb;
1064
1065
		// if we don't have a multi site setup no need to do any more
1066
		if ( ! is_multisite() ) {
1067
			return false;
1068
		}
1069
1070
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1071
		if ( $num_sites > 1 ) {
1072
			return true;
1073
		} else {
1074
			return false;
1075
		}
1076
	}
1077
1078
	/**
1079
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1080
	 * @return null
1081
	 */
1082
	function update_jetpack_main_network_site_option() {
1083
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1084
		/**
1085
		 * Fires when the site URL is updated.
1086
		 * Determines if the site is the main site of a Mulitiste network.
1087
		 *
1088
		 * @since 3.3.0
1089
		 *
1090
		 * @param string jetpack_main_network_site.
1091
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1092
		 */
1093
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1094
		/**
1095
		 * Fires when the site URL is updated.
1096
		 * Determines if the is part of a multi network.
1097
		 *
1098
		 * @since 3.3.0
1099
		 *
1100
		 * @param string jetpack_is_main_network.
1101
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1102
		 */
1103
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1104
		/**
1105
		 * Fires when the site URL is updated.
1106
		 * Determines if the site is part of a multisite network.
1107
		 *
1108
		 * @since 3.4.0
1109
		 *
1110
		 * @param string jetpack_is_multi_site.
1111
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1112
		 */
1113
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1114
	}
1115
	/**
1116
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1117
	 *
1118
	 */
1119
	function update_jetpack_network_settings() {
1120
		// Only sync this info for the main network site.
1121
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1122
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1123
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1124
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1125
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1126
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1127
1128
	}
1129
1130
	/**
1131
	 * Get back if the current site is single user site.
1132
	 *
1133
	 * @return bool
1134
	 */
1135
	public static function is_single_user_site() {
1136
1137
		$user_query = new WP_User_Query( array(
1138
			'blog_id' => get_current_blog_id(),
1139
			'fields'  => 'ID',
1140
			'number' => 2
1141
		) );
1142
		return 1 === (int) $user_query->get_total();
1143
	}
1144
1145
	/**
1146
	 * Returns true if the site has file write access false otherwise.
1147
	 * @return string ( '1' | '0' )
1148
	 **/
1149
	public static function file_system_write_access() {
1150
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1151
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1152
		}
1153
1154
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1155
1156
		$filesystem_method = get_filesystem_method();
1157
		if ( $filesystem_method === 'direct' ) {
1158
			return 1;
1159
		}
1160
1161
		ob_start();
1162
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1163
		ob_end_clean();
1164
		if ( $filesystem_credentials_are_stored ) {
1165
			return 1;
1166
		}
1167
		return 0;
1168
	}
1169
1170
	/**
1171
	 * Finds out if a site is using a version control system.
1172
	 * @return string ( '1' | '0' )
1173
	 **/
1174
	public static function is_version_controlled() {
1175
		_deprecated_function( 'Jetpack::is_version_controlled', '4.1', 'Jetpack_Sync_Functions::is_version_controlled' );
1176
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1177
	}
1178
1179
	/**
1180
	 * Determines whether the current theme supports featured images or not.
1181
	 * @return string ( '1' | '0' )
1182
	 */
1183
	public static function featured_images_enabled() {
1184
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1185
	}
1186
	
1187
	/**
1188
	 * jetpack_updates is saved in the following schema:
1189
	 *
1190
	 * array (
1191
	 *      'plugins'                       => (int) Number of plugin updates available.
1192
	 *      'themes'                        => (int) Number of theme updates available.
1193
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1194
	 *      'translations'                  => (int) Number of translation updates available.
1195
	 *      'total'                         => (int) Total of all available updates.
1196
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1197
	 * )
1198
	 * @return array
1199
	 */
1200
	public static function get_updates() {
1201
		$update_data = wp_get_update_data();
1202
1203
		// Stores the individual update counts as well as the total count.
1204
		if ( isset( $update_data['counts'] ) ) {
1205
			$updates = $update_data['counts'];
1206
		}
1207
1208
		// If we need to update WordPress core, let's find the latest version number.
1209 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1210
			$cur = get_preferred_from_update_core();
1211
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1212
				$updates['wp_update_version'] = $cur->current;
1213
			}
1214
		}
1215
		return isset( $updates ) ? $updates : array();
1216
	}
1217
1218
	public static function get_update_details() {
1219
		$update_details = array(
1220
			'update_core' => get_site_transient( 'update_core' ),
1221
			'update_plugins' => get_site_transient( 'update_plugins' ),
1222
			'update_themes' => get_site_transient( 'update_themes' ),
1223
		);
1224
		return $update_details;
1225
	}
1226
1227
	public static function refresh_update_data() {
1228
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1229
			/**
1230
			 * Fires whenever the amount of updates needed for a site changes.
1231
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1232
			 *
1233
			 * @since 3.7.0
1234
			 *
1235
			 * @param string jetpack_updates
1236
			 * @param array Update counts calculated by Jetpack::get_updates
1237
			 */
1238
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1239
		}
1240
		/**
1241
		 * Fires whenever the amount of updates needed for a site changes.
1242
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1243
		 *
1244
		 * @since 3.7.0
1245
		 *
1246
		 * @param string jetpack_update_details
1247
		 * @param array Update details calculated by Jetpack::get_update_details
1248
		 */
1249
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1250
	}
1251
1252
	public static function refresh_theme_data() {
1253
		/**
1254
		 * Fires whenever a theme change is made.
1255
		 *
1256
		 * @since 3.8.1
1257
		 *
1258
		 * @param string featured_images_enabled
1259
		 * @param boolean Whether featured images are enabled or not
1260
		 */
1261
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1262
	}
1263
1264
	/**
1265
	 * Is Jetpack active?
1266
	 */
1267
	public static function is_active() {
1268
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1269
	}
1270
1271
	/**
1272
	 * Is Jetpack in development (offline) mode?
1273
	 */
1274
	public static function is_development_mode() {
1275
		$development_mode = false;
1276
1277
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1278
			$development_mode = JETPACK_DEV_DEBUG;
1279
		}
1280
1281
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1282
			$development_mode = true;
1283
		}
1284
		/**
1285
		 * Filters Jetpack's development mode.
1286
		 *
1287
		 * @see https://jetpack.com/support/development-mode/
1288
		 *
1289
		 * @since 2.2.1
1290
		 *
1291
		 * @param bool $development_mode Is Jetpack's development mode active.
1292
		 */
1293
		return apply_filters( 'jetpack_development_mode', $development_mode );
1294
	}
1295
1296
	/**
1297
	* Get Jetpack development mode notice text and notice class.
1298
	*
1299
	* Mirrors the checks made in Jetpack::is_development_mode
1300
	*
1301
	*/
1302
	public static function show_development_mode_notice() {
1303
		if ( Jetpack::is_development_mode() ) {
1304
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1305
				$notice = sprintf(
1306
					/* translators: %s is a URL */
1307
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1308
					'https://jetpack.com/support/development-mode/'
1309
				);
1310
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1311
				$notice = sprintf(
1312
					/* translators: %s is a URL */
1313
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1314
					'https://jetpack.com/support/development-mode/'
1315
				);
1316
			} else {
1317
				$notice = sprintf(
1318
					/* translators: %s is a URL */
1319
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1320
					'https://jetpack.com/support/development-mode/'
1321
				);
1322
			}
1323
1324
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1325
		}
1326
1327
		// Throw up a notice if using a development version and as for feedback.
1328
		if ( Jetpack::is_development_version() ) {
1329
			/* translators: %s is a URL */
1330
			$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/' );
1331
1332
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1333
		}
1334
		// Throw up a notice if using staging mode
1335
		if ( Jetpack::is_staging_site() ) {
1336
			/* translators: %s is a URL */
1337
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1338
1339
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1340
		}
1341
	}
1342
1343
	/**
1344
	 * Whether Jetpack's version maps to a public release, or a development version.
1345
	 */
1346
	public static function is_development_version() {
1347
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1348
	}
1349
1350
	/**
1351
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1352
	 */
1353
	public static function is_user_connected( $user_id = false ) {
1354
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1355
		if ( ! $user_id ) {
1356
			return false;
1357
		}
1358
		return (bool) Jetpack_Data::get_access_token( $user_id );
1359
	}
1360
1361
	/**
1362
	 * Get the wpcom user data of the current|specified connected user.
1363
	 */
1364 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1365
		if ( ! $user_id ) {
1366
			$user_id = get_current_user_id();
1367
		}
1368
		Jetpack::load_xml_rpc_client();
1369
		$xml = new Jetpack_IXR_Client( array(
1370
			'user_id' => $user_id,
1371
		) );
1372
		$xml->query( 'wpcom.getUser' );
1373
		if ( ! $xml->isError() ) {
1374
			return $xml->getResponse();
1375
		}
1376
		return false;
1377
	}
1378
1379
	/**
1380
	 * Get the wpcom email of the current|specified connected user.
1381
	 */
1382 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1383
		if ( ! $user_id ) {
1384
			$user_id = get_current_user_id();
1385
		}
1386
		Jetpack::load_xml_rpc_client();
1387
		$xml = new Jetpack_IXR_Client( array(
1388
			'user_id' => $user_id,
1389
		) );
1390
		$xml->query( 'wpcom.getUserEmail' );
1391
		if ( ! $xml->isError() ) {
1392
			return $xml->getResponse();
1393
		}
1394
		return false;
1395
	}
1396
1397
	/**
1398
	 * Get the wpcom email of the master user.
1399
	 */
1400
	public static function get_master_user_email() {
1401
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1402
		if ( $master_user_id ) {
1403
			return self::get_connected_user_email( $master_user_id );
1404
		}
1405
		return '';
1406
	}
1407
1408
	function current_user_is_connection_owner() {
1409
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1410
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1411
	}
1412
1413
	/**
1414
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1415
	 */
1416
	function extra_oembed_providers() {
1417
		// Cloudup: https://dev.cloudup.com/#oembed
1418
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1419
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1420
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1421
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1422
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1423
	}
1424
1425
	/**
1426
	 * Synchronize connected user role changes
1427
	 */
1428
	function user_role_change( $user_id ) {
1429
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1430
			$current_user_id = get_current_user_id();
1431
			wp_set_current_user( $user_id );
1432
			$role = $this->translate_current_user_to_role();
1433
			$signed_role = $this->sign_role( $role );
1434
			wp_set_current_user( $current_user_id );
1435
1436
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1437
			$master_user_id = absint( $master_token->external_user_id );
1438
1439
			if ( ! $master_user_id )
1440
				return; // this shouldn't happen
1441
1442
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1443
			//@todo retry on failure
1444
1445
			//try to choose a new master if we're demoting the current one
1446 View Code Duplication
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1447
				$query = new WP_User_Query(
1448
					array(
1449
						'fields'  => array( 'id' ),
1450
						'role'    => 'administrator',
1451
						'orderby' => 'id',
1452
						'exclude' => array( $master_user_id ),
1453
					)
1454
				);
1455
				$new_master = false;
1456
				foreach ( $query->results as $result ) {
1457
					$uid = absint( $result->id );
1458
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1459
						$new_master = $uid;
1460
						break;
1461
					}
1462
				}
1463
1464
				if ( $new_master ) {
1465
					Jetpack_Options::update_option( 'master_user', $new_master );
1466
				}
1467
				// else disconnect..?
1468
			}
1469
		}
1470
	}
1471
1472
	/**
1473
	 * Loads the currently active modules.
1474
	 */
1475
	public static function load_modules() {
1476
		if ( ! self::is_active() && !self::is_development_mode() ) {
1477
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1478
				return;
1479
			}
1480
		}
1481
1482
		$version = Jetpack_Options::get_option( 'version' );
1483 View Code Duplication
		if ( ! $version ) {
1484
			$version = $old_version = JETPACK__VERSION . ':' . time();
1485
			/** This action is documented in class.jetpack.php */
1486
			do_action( 'updating_jetpack_version', $version, false );
1487
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1488
		}
1489
		list( $version ) = explode( ':', $version );
1490
1491
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1492
1493
		$modules_data = array();
1494
1495
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1496
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1497
			$updated_modules = array();
1498
			foreach ( $modules as $module ) {
1499
				$modules_data[ $module ] = Jetpack::get_module( $module );
1500
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1501
					continue;
1502
				}
1503
1504
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1505
					continue;
1506
				}
1507
1508
				$updated_modules[] = $module;
1509
			}
1510
1511
			$modules = array_diff( $modules, $updated_modules );
1512
		}
1513
1514
		$is_development_mode = Jetpack::is_development_mode();
1515
1516
		foreach ( $modules as $index => $module ) {
1517
			// If we're in dev mode, disable modules requiring a connection
1518
			if ( $is_development_mode ) {
1519
				// Prime the pump if we need to
1520
				if ( empty( $modules_data[ $module ] ) ) {
1521
					$modules_data[ $module ] = Jetpack::get_module( $module );
1522
				}
1523
				// If the module requires a connection, but we're in local mode, don't include it.
1524
				if ( $modules_data[ $module ]['requires_connection'] ) {
1525
					continue;
1526
				}
1527
			}
1528
1529
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1530
				continue;
1531
			}
1532
1533
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1534
				unset( $modules[ $index ] );
1535
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1536
				continue;
1537
			}
1538
1539
			/**
1540
			 * Fires when a specific module is loaded.
1541
			 * The dynamic part of the hook, $module, is the module slug.
1542
			 *
1543
			 * @since 1.1.0
1544
			 */
1545
			do_action( 'jetpack_module_loaded_' . $module );
1546
		}
1547
1548
		/**
1549
		 * Fires when all the modules are loaded.
1550
		 *
1551
		 * @since 1.1.0
1552
		 */
1553
		do_action( 'jetpack_modules_loaded' );
1554
1555
		// 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.
1556
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1557
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1558
	}
1559
1560
	/**
1561
	 * Check if Jetpack's REST API compat file should be included
1562
	 * @action plugins_loaded
1563
	 * @return null
1564
	 */
1565
	public function check_rest_api_compat() {
1566
		/**
1567
		 * Filters the list of REST API compat files to be included.
1568
		 *
1569
		 * @since 2.2.5
1570
		 *
1571
		 * @param array $args Array of REST API compat files to include.
1572
		 */
1573
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1574
1575
		if ( function_exists( 'bbpress' ) )
1576
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1577
1578
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1579
			require_once $_jetpack_rest_api_compat_include;
1580
	}
1581
1582
	/**
1583
	 * Gets all plugins currently active in values, regardless of whether they're
1584
	 * traditionally activated or network activated.
1585
	 *
1586
	 * @todo Store the result in core's object cache maybe?
1587
	 */
1588
	public static function get_active_plugins() {
1589
		$active_plugins = (array) get_option( 'active_plugins', array() );
1590
1591
		if ( is_multisite() ) {
1592
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1593
			// whereas active_plugins stores them in the values.
1594
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1595
			if ( $network_plugins ) {
1596
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1597
			}
1598
		}
1599
1600
		sort( $active_plugins );
1601
1602
		return array_unique( $active_plugins );
1603
	}
1604
1605
	/**
1606
	 * Gets and parses additional plugin data to send with the heartbeat data
1607
	 *
1608
	 * @since 3.8.1
1609
	 *
1610
	 * @return array Array of plugin data
1611
	 */
1612
	public static function get_parsed_plugin_data() {
1613
		if ( ! function_exists( 'get_plugins' ) ) {
1614
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1615
		}
1616
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1617
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1618
		$active_plugins = Jetpack::get_active_plugins();
1619
1620
		$plugins = array();
1621
		foreach ( $all_plugins as $path => $plugin_data ) {
1622
			$plugins[ $path ] = array(
1623
					'is_active' => in_array( $path, $active_plugins ),
1624
					'file'      => $path,
1625
					'name'      => $plugin_data['Name'],
1626
					'version'   => $plugin_data['Version'],
1627
					'author'    => $plugin_data['Author'],
1628
			);
1629
		}
1630
1631
		return $plugins;
1632
	}
1633
1634
	/**
1635
	 * Gets and parses theme data to send with the heartbeat data
1636
	 *
1637
	 * @since 3.8.1
1638
	 *
1639
	 * @return array Array of theme data
1640
	 */
1641
	public static function get_parsed_theme_data() {
1642
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1643
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1644
1645
		$themes = array();
1646
		foreach ( $all_themes as $slug => $theme_data ) {
1647
			$theme_headers = array();
1648
			foreach ( $header_keys as $header_key ) {
1649
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1650
			}
1651
1652
			$themes[ $slug ] = array(
1653
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1654
					'slug' => $slug,
1655
					'theme_root' => $theme_data->get_theme_root_uri(),
1656
					'parent' => $theme_data->parent(),
1657
					'headers' => $theme_headers
1658
			);
1659
		}
1660
1661
		return $themes;
1662
	}
1663
1664
	/**
1665
	 * Checks whether a specific plugin is active.
1666
	 *
1667
	 * We don't want to store these in a static variable, in case
1668
	 * there are switch_to_blog() calls involved.
1669
	 */
1670
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1671
		return in_array( $plugin, self::get_active_plugins() );
1672
	}
1673
1674
	/**
1675
	 * Check if Jetpack's Open Graph tags should be used.
1676
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1677
	 *
1678
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1679
	 * @action plugins_loaded
1680
	 * @return null
1681
	 */
1682
	public function check_open_graph() {
1683
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1684
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1685
		}
1686
1687
		$active_plugins = self::get_active_plugins();
1688
1689
		if ( ! empty( $active_plugins ) ) {
1690
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1691
				if ( in_array( $plugin, $active_plugins ) ) {
1692
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1693
					break;
1694
				}
1695
			}
1696
		}
1697
1698
		/**
1699
		 * Allow the addition of Open Graph Meta Tags to all pages.
1700
		 *
1701
		 * @since 2.0.3
1702
		 *
1703
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1704
		 */
1705
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1706
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1707
		}
1708
	}
1709
1710
	/**
1711
	 * Check if Jetpack's Twitter tags should be used.
1712
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1713
	 *
1714
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1715
	 * @action plugins_loaded
1716
	 * @return null
1717
	 */
1718
	public function check_twitter_tags() {
1719
1720
		$active_plugins = self::get_active_plugins();
1721
1722
		if ( ! empty( $active_plugins ) ) {
1723
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1724
				if ( in_array( $plugin, $active_plugins ) ) {
1725
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1726
					break;
1727
				}
1728
			}
1729
		}
1730
1731
		/**
1732
		 * Allow Twitter Card Meta tags to be disabled.
1733
		 *
1734
		 * @since 2.6.0
1735
		 *
1736
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1737
		 */
1738
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1739
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1740
		}
1741
	}
1742
1743
1744
1745
1746
	/*
1747
	 *
1748
	 * Jetpack Security Reports
1749
	 *
1750
	 * Allowed types: login_form, backup, file_scanning, spam
1751
	 *
1752
	 * Args for login_form and spam: 'blocked'=>(int)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1753
	 *
1754
	 * Args for backup and file_scanning: 'last'=>(timestamp)(optional), 'next'=>(timestamp)(optional), 'status'=>(string)(ok, warning, error), 'message'=>(optional, disregarded if status is ok, allowed tags: a, em, strong)
1755
	 *
1756
	 *
1757
	 * Example code to submit a security report:
1758
	 *
1759
	 *  function akismet_submit_jetpack_security_report() {
1760
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1761
	 *  }
1762
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1763
	 *
1764
	 */
1765
1766
1767
	/**
1768
	 * Calls for security report submissions.
1769
	 *
1770
	 * @return null
1771
	 */
1772
	public static function perform_security_reporting() {
1773
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1774
1775
		if ( $no_check_needed ) {
1776
			return;
1777
		}
1778
1779
		/**
1780
		 * Fires before a security report is created.
1781
		 *
1782
		 * @since 3.4.0
1783
		 */
1784
		do_action( 'jetpack_security_report' );
1785
1786
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1787
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1788
	}
1789
1790
	/**
1791
	 * Allows plugins to submit security reports.
1792
 	 *
1793
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1794
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1795
	 * @param array   $args         See definitions above
1796
	 */
1797
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1798
1799
		if( !doing_action( 'jetpack_security_report' ) ) {
1800
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1801
		}
1802
1803
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1804
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1805
		}
1806
1807
		if( !function_exists( 'get_plugin_data' ) ) {
1808
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1809
		}
1810
1811
		//Get rid of any non-allowed args
1812
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1813
1814
		$plugin = get_plugin_data( $plugin_file );
1815
1816
		if ( !$plugin['Name'] ) {
1817
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1818
		}
1819
1820
		// Sanitize everything to make sure we're not syncing something wonky
1821
		$type = sanitize_key( $type );
1822
1823
		$args['plugin'] = $plugin;
1824
1825
		// Cast blocked, last and next as integers.
1826
		// Last and next should be in unix timestamp format
1827
		if ( isset( $args['blocked'] ) ) {
1828
			$args['blocked'] = (int) $args['blocked'];
1829
		}
1830
		if ( isset( $args['last'] ) ) {
1831
			$args['last'] = (int) $args['last'];
1832
		}
1833
		if ( isset( $args['next'] ) ) {
1834
			$args['next'] = (int) $args['next'];
1835
		}
1836
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1837
			$args['status'] = 'ok';
1838
		}
1839
		if ( isset( $args['message'] ) ) {
1840
1841
			if( $args['status'] == 'ok' ) {
1842
				unset( $args['message'] );
1843
			}
1844
1845
			$allowed_html = array(
1846
			    'a' => array(
1847
			        'href' => array(),
1848
			        'title' => array()
1849
			    ),
1850
			    'em' => array(),
1851
			    'strong' => array(),
1852
			);
1853
1854
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1855
		}
1856
1857
		$plugin_name = $plugin[ 'Name' ];
1858
1859
		self::$security_report[ $type ][ $plugin_name ] = $args;
1860
	}
1861
1862
	/**
1863
	 * Collects a new report if needed, then returns it.
1864
	 */
1865
	public function get_security_report() {
1866
		self::perform_security_reporting();
1867
		return Jetpack_Options::get_option( 'security_report' );
1868
	}
1869
1870
1871
/* Jetpack Options API */
1872
1873
	public static function get_option_names( $type = 'compact' ) {
1874
		return Jetpack_Options::get_option_names( $type );
1875
	}
1876
1877
	/**
1878
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1879
 	 *
1880
	 * @param string $name    Option name
1881
	 * @param mixed  $default (optional)
1882
	 */
1883
	public static function get_option( $name, $default = false ) {
1884
		return Jetpack_Options::get_option( $name, $default );
1885
	}
1886
1887
	/**
1888
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1889
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1890
	* $name must be a registered option name.
1891
	*/
1892
	public static function create_nonce( $name ) {
1893
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1894
1895
		Jetpack_Options::update_option( $name, $secret );
1896
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1897
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1898
			return new Jetpack_Error( 'missing_secrets' );
1899
1900
		return array(
1901
			'secret_1' => $secret_1,
1902
			'secret_2' => $secret_2,
1903
			'eol'      => $eol,
1904
		);
1905
	}
1906
1907
	/**
1908
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1909
 	 *
1910
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1911
	 * @param string $name  Option name
1912
	 * @param mixed  $value Option value
1913
	 */
1914
	public static function update_option( $name, $value ) {
1915
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1916
		return Jetpack_Options::update_option( $name, $value );
1917
	}
1918
1919
	/**
1920
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1921
 	 *
1922
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1923
	 * @param array $array array( option name => option value, ... )
1924
	 */
1925
	public static function update_options( $array ) {
1926
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1927
		return Jetpack_Options::update_options( $array );
1928
	}
1929
1930
	/**
1931
	 * Deletes the given option.  May be passed multiple option names as an array.
1932
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1933
	 *
1934
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1935
	 * @param string|array $names
1936
	 */
1937
	public static function delete_option( $names ) {
1938
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1939
		return Jetpack_Options::delete_option( $names );
1940
	}
1941
1942
	/**
1943
	 * Enters a user token into the user_tokens option
1944
	 *
1945
	 * @param int $user_id
1946
	 * @param string $token
1947
	 * return bool
1948
	 */
1949
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1950
		// not designed for concurrent updates
1951
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1952
		if ( ! is_array( $user_tokens ) )
1953
			$user_tokens = array();
1954
		$user_tokens[$user_id] = $token;
1955
		if ( $is_master_user ) {
1956
			$master_user = $user_id;
1957
			$options     = compact( 'user_tokens', 'master_user' );
1958
		} else {
1959
			$options = compact( 'user_tokens' );
1960
		}
1961
		return Jetpack_Options::update_options( $options );
1962
	}
1963
1964
	/**
1965
	 * Returns an array of all PHP files in the specified absolute path.
1966
	 * Equivalent to glob( "$absolute_path/*.php" ).
1967
	 *
1968
	 * @param string $absolute_path The absolute path of the directory to search.
1969
	 * @return array Array of absolute paths to the PHP files.
1970
	 */
1971
	public static function glob_php( $absolute_path ) {
1972
		if ( function_exists( 'glob' ) ) {
1973
			return glob( "$absolute_path/*.php" );
1974
		}
1975
1976
		$absolute_path = untrailingslashit( $absolute_path );
1977
		$files = array();
1978
		if ( ! $dir = @opendir( $absolute_path ) ) {
1979
			return $files;
1980
		}
1981
1982
		while ( false !== $file = readdir( $dir ) ) {
1983
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1984
				continue;
1985
			}
1986
1987
			$file = "$absolute_path/$file";
1988
1989
			if ( ! is_file( $file ) ) {
1990
				continue;
1991
			}
1992
1993
			$files[] = $file;
1994
		}
1995
1996
		closedir( $dir );
1997
1998
		return $files;
1999
	}
2000
2001
	public static function activate_new_modules( $redirect = false ) {
2002
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2003
			return;
2004
		}
2005
2006
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2007 View Code Duplication
		if ( ! $jetpack_old_version ) {
2008
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2009
			/** This action is documented in class.jetpack.php */
2010
			do_action( 'updating_jetpack_version', $version, false );
2011
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2012
		}
2013
2014
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2015
2016
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2017
			return;
2018
		}
2019
2020
		$active_modules     = Jetpack::get_active_modules();
2021
		$reactivate_modules = array();
2022
		foreach ( $active_modules as $active_module ) {
2023
			$module = Jetpack::get_module( $active_module );
2024
			if ( ! isset( $module['changed'] ) ) {
2025
				continue;
2026
			}
2027
2028
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2029
				continue;
2030
			}
2031
2032
			$reactivate_modules[] = $active_module;
2033
			Jetpack::deactivate_module( $active_module );
2034
		}
2035
2036
		$new_version = JETPACK__VERSION . ':' . time();
2037
		/** This action is documented in class.jetpack.php */
2038
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2039
		Jetpack_Options::update_options(
2040
			array(
2041
				'version'     => $new_version,
2042
				'old_version' => $jetpack_old_version,
2043
			)
2044
		);
2045
2046
		Jetpack::state( 'message', 'modules_activated' );
2047
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2048
2049
		if ( $redirect ) {
2050
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2051
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2052
				$page = $_GET['page'];
2053
			}
2054
2055
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2056
			exit;
2057
		}
2058
	}
2059
2060
	/**
2061
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2062
	 * Make sure to tuck away module "library" files in a sub-directory.
2063
	 */
2064
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2065
		static $modules = null;
2066
2067
		if ( ! isset( $modules ) ) {
2068
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2069
			// Use the cache if we're on the front-end and it's available...
2070
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2071
				$modules = $available_modules_option[ JETPACK__VERSION ];
2072
			} else {
2073
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2074
2075
				$modules = array();
2076
2077
				foreach ( $files as $file ) {
2078
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2079
						continue;
2080
					}
2081
2082
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2083
				}
2084
2085
				Jetpack_Options::update_option( 'available_modules', array(
2086
					JETPACK__VERSION => $modules,
2087
				) );
2088
			}
2089
		}
2090
2091
		/**
2092
		 * Filters the array of modules available to be activated.
2093
		 *
2094
		 * @since 2.4.0
2095
		 *
2096
		 * @param array $modules Array of available modules.
2097
		 * @param string $min_version Minimum version number required to use modules.
2098
		 * @param string $max_version Maximum version number required to use modules.
2099
		 */
2100
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2101
2102
		if ( ! $min_version && ! $max_version ) {
2103
			return array_keys( $mods );
2104
		}
2105
2106
		$r = array();
2107
		foreach ( $mods as $slug => $introduced ) {
2108
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2109
				continue;
2110
			}
2111
2112
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2113
				continue;
2114
			}
2115
2116
			$r[] = $slug;
2117
		}
2118
2119
		return $r;
2120
	}
2121
2122
	/**
2123
	 * Default modules loaded on activation.
2124
	 */
2125
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2126
		$return = array();
2127
2128
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2129
			$module_data = Jetpack::get_module( $module );
2130
2131
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2132
				case 'yes' :
2133
					$return[] = $module;
2134
					break;
2135
				case 'public' :
2136
					if ( Jetpack_Options::get_option( 'public' ) ) {
2137
						$return[] = $module;
2138
					}
2139
					break;
2140
				case 'no' :
2141
				default :
2142
					break;
2143
			}
2144
		}
2145
		/**
2146
		 * Filters the array of default modules.
2147
		 *
2148
		 * @since 2.5.0
2149
		 *
2150
		 * @param array $return Array of default modules.
2151
		 * @param string $min_version Minimum version number required to use modules.
2152
		 * @param string $max_version Maximum version number required to use modules.
2153
		 */
2154
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2155
	}
2156
2157
	/**
2158
	 * Checks activated modules during auto-activation to determine
2159
	 * if any of those modules are being deprecated.  If so, close
2160
	 * them out, and add any replacement modules.
2161
	 *
2162
	 * Runs at priority 99 by default.
2163
	 *
2164
	 * This is run late, so that it can still activate a module if
2165
	 * the new module is a replacement for another that the user
2166
	 * currently has active, even if something at the normal priority
2167
	 * would kibosh everything.
2168
	 *
2169
	 * @since 2.6
2170
	 * @uses jetpack_get_default_modules filter
2171
	 * @param array $modules
2172
	 * @return array
2173
	 */
2174
	function handle_deprecated_modules( $modules ) {
2175
		$deprecated_modules = array(
2176
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2177
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2178
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2179
		);
2180
2181
		// Don't activate SSO if they never completed activating WPCC.
2182
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2183
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2184
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2185
				$deprecated_modules['wpcc'] = null;
2186
			}
2187
		}
2188
2189
		foreach ( $deprecated_modules as $module => $replacement ) {
2190
			if ( Jetpack::is_module_active( $module ) ) {
2191
				self::deactivate_module( $module );
2192
				if ( $replacement ) {
2193
					$modules[] = $replacement;
2194
				}
2195
			}
2196
		}
2197
2198
		return array_unique( $modules );
2199
	}
2200
2201
	/**
2202
	 * Checks activated plugins during auto-activation to determine
2203
	 * if any of those plugins are in the list with a corresponding module
2204
	 * that is not compatible with the plugin. The module will not be allowed
2205
	 * to auto-activate.
2206
	 *
2207
	 * @since 2.6
2208
	 * @uses jetpack_get_default_modules filter
2209
	 * @param array $modules
2210
	 * @return array
2211
	 */
2212
	function filter_default_modules( $modules ) {
2213
2214
		$active_plugins = self::get_active_plugins();
2215
2216
		if ( ! empty( $active_plugins ) ) {
2217
2218
			// For each module we'd like to auto-activate...
2219
			foreach ( $modules as $key => $module ) {
2220
				// If there are potential conflicts for it...
2221
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2222
					// For each potential conflict...
2223
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2224
						// If that conflicting plugin is active...
2225
						if ( in_array( $plugin, $active_plugins ) ) {
2226
							// Remove that item from being auto-activated.
2227
							unset( $modules[ $key ] );
2228
						}
2229
					}
2230
				}
2231
			}
2232
		}
2233
2234
		return $modules;
2235
	}
2236
2237
	/**
2238
	 * Extract a module's slug from its full path.
2239
	 */
2240
	public static function get_module_slug( $file ) {
2241
		return str_replace( '.php', '', basename( $file ) );
2242
	}
2243
2244
	/**
2245
	 * Generate a module's path from its slug.
2246
	 */
2247
	public static function get_module_path( $slug ) {
2248
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2249
	}
2250
2251
	/**
2252
	 * Load module data from module file. Headers differ from WordPress
2253
	 * plugin headers to avoid them being identified as standalone
2254
	 * plugins on the WordPress plugins page.
2255
	 */
2256
	public static function get_module( $module ) {
2257
		$headers = array(
2258
			'name'                      => 'Module Name',
2259
			'description'               => 'Module Description',
2260
			'jumpstart_desc'            => 'Jumpstart Description',
2261
			'sort'                      => 'Sort Order',
2262
			'recommendation_order'      => 'Recommendation Order',
2263
			'introduced'                => 'First Introduced',
2264
			'changed'                   => 'Major Changes In',
2265
			'deactivate'                => 'Deactivate',
2266
			'free'                      => 'Free',
2267
			'requires_connection'       => 'Requires Connection',
2268
			'auto_activate'             => 'Auto Activate',
2269
			'module_tags'               => 'Module Tags',
2270
			'feature'                   => 'Feature',
2271
			'additional_search_queries' => 'Additional Search Queries',
2272
		);
2273
2274
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2275
2276
		$mod = Jetpack::get_file_data( $file, $headers );
2277
		if ( empty( $mod['name'] ) ) {
2278
			return false;
2279
		}
2280
2281
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2282
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2283
		$mod['deactivate']              = empty( $mod['deactivate'] );
2284
		$mod['free']                    = empty( $mod['free'] );
2285
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2286
2287
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2288
			$mod['auto_activate'] = 'No';
2289
		} else {
2290
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2291
		}
2292
2293
		if ( $mod['module_tags'] ) {
2294
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2295
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2296
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2297
		} else {
2298
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2299
		}
2300
2301
		if ( $mod['feature'] ) {
2302
			$mod['feature'] = explode( ',', $mod['feature'] );
2303
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2304
		} else {
2305
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2306
		}
2307
2308
		/**
2309
		 * Filters the feature array on a module.
2310
		 *
2311
		 * This filter allows you to control where each module is filtered: Recommended,
2312
		 * Jumpstart, and the default "Other" listing.
2313
		 *
2314
		 * @since 3.5.0
2315
		 *
2316
		 * @param array   $mod['feature'] The areas to feature this module:
2317
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2318
		 *     'Recommended' shows on the main Jetpack admin screen.
2319
		 *     'Other' should be the default if no other value is in the array.
2320
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2321
		 * @param array   $mod All the currently assembled module data.
2322
		 */
2323
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2324
2325
		/**
2326
		 * Filter the returned data about a module.
2327
		 *
2328
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2329
		 * so please be careful.
2330
		 *
2331
		 * @since 3.6.0
2332
		 *
2333
		 * @param array   $mod    The details of the requested module.
2334
		 * @param string  $module The slug of the module, e.g. sharedaddy
2335
		 * @param string  $file   The path to the module source file.
2336
		 */
2337
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2338
	}
2339
2340
	/**
2341
	 * Like core's get_file_data implementation, but caches the result.
2342
	 */
2343
	public static function get_file_data( $file, $headers ) {
2344
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2345
		$file_name = basename( $file );
2346
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2347
		$key              = md5( $file_name . serialize( $headers ) );
2348
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2349
2350
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2351
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2352
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2353
		}
2354
2355
		$data = get_file_data( $file, $headers );
2356
2357
		// Strip out any old Jetpack versions that are cluttering the option.
2358
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2359
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2360
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2361
2362
		return $data;
2363
	}
2364
2365
	/**
2366
	 * Return translated module tag.
2367
	 *
2368
	 * @param string $tag Tag as it appears in each module heading.
2369
	 *
2370
	 * @return mixed
2371
	 */
2372
	public static function translate_module_tag( $tag ) {
2373
		return jetpack_get_module_i18n_tag( $tag );
2374
	}
2375
2376
	/**
2377
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2378
	 *
2379
	 * @since 3.9.2
2380
	 *
2381
	 * @param array $modules
2382
	 *
2383
	 * @return string|void
2384
	 */
2385
	public static function get_translated_modules( $modules ) {
2386
		foreach ( $modules as $index => $module ) {
2387
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2388
			if ( isset( $module['name'] ) ) {
2389
				$modules[ $index ]['name'] = $i18n_module['name'];
2390
			}
2391
			if ( isset( $module['description'] ) ) {
2392
				$modules[ $index ]['description'] = $i18n_module['description'];
2393
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2394
			}
2395
		}
2396
		if ( Jetpack::is_module_active( 'manage' ) ) {
2397
			unset( $modules['manage'] );
2398
		}
2399
		return $modules;
2400
	}
2401
2402
	/**
2403
	 * Get a list of activated modules as an array of module slugs.
2404
	 */
2405
	public static function get_active_modules() {
2406
		$active = Jetpack_Options::get_option( 'active_modules' );
2407
		if ( ! is_array( $active ) )
2408
			$active = array();
2409
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2410
			$active[] = 'vaultpress';
2411
		} else {
2412
			$active = array_diff( $active, array( 'vaultpress' ) );
2413
		}
2414
2415
		//If protect is active on the main site of a multisite, it should be active on all sites.
2416
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2417
			$active[] = 'protect';
2418
		}
2419
2420
		return array_unique( $active );
2421
	}
2422
2423
	/**
2424
	 * Check whether or not a Jetpack module is active.
2425
	 *
2426
	 * @param string $module The slug of a Jetpack module.
2427
	 * @return bool
2428
	 *
2429
	 * @static
2430
	 */
2431
	public static function is_module_active( $module ) {
2432
		return in_array( $module, self::get_active_modules() );
2433
	}
2434
2435
	public static function is_module( $module ) {
2436
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2437
	}
2438
2439
	/**
2440
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2441
	 *
2442
	 * @param bool $catch True to start catching, False to stop.
2443
	 *
2444
	 * @static
2445
	 */
2446
	public static function catch_errors( $catch ) {
2447
		static $display_errors, $error_reporting;
2448
2449
		if ( $catch ) {
2450
			$display_errors  = @ini_set( 'display_errors', 1 );
2451
			$error_reporting = @error_reporting( E_ALL );
2452
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2453
		} else {
2454
			@ini_set( 'display_errors', $display_errors );
2455
			@error_reporting( $error_reporting );
2456
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2457
		}
2458
	}
2459
2460
	/**
2461
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2462
	 */
2463
	public static function catch_errors_on_shutdown() {
2464
		Jetpack::state( 'php_errors', ob_get_clean() );
2465
	}
2466
2467
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2468
		$jetpack = Jetpack::init();
2469
2470
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2471
		$modules = array_merge( $other_modules, $modules );
2472
2473
		// Look for standalone plugins and disable if active.
2474
2475
		$to_deactivate = array();
2476
		foreach ( $modules as $module ) {
2477
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2478
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2479
			}
2480
		}
2481
2482
		$deactivated = array();
2483
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2484
			list( $probable_file, $probable_title ) = $deactivate_me;
2485
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2486
				$deactivated[] = $module;
2487
			}
2488
		}
2489
2490
		if ( $deactivated && $redirect ) {
2491
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2492
2493
			$url = add_query_arg(
2494
				array(
2495
					'action'   => 'activate_default_modules',
2496
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2497
				),
2498
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2499
			);
2500
			wp_safe_redirect( $url );
2501
			exit;
2502
		}
2503
2504
		/**
2505
		 * Fires before default modules are activated.
2506
		 *
2507
		 * @since 1.9.0
2508
		 *
2509
		 * @param string $min_version Minimum version number required to use modules.
2510
		 * @param string $max_version Maximum version number required to use modules.
2511
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2512
		 */
2513
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2514
2515
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2516
		Jetpack::restate();
2517
		Jetpack::catch_errors( true );
2518
2519
		$active = Jetpack::get_active_modules();
2520
2521
		foreach ( $modules as $module ) {
2522
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2523
				$active[] = $module;
2524
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2525
				continue;
2526
			}
2527
2528
			if ( in_array( $module, $active ) ) {
2529
				$module_info = Jetpack::get_module( $module );
2530
				if ( ! $module_info['deactivate'] ) {
2531
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2532 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2533
						$active_state = explode( ',', $active_state );
2534
					} else {
2535
						$active_state = array();
2536
					}
2537
					$active_state[] = $module;
2538
					Jetpack::state( $state, implode( ',', $active_state ) );
2539
				}
2540
				continue;
2541
			}
2542
2543
			$file = Jetpack::get_module_path( $module );
2544
			if ( ! file_exists( $file ) ) {
2545
				continue;
2546
			}
2547
2548
			// we'll override this later if the plugin can be included without fatal error
2549
			if ( $redirect ) {
2550
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2551
			}
2552
			Jetpack::state( 'error', 'module_activation_failed' );
2553
			Jetpack::state( 'module', $module );
2554
			ob_start();
2555
			require $file;
2556
			/**
2557
			 * Fires when a specific module is activated.
2558
			 *
2559
			 * @since 1.9.0
2560
			 *
2561
			 * @param string $module Module slug.
2562
			 */
2563
			do_action( 'jetpack_activate_module', $module );
2564
			$active[] = $module;
2565
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2566 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2567
				$active_state = explode( ',', $active_state );
2568
			} else {
2569
				$active_state = array();
2570
			}
2571
			$active_state[] = $module;
2572
			Jetpack::state( $state, implode( ',', $active_state ) );
2573
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2574
			ob_end_clean();
2575
		}
2576
		Jetpack::state( 'error', false );
2577
		Jetpack::state( 'module', false );
2578
		Jetpack::catch_errors( false );
2579
		/**
2580
		 * Fires when default modules are activated.
2581
		 *
2582
		 * @since 1.9.0
2583
		 *
2584
		 * @param string $min_version Minimum version number required to use modules.
2585
		 * @param string $max_version Maximum version number required to use modules.
2586
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2587
		 */
2588
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2589
	}
2590
2591
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2592
		/**
2593
		 * Fires before a module is activated.
2594
		 *
2595
		 * @since 2.6.0
2596
		 *
2597
		 * @param string $module Module slug.
2598
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2599
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2600
		 */
2601
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2602
2603
		$jetpack = Jetpack::init();
2604
2605
		if ( ! strlen( $module ) )
2606
			return false;
2607
2608
		if ( ! Jetpack::is_module( $module ) )
2609
			return false;
2610
2611
		// If it's already active, then don't do it again
2612
		$active = Jetpack::get_active_modules();
2613
		foreach ( $active as $act ) {
2614
			if ( $act == $module )
2615
				return true;
2616
		}
2617
2618
		$module_data = Jetpack::get_module( $module );
2619
2620
		if ( ! Jetpack::is_active() ) {
2621
			if ( !Jetpack::is_development_mode() )
2622
				return false;
2623
2624
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2625
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2626
				return false;
2627
		}
2628
2629
		// Check and see if the old plugin is active
2630
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2631
			// Deactivate the old plugin
2632
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2633
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2634
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2635
				Jetpack::state( 'deactivated_plugins', $module );
2636
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2637
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2638
			}
2639
		}
2640
2641
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2642
		Jetpack::state( 'module', $module );
2643
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2644
2645
		Jetpack::catch_errors( true );
2646
		ob_start();
2647
		require Jetpack::get_module_path( $module );
2648
		/** This action is documented in class.jetpack.php */
2649
		do_action( 'jetpack_activate_module', $module );
2650
		$active[] = $module;
2651
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2652
		Jetpack::state( 'error', false ); // the override
2653
		Jetpack::state( 'message', 'module_activated' );
2654
		Jetpack::state( 'module', $module );
2655
		ob_end_clean();
2656
		Jetpack::catch_errors( false );
2657
2658
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2659 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2660
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2661
2662
			//Jump start is being dismissed send data to MC Stats
2663
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2664
2665
			$jetpack->do_stats( 'server_side' );
2666
		}
2667
2668
		if ( $redirect ) {
2669
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2670
		}
2671
		if ( $exit ) {
2672
			exit;
2673
		}
2674
		return true;
2675
	}
2676
2677
	function activate_module_actions( $module ) {
2678
		/**
2679
		 * Fires when a module is activated.
2680
		 * The dynamic part of the filter, $module, is the module slug.
2681
		 *
2682
		 * @since 1.9.0
2683
		 *
2684
		 * @param string $module Module slug.
2685
		 */
2686
		do_action( "jetpack_activate_module_$module", $module );
2687
	}
2688
2689
	public static function deactivate_module( $module ) {
2690
		/**
2691
		 * Fires when a module is deactivated.
2692
		 *
2693
		 * @since 1.9.0
2694
		 *
2695
		 * @param string $module Module slug.
2696
		 */
2697
		do_action( 'jetpack_pre_deactivate_module', $module );
2698
2699
		$jetpack = Jetpack::init();
2700
2701
		$active = Jetpack::get_active_modules();
2702
		$new    = array_filter( array_diff( $active, (array) $module ) );
2703
2704
		/**
2705
		 * Fires when a module is deactivated.
2706
		 * The dynamic part of the filter, $module, is the module slug.
2707
		 *
2708
		 * @since 1.9.0
2709
		 *
2710
		 * @param string $module Module slug.
2711
		 */
2712
		do_action( "jetpack_deactivate_module_$module", $module );
2713
2714
		// A flag for Jump Start so it's not shown again.
2715 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2716
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2717
2718
			//Jump start is being dismissed send data to MC Stats
2719
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2720
2721
			$jetpack->do_stats( 'server_side' );
2722
		}
2723
2724
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2725
		/**
2726
		 * Fired after a module has been deactivated.
2727
		 *
2728
		 * @since 4.1
2729
		 *
2730
		 * @param string $module Module slug.
2731
		 * @param boolean $success whether the module was deactivated.
2732
		 */
2733
		do_action( 'jetpack_deactivate_module', $module, $success );
2734
2735
		return $success;
2736
	}
2737
2738
	public static function enable_module_configurable( $module ) {
2739
		$module = Jetpack::get_module_slug( $module );
2740
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2741
	}
2742
2743
	public static function module_configuration_url( $module ) {
2744
		$module = Jetpack::get_module_slug( $module );
2745
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2746
	}
2747
2748
	public static function module_configuration_load( $module, $method ) {
2749
		$module = Jetpack::get_module_slug( $module );
2750
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2751
	}
2752
2753
	public static function module_configuration_head( $module, $method ) {
2754
		$module = Jetpack::get_module_slug( $module );
2755
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2756
	}
2757
2758
	public static function module_configuration_screen( $module, $method ) {
2759
		$module = Jetpack::get_module_slug( $module );
2760
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2761
	}
2762
2763
	public static function module_configuration_activation_screen( $module, $method ) {
2764
		$module = Jetpack::get_module_slug( $module );
2765
		add_action( 'display_activate_module_setting_' . $module, $method );
2766
	}
2767
2768
/* Installation */
2769
2770
	public static function bail_on_activation( $message, $deactivate = true ) {
2771
?>
2772
<!doctype html>
2773
<html>
2774
<head>
2775
<meta charset="<?php bloginfo( 'charset' ); ?>">
2776
<style>
2777
* {
2778
	text-align: center;
2779
	margin: 0;
2780
	padding: 0;
2781
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2782
}
2783
p {
2784
	margin-top: 1em;
2785
	font-size: 18px;
2786
}
2787
</style>
2788
<body>
2789
<p><?php echo esc_html( $message ); ?></p>
2790
</body>
2791
</html>
2792
<?php
2793
		if ( $deactivate ) {
2794
			$plugins = get_option( 'active_plugins' );
2795
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2796
			$update  = false;
2797
			foreach ( $plugins as $i => $plugin ) {
2798
				if ( $plugin === $jetpack ) {
2799
					$plugins[$i] = false;
2800
					$update = true;
2801
				}
2802
			}
2803
2804
			if ( $update ) {
2805
				update_option( 'active_plugins', array_filter( $plugins ) );
2806
			}
2807
		}
2808
		exit;
2809
	}
2810
2811
	/**
2812
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2813
	 * @static
2814
	 */
2815
	public static function plugin_activation( $network_wide ) {
2816
		Jetpack_Options::update_option( 'activated', 1 );
2817
2818
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2819
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2820
		}
2821
2822
		if ( $network_wide )
2823
			Jetpack::state( 'network_nag', true );
2824
2825
		Jetpack::plugin_initialize();
2826
	}
2827
	/**
2828
	 * Runs before bumping version numbers up to a new version
2829
	 * @param  (string) $version    Version:timestamp
2830
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2831
	 * @return null              [description]
2832
	 */
2833
	public static function do_version_bump( $version, $old_version ) {
2834
2835
		if ( ! $old_version ) { // For new sites
2836
			// Setting up jetpack manage
2837
			Jetpack::activate_manage();
2838
		}
2839
	}
2840
2841
	/**
2842
	 * Sets the internal version number and activation state.
2843
	 * @static
2844
	 */
2845
	public static function plugin_initialize() {
2846
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2847
			Jetpack_Options::update_option( 'activated', 2 );
2848
		}
2849
2850 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2851
			$version = $old_version = JETPACK__VERSION . ':' . time();
2852
			/** This action is documented in class.jetpack.php */
2853
			do_action( 'updating_jetpack_version', $version, false );
2854
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2855
		}
2856
2857
		Jetpack::load_modules();
2858
2859
		Jetpack_Options::delete_option( 'do_activate' );
2860
	}
2861
2862
	/**
2863
	 * Removes all connection options
2864
	 * @static
2865
	 */
2866
	public static function plugin_deactivation( ) {
2867
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2868
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2869
			Jetpack_Network::init()->deactivate();
2870
		} else {
2871
			Jetpack::disconnect( false );
2872
			//Jetpack_Heartbeat::init()->deactivate();
2873
		}
2874
	}
2875
2876
	/**
2877
	 * Disconnects from the Jetpack servers.
2878
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2879
	 * @static
2880
	 */
2881
	public static function disconnect( $update_activated_state = true ) {
2882
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2883
		Jetpack::clean_nonces( true );
2884
2885
		Jetpack::load_xml_rpc_client();
2886
		$xml = new Jetpack_IXR_Client();
2887
		$xml->query( 'jetpack.deregister' );
2888
2889
		Jetpack_Options::delete_option(
2890
			array(
2891
				'register',
2892
				'blog_token',
2893
				'user_token',
2894
				'user_tokens',
2895
				'master_user',
2896
				'time_diff',
2897
				'fallback_no_verify_ssl_certs',
2898
			)
2899
		);
2900
2901
		if ( $update_activated_state ) {
2902
			Jetpack_Options::update_option( 'activated', 4 );
2903
		}
2904
2905
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2906
		// Check then record unique disconnection if site has never been disconnected previously
2907
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2908
			$jetpack_unique_connection['disconnected'] = 1;
2909
		}
2910
		else {
2911
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2912
				//track unique disconnect
2913
				$jetpack = Jetpack::init();
2914
2915
				$jetpack->stat( 'connections', 'unique-disconnect' );
2916
				$jetpack->do_stats( 'server_side' );
2917
			}
2918
			// increment number of times disconnected
2919
			$jetpack_unique_connection['disconnected'] += 1;
2920
		}
2921
2922
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2923
		
2924
		// Delete all the sync related data. Since it could be taking up space.
2925
		Jetpack_Sync_Sender::getInstance()->uninstall();
2926
2927
		// Disable the Heartbeat cron
2928
		Jetpack_Heartbeat::init()->deactivate();
2929
	}
2930
2931
	/**
2932
	 * Unlinks the current user from the linked WordPress.com user
2933
	 */
2934
	public static function unlink_user( $user_id = null ) {
2935
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2936
			return false;
2937
2938
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2939
2940
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2941
			return false;
2942
2943
		if ( ! isset( $tokens[ $user_id ] ) )
2944
			return false;
2945
2946
		Jetpack::load_xml_rpc_client();
2947
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2948
		$xml->query( 'jetpack.unlink_user', $user_id );
2949
2950
		unset( $tokens[ $user_id ] );
2951
2952
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2953
2954
		/**
2955
		 * Fires after the current user has been unlinked from WordPress.com.
2956
		 *
2957
		 * @since 4.1.0
2958
		 *
2959
		 * @param int $user_id The current user's ID.
2960
		 */
2961
		do_action( 'jetpack_unlinked_user', $user_id );
2962
2963
		return true;
2964
	}
2965
2966
	/**
2967
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2968
	 */
2969
	public static function try_registration() {
2970
		// Let's get some testing in beta versions and such.
2971
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2972
			// Before attempting to connect, let's make sure that the domains are viable.
2973
			$domains_to_check = array_unique( array(
2974
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2975
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2976
			) );
2977
			foreach ( $domains_to_check as $domain ) {
2978
				$result = Jetpack_Data::is_usable_domain( $domain );
2979
				if ( is_wp_error( $result ) ) {
2980
					return $result;
2981
				}
2982
			}
2983
		}
2984
2985
		$result = Jetpack::register();
2986
2987
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2988
		if ( ! $result || is_wp_error( $result ) ) {
2989
			return $result;
2990
		} else {
2991
			return true;
2992
		}
2993
	}
2994
2995
	/**
2996
	 * Tracking an internal event log. Try not to put too much chaff in here.
2997
	 *
2998
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2999
	 */
3000
	public static function log( $code, $data = null ) {
3001
		// only grab the latest 200 entries
3002
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3003
3004
		// Append our event to the log
3005
		$log_entry = array(
3006
			'time'    => time(),
3007
			'user_id' => get_current_user_id(),
3008
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3009
			'code'    => $code,
3010
		);
3011
		// Don't bother storing it unless we've got some.
3012
		if ( ! is_null( $data ) ) {
3013
			$log_entry['data'] = $data;
3014
		}
3015
		$log[] = $log_entry;
3016
3017
		// Try add_option first, to make sure it's not autoloaded.
3018
		// @todo: Add an add_option method to Jetpack_Options
3019
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3020
			Jetpack_Options::update_option( 'log', $log );
3021
		}
3022
3023
		/**
3024
		 * Fires when Jetpack logs an internal event.
3025
		 *
3026
		 * @since 3.0.0
3027
		 *
3028
		 * @param array $log_entry {
3029
		 *	Array of details about the log entry.
3030
		 *
3031
		 *	@param string time Time of the event.
3032
		 *	@param int user_id ID of the user who trigerred the event.
3033
		 *	@param int blog_id Jetpack Blog ID.
3034
		 *	@param string code Unique name for the event.
3035
		 *	@param string data Data about the event.
3036
		 * }
3037
		 */
3038
		do_action( 'jetpack_log_entry', $log_entry );
3039
	}
3040
3041
	/**
3042
	 * Get the internal event log.
3043
	 *
3044
	 * @param $event (string) - only return the specific log events
3045
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3046
	 *
3047
	 * @return array of log events || WP_Error for invalid params
3048
	 */
3049
	public static function get_log( $event = false, $num = false ) {
3050
		if ( $event && ! is_string( $event ) ) {
3051
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3052
		}
3053
3054
		if ( $num && ! is_numeric( $num ) ) {
3055
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3056
		}
3057
3058
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3059
3060
		// If nothing set - act as it did before, otherwise let's start customizing the output
3061
		if ( ! $num && ! $event ) {
3062
			return $entire_log;
3063
		} else {
3064
			$entire_log = array_reverse( $entire_log );
3065
		}
3066
3067
		$custom_log_output = array();
3068
3069
		if ( $event ) {
3070
			foreach ( $entire_log as $log_event ) {
3071
				if ( $event == $log_event[ 'code' ] ) {
3072
					$custom_log_output[] = $log_event;
3073
				}
3074
			}
3075
		} else {
3076
			$custom_log_output = $entire_log;
3077
		}
3078
3079
		if ( $num ) {
3080
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3081
		}
3082
3083
		return $custom_log_output;
3084
	}
3085
3086
	/**
3087
	 * Log modification of important settings.
3088
	 */
3089
	public static function log_settings_change( $option, $old_value, $value ) {
3090
		switch( $option ) {
3091
			case 'jetpack_sync_non_public_post_stati':
3092
				self::log( $option, $value );
3093
				break;
3094
		}
3095
	}
3096
3097
	/**
3098
	 * Return stat data for WPCOM sync
3099
	 */
3100
	function get_stat_data() {
3101
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3102
		$additional_data = $this->get_additional_stat_data();
3103
3104
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3105
	}
3106
3107
	/**
3108
	 * Get additional stat data to sync to WPCOM
3109
	 */
3110
	function get_additional_stat_data( $prefix = '' ) {
3111
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3112
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3113
		$return["{$prefix}users"]          = count_users();
3114
		$return["{$prefix}site-count"]     = 0;
3115
		if ( function_exists( 'get_blog_count' ) ) {
3116
			$return["{$prefix}site-count"] = get_blog_count();
3117
		}
3118
		return $return;
3119
	}
3120
3121
	/* Admin Pages */
3122
3123
	function admin_init() {
3124
		// If the plugin is not connected, display a connect message.
3125
		if (
3126
			// the plugin was auto-activated and needs its candy
3127
			Jetpack_Options::get_option( 'do_activate' )
3128
		||
3129
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3130
			! Jetpack_Options::get_option( 'activated' )
3131
		) {
3132
			Jetpack::plugin_initialize();
3133
		}
3134
3135
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3136
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3137
				// Show connect notice on dashboard and plugins pages
3138
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3139
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3140
			}
3141
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3142
			// Upgrade: 1.1 -> 1.1.1
3143
			// Check and see if host can verify the Jetpack servers' SSL certificate
3144
			$args = array();
3145
			Jetpack_Client::_wp_remote_request(
3146
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3147
				$args,
3148
				true
3149
			);
3150
		} else {
3151
			// Show the notice on the Dashboard only for now
3152
3153
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3154
		}
3155
3156
		// If the plugin has just been disconnected from WP.com, show the survey notice
3157
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3158
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3159
		}
3160
3161
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3162
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3163
		}
3164
3165
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3166
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3167
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3168
3169
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3170
			// Artificially throw errors in certain whitelisted cases during plugin activation
3171
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3172
3173
			// Kick off synchronization of user role when it changes
3174
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3175
		}
3176
3177
		// Jetpack Manage Activation Screen from .com
3178
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3179
3180
		// Add custom column in wp-admin/users.php to show whether user is linked.
3181
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3182
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3183
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3184
	}
3185
3186
	function admin_body_class( $admin_body_class = '' ) {
3187
		$classes = explode( ' ', trim( $admin_body_class ) );
3188
3189
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3190
3191
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3192
		return " $admin_body_class ";
3193
	}
3194
3195
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3196
		return $admin_body_class . ' jetpack-pagestyles ';
3197
	}
3198
3199
	function prepare_connect_notice() {
3200
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3201
3202
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3203
3204
		if ( Jetpack::state( 'network_nag' ) )
3205
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3206
	}
3207
	/**
3208
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3209
	 *
3210
	 * @return null
3211
	 */
3212
	function prepare_manage_jetpack_notice() {
3213
3214
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3215
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3216
	}
3217
3218
	function manage_activate_screen() {
3219
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3220
	}
3221
	/**
3222
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3223
	 * This function artificially throws errors for such cases (whitelisted).
3224
	 *
3225
	 * @param string $plugin The activated plugin.
3226
	 */
3227
	function throw_error_on_activate_plugin( $plugin ) {
3228
		$active_modules = Jetpack::get_active_modules();
3229
3230
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3231
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3232
			$throw = false;
3233
3234
			// Try and make sure it really was the stats plugin
3235
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3236
				if ( 'stats.php' == basename( $plugin ) ) {
3237
					$throw = true;
3238
				}
3239
			} else {
3240
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3241
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3242
					$throw = true;
3243
				}
3244
			}
3245
3246
			if ( $throw ) {
3247
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3248
			}
3249
		}
3250
	}
3251
3252
	function intercept_plugin_error_scrape_init() {
3253
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3254
	}
3255
3256
	function intercept_plugin_error_scrape( $action, $result ) {
3257
		if ( ! $result ) {
3258
			return;
3259
		}
3260
3261
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3262
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3263
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3264
			}
3265
		}
3266
	}
3267
3268
	function add_remote_request_handlers() {
3269
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3270
	}
3271
3272
	function remote_request_handlers() {
3273
		switch ( current_filter() ) {
3274
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3275
			$response = $this->upload_handler();
3276
			break;
3277
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
3278
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3279
			break;
3280
		}
3281
3282
		if ( ! $response ) {
3283
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3284
		}
3285
3286
		if ( is_wp_error( $response ) ) {
3287
			$status_code       = $response->get_error_data();
3288
			$error             = $response->get_error_code();
3289
			$error_description = $response->get_error_message();
3290
3291
			if ( ! is_int( $status_code ) ) {
3292
				$status_code = 400;
3293
			}
3294
3295
			status_header( $status_code );
3296
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3297
		}
3298
3299
		status_header( 200 );
3300
		if ( true === $response ) {
3301
			exit;
3302
		}
3303
3304
		die( json_encode( (object) $response ) );
3305
	}
3306
3307
	function upload_handler() {
3308
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3309
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3310
		}
3311
3312
		$user = wp_authenticate( '', '' );
3313
		if ( ! $user || is_wp_error( $user ) ) {
3314
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3315
		}
3316
3317
		wp_set_current_user( $user->ID );
3318
3319
		if ( ! current_user_can( 'upload_files' ) ) {
3320
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3321
		}
3322
3323
		if ( empty( $_FILES ) ) {
3324
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3325
		}
3326
3327
		foreach ( array_keys( $_FILES ) as $files_key ) {
3328
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3329
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3330
			}
3331
		}
3332
3333
		$media_keys = array_keys( $_FILES['media'] );
3334
3335
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3336
		if ( ! $token || is_wp_error( $token ) ) {
3337
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3338
		}
3339
3340
		$uploaded_files = array();
3341
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3342
		unset( $GLOBALS['post'] );
3343
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3344
			$file = array();
3345
			foreach ( $media_keys as $media_key ) {
3346
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3347
			}
3348
3349
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3350
3351
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3352
			if ( $hmac_provided !== $hmac_file ) {
3353
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3354
				continue;
3355
			}
3356
3357
			$_FILES['.jetpack.upload.'] = $file;
3358
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3359
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3360
				$post_id = 0;
3361
			}
3362
			$attachment_id = media_handle_upload(
3363
				'.jetpack.upload.',
3364
				$post_id,
3365
				array(),
3366
				array(
3367
					'action' => 'jetpack_upload_file',
3368
				)
3369
			);
3370
3371
			if ( ! $attachment_id ) {
3372
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3373
			} elseif ( is_wp_error( $attachment_id ) ) {
3374
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3375
			} else {
3376
				$attachment = get_post( $attachment_id );
3377
				$uploaded_files[$index] = (object) array(
3378
					'id'   => (string) $attachment_id,
3379
					'file' => $attachment->post_title,
3380
					'url'  => wp_get_attachment_url( $attachment_id ),
3381
					'type' => $attachment->post_mime_type,
3382
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3383
				);
3384
			}
3385
		}
3386
		if ( ! is_null( $global_post ) ) {
3387
			$GLOBALS['post'] = $global_post;
3388
		}
3389
3390
		return $uploaded_files;
3391
	}
3392
3393
	/**
3394
	 * Add help to the Jetpack page
3395
	 *
3396
	 * @since Jetpack (1.2.3)
3397
	 * @return false if not the Jetpack page
3398
	 */
3399
	function admin_help() {
3400
		$current_screen = get_current_screen();
3401
3402
		// Overview
3403
		$current_screen->add_help_tab(
3404
			array(
3405
				'id'		=> 'home',
3406
				'title'		=> __( 'Home', 'jetpack' ),
3407
				'content'	=>
3408
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3409
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3410
					'<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>',
3411
			)
3412
		);
3413
3414
		// Screen Content
3415
		if ( current_user_can( 'manage_options' ) ) {
3416
			$current_screen->add_help_tab(
3417
				array(
3418
					'id'		=> 'settings',
3419
					'title'		=> __( 'Settings', 'jetpack' ),
3420
					'content'	=>
3421
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3422
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3423
						'<ol>' .
3424
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3425
							'<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>' .
3426
						'</ol>' .
3427
						'<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>'
3428
				)
3429
			);
3430
		}
3431
3432
		// Help Sidebar
3433
		$current_screen->set_help_sidebar(
3434
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3435
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3436
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3437
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3438
		);
3439
	}
3440
3441
	function admin_menu_css() {
3442
		wp_enqueue_style( 'jetpack-icons' );
3443
	}
3444
3445
	function admin_menu_order() {
3446
		return true;
3447
	}
3448
3449 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3450
		$jp_menu_order = array();
3451
3452
		foreach ( $menu_order as $index => $item ) {
3453
			if ( $item != 'jetpack' ) {
3454
				$jp_menu_order[] = $item;
3455
			}
3456
3457
			if ( $index == 0 ) {
3458
				$jp_menu_order[] = 'jetpack';
3459
			}
3460
		}
3461
3462
		return $jp_menu_order;
3463
	}
3464
3465
	function admin_head() {
3466 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3467
			/** This action is documented in class.jetpack-admin-page.php */
3468
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3469
	}
3470
3471
	function admin_banner_styles() {
3472
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3473
3474
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3475
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3476
		wp_style_add_data( 'jetpack', 'suffix', $min );
3477
	}
3478
3479
	function admin_scripts() {
3480
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3481
		wp_localize_script(
3482
			'jetpack-js',
3483
			'jetpackL10n',
3484
			array(
3485
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3486
				'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?",
3487
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3488
			)
3489
		);
3490
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3491
	}
3492
3493
	function plugin_action_links( $actions ) {
3494
3495
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3496
3497
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3498
			return array_merge(
3499
				$jetpack_home,
3500
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3501
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3502
				$actions
3503
				);
3504
			}
3505
3506
		return array_merge( $jetpack_home, $actions );
3507
	}
3508
3509
	function admin_connect_notice() {
3510
		// Don't show the connect notice anywhere but the plugins.php after activating
3511
		$current = get_current_screen();
3512
		if ( 'plugins' !== $current->parent_base )
3513
			return;
3514
3515
		if ( ! current_user_can( 'jetpack_connect' ) )
3516
			return;
3517
3518
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3519
		?>
3520
		<div id="message" class="updated jp-banner">
3521
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3522
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3523
					<div class="jp-banner__description-container">
3524
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3525
						<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>
3526
						<p class="jp-banner__button-container">
3527
							<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>
3528
							<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>
3529
						</p>
3530
					</div>
3531 View Code Duplication
			<?php else : ?>
3532
				<div class="jp-banner__content">
3533
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3534
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3535
				</div>
3536
				<div class="jp-banner__action-container">
3537
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3538
				</div>
3539
			<?php endif; ?>
3540
		</div>
3541
3542
		<?php
3543
	}
3544
3545
	/**
3546
	 * This is the first banner
3547
	 * It should be visible only to user that can update the option
3548
	 * Are not connected
3549
	 *
3550
	 * @return null
3551
	 */
3552
	function admin_jetpack_manage_notice() {
3553
		$screen = get_current_screen();
3554
3555
		// Don't show the connect notice on the jetpack settings page.
3556
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3557
			return;
3558
3559
		// Only show it if don't have the managment option set.
3560
		// And not dismissed it already.
3561
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3562
			return;
3563
		}
3564
3565
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3566
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3567
		/**
3568
		 * I think it would be great to have different wordsing depending on where you are
3569
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3570
		 * etc..
3571
		 */
3572
3573
		?>
3574
		<div id="message" class="updated jp-banner">
3575
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3576
				<div class="jp-banner__description-container">
3577
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3578
					<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>
3579
					<p class="jp-banner__button-container">
3580
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3581
						<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>
3582
					</p>
3583
				</div>
3584
		</div>
3585
		<?php
3586
	}
3587
3588
	/**
3589
	 * Returns the url that the user clicks to remove the notice for the big banner
3590
	 * @return (string)
3591
	 */
3592
	function opt_out_jetpack_manage_url() {
3593
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3594
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3595
	}
3596
	/**
3597
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3598
	 * @return (string)
3599
	 */
3600
	function opt_in_jetpack_manage_url() {
3601
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3602
	}
3603
3604
	function opt_in_jetpack_manage_notice() {
3605
		?>
3606
		<div class="wrap">
3607
			<div id="message" class="jetpack-message is-opt-in">
3608
				<?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' ); ?>
3609
			</div>
3610
		</div>
3611
		<?php
3612
3613
	}
3614
	/**
3615
	 * Determines whether to show the notice of not true = display notice
3616
	 * @return (bool)
3617
	 */
3618
	function can_display_jetpack_manage_notice() {
3619
		// never display the notice to users that can't do anything about it anyways
3620
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3621
			return false;
3622
3623
		// don't display if we are in development more
3624
		if( Jetpack::is_development_mode() ) {
3625
			return false;
3626
		}
3627
		// don't display if the site is private
3628
		if(  ! Jetpack_Options::get_option( 'public' ) )
3629
			return false;
3630
3631
		/**
3632
		 * Should the Jetpack Remote Site Management notice be displayed.
3633
		 *
3634
		 * @since 3.3.0
3635
		 *
3636
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3637
		 */
3638
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3639
	}
3640
3641
	function network_connect_notice() {
3642
		?>
3643
		<div id="message" class="updated jetpack-message">
3644
			<div class="squeezer">
3645
				<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>
3646
			</div>
3647
		</div>
3648
		<?php
3649
	}
3650
3651
	public static function jetpack_comment_notice() {
3652
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3653
			return '';
3654
		}
3655
3656
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3657
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3658
3659
		if ( $jetpack_old_version ) {
3660
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3661
				return '';
3662
			}
3663
		}
3664
3665
		if ( $jetpack_new_version ) {
3666
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3667
				return '';
3668
			}
3669
		}
3670
3671
		return '<br /><br />' . sprintf(
3672
			__( 'Jetpack now includes Comments, which enables your visitors to use their WordPress.com, Twitter, or Facebook accounts when commenting on your site. To activate Comments, <a href="%s">%s</a>.', 'jetpack' ),
3673
			wp_nonce_url(
3674
				Jetpack::admin_url(
3675
					array(
3676
						'page'   => 'jetpack',
3677
						'action' => 'activate',
3678
						'module' => 'comments',
3679
					)
3680
				),
3681
				'jetpack_activate-comments'
3682
			),
3683
			__( 'click here', 'jetpack' )
3684
		);
3685
	}
3686
3687
	/**
3688
	 * Show the survey link when the user has just disconnected Jetpack.
3689
	 */
3690
	function disconnect_survey_notice() {
3691
		?>
3692
		<div class="wrap">
3693
			<div id="message" class="jetpack-message stay-visible">
3694
				<div class="squeezer">
3695
					<h2>
3696
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3697
						<br />
3698
						<?php echo sprintf(
3699
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3700
							'https://jetpack.com/survey-disconnected/',
3701
							'_blank'
3702
						); ?>
3703
					</h2>
3704
				</div>
3705
			</div>
3706
		</div>
3707
		<?php
3708
	}
3709
3710
	/*
3711
	 * Registration flow:
3712
	 * 1 - ::admin_page_load() action=register
3713
	 * 2 - ::try_registration()
3714
	 * 3 - ::register()
3715
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3716
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3717
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3718
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3719
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3720
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3721
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3722
	 *       jetpack_id, jetpack_secret, jetpack_public
3723
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3724
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3725
	 * 5 - user logs in with WP.com account
3726
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3727
	 *		- Jetpack_Client_Server::authorize()
3728
	 *		- Jetpack_Client_Server::get_token()
3729
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3730
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3731
	 *			- which responds with access_token, token_type, scope
3732
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3733
	 *		- Jetpack::activate_default_modules()
3734
	 *     		- Deactivates deprecated plugins
3735
	 *     		- Activates all default modules
3736
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3737
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3738
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3739
	 *     Done!
3740
	 */
3741
3742
	/**
3743
	 * Handles the page load events for the Jetpack admin page
3744
	 */
3745
	function admin_page_load() {
3746
		$error = false;
3747
3748
		// Make sure we have the right body class to hook stylings for subpages off of.
3749
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3750
3751
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3752
			// Should only be used in intermediate redirects to preserve state across redirects
3753
			Jetpack::restate();
3754
		}
3755
3756
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3757
			// User clicked in the iframe to link their accounts
3758
			if ( ! Jetpack::is_user_connected() ) {
3759
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3760
				if ( isset( $_GET['notes_iframe'] ) )
3761
					$connect_url .= '&notes_iframe';
3762
				wp_redirect( $connect_url );
3763
				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...
3764
			} else {
3765
				if ( ! isset( $_GET['calypso_env'] ) ) {
3766
					Jetpack::state( 'message', 'already_authorized' );
3767
					wp_safe_redirect( Jetpack::admin_url() );
3768
				} else {
3769
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3770
					$connect_url .= '&already_authorized=true';
3771
					wp_redirect( $connect_url );
3772
				}
3773
			}
3774
		}
3775
3776
3777
		if ( isset( $_GET['action'] ) ) {
3778
			switch ( $_GET['action'] ) {
3779
			case 'authorize':
3780
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3781
					Jetpack::state( 'message', 'already_authorized' );
3782
					wp_safe_redirect( Jetpack::admin_url() );
3783
					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...
3784
				}
3785
				Jetpack::log( 'authorize' );
3786
				$client_server = new Jetpack_Client_Server;
3787
				$client_server->client_authorize();
3788
				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...
3789
			case 'register' :
3790
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3791
					$error = 'cheatin';
3792
					break;
3793
				}
3794
				check_admin_referer( 'jetpack-register' );
3795
				Jetpack::log( 'register' );
3796
				Jetpack::maybe_set_version_option();
3797
				$registered = Jetpack::try_registration();
3798
				if ( is_wp_error( $registered ) ) {
3799
					$error = $registered->get_error_code();
3800
					Jetpack::state( 'error_description', $registered->get_error_message() );
3801
					break;
3802
				}
3803
3804
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3805
3806
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3807
				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...
3808
			case 'activate' :
3809
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3810
					$error = 'cheatin';
3811
					break;
3812
				}
3813
3814
				$module = stripslashes( $_GET['module'] );
3815
				check_admin_referer( "jetpack_activate-$module" );
3816
				Jetpack::log( 'activate', $module );
3817
				Jetpack::activate_module( $module );
3818
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3819
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3820
				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...
3821
			case 'activate_default_modules' :
3822
				check_admin_referer( 'activate_default_modules' );
3823
				Jetpack::log( 'activate_default_modules' );
3824
				Jetpack::restate();
3825
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3826
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3827
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3828
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3829
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3830
				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...
3831
			case 'disconnect' :
3832
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3833
					$error = 'cheatin';
3834
					break;
3835
				}
3836
3837
				check_admin_referer( 'jetpack-disconnect' );
3838
				Jetpack::log( 'disconnect' );
3839
				Jetpack::disconnect();
3840
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3841
				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...
3842
			case 'reconnect' :
3843
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3844
					$error = 'cheatin';
3845
					break;
3846
				}
3847
3848
				check_admin_referer( 'jetpack-reconnect' );
3849
				Jetpack::log( 'reconnect' );
3850
				$this->disconnect();
3851
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3852
				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...
3853 View Code Duplication
			case 'deactivate' :
3854
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3855
					$error = 'cheatin';
3856
					break;
3857
				}
3858
3859
				$modules = stripslashes( $_GET['module'] );
3860
				check_admin_referer( "jetpack_deactivate-$modules" );
3861
				foreach ( explode( ',', $modules ) as $module ) {
3862
					Jetpack::log( 'deactivate', $module );
3863
					Jetpack::deactivate_module( $module );
3864
					Jetpack::state( 'message', 'module_deactivated' );
3865
				}
3866
				Jetpack::state( 'module', $modules );
3867
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3868
				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...
3869
			case 'unlink' :
3870
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3871
				check_admin_referer( 'jetpack-unlink' );
3872
				Jetpack::log( 'unlink' );
3873
				$this->unlink_user();
3874
				Jetpack::state( 'message', 'unlinked' );
3875
				if ( 'sub-unlink' == $redirect ) {
3876
					wp_safe_redirect( admin_url() );
3877
				} else {
3878
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3879
				}
3880
				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...
3881
			default:
3882
				/**
3883
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3884
				 *
3885
				 * @since 2.6.0
3886
				 *
3887
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3888
				 */
3889
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3890
			}
3891
		}
3892
3893
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3894
			self::activate_new_modules( true );
3895
		}
3896
3897
		switch ( $error ) {
3898
		case 'cheatin' :
3899
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3900
			break;
3901
		case 'access_denied' :
3902
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'https://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
3903
			break;
3904
		case 'wrong_state' :
3905
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3906
			break;
3907
		case 'invalid_client' :
3908
			// @todo re-register instead of deactivate/reactivate
3909
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3910
			break;
3911
		case 'invalid_grant' :
3912
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3913
			break;
3914
		case 'site_inaccessible' :
3915
		case 'site_requires_authorization' :
3916
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3917
			break;
3918
		case 'module_activation_failed' :
3919
			$module = Jetpack::state( 'module' );
3920
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3921
				$this->error = sprintf( __( '%s could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' ), $mod['name'] );
3922
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3923
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3924
				}
3925
			} else {
3926
				$this->error = __( 'Module could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' );
3927
			}
3928
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
3929
				$this->error .= "<br />\n";
3930
				$this->error .= $php_errors;
3931
			}
3932
			break;
3933
		case 'master_user_required' :
3934
			$module = Jetpack::state( 'module' );
3935
			$module_name = '';
3936
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3937
				$module_name = $mod['name'];
3938
			}
3939
3940
			$master_user = Jetpack_Options::get_option( 'master_user' );
3941
			$master_userdata = get_userdata( $master_user ) ;
3942
			if ( $master_userdata ) {
3943
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
3944
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
3945
				} else {
3946
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
3947
				}
3948
				$this->error .= '  ' . sprintf( __( 'This module can only be altered by %s, the user who initiated the Jetpack connection on this site.' , 'jetpack' ), esc_html( $master_userdata->display_name ) );
3949
3950
			} else {
3951
				$this->error = sprintf( __( 'Only the user who initiated the Jetpack connection on this site can toggle %s, but that user no longer exists. This should not happen.', 'jetpack' ), $module_name );
3952
			}
3953
			break;
3954
		case 'not_public' :
3955
			$this->error = __( '<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. This usually means your site is not publicly accessible (localhost).', 'jetpack' );
3956
			break;
3957
		case 'wpcom_408' :
3958
		case 'wpcom_5??' :
3959
		case 'wpcom_bad_response' :
3960
		case 'wpcom_outage' :
3961
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
3962
			break;
3963
		case 'register_http_request_failed' :
3964
		case 'token_http_request_failed' :
3965
			$this->error = sprintf( __( 'Jetpack could not contact WordPress.com: %s.  This usually means something is incorrectly configured on your web host.', 'jetpack' ), "<code>$error</code>" );
3966
			break;
3967
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
3968
			if ( empty( $error ) ) {
3969
				break;
3970
			}
3971
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
3972
			// no break: fall through
3973
		case 'no_role' :
3974
		case 'no_cap' :
3975
		case 'no_code' :
3976
		case 'no_state' :
3977
		case 'invalid_state' :
3978
		case 'invalid_request' :
3979
		case 'invalid_scope' :
3980
		case 'unsupported_response_type' :
3981
		case 'invalid_token' :
3982
		case 'no_token' :
3983
		case 'missing_secrets' :
3984
		case 'home_missing' :
3985
		case 'siteurl_missing' :
3986
		case 'gmt_offset_missing' :
3987
		case 'site_name_missing' :
3988
		case 'secret_1_missing' :
3989
		case 'secret_2_missing' :
3990
		case 'site_lang_missing' :
3991
		case 'home_malformed' :
3992
		case 'siteurl_malformed' :
3993
		case 'gmt_offset_malformed' :
3994
		case 'timezone_string_malformed' :
3995
		case 'site_name_malformed' :
3996
		case 'secret_1_malformed' :
3997
		case 'secret_2_malformed' :
3998
		case 'site_lang_malformed' :
3999
		case 'secrets_mismatch' :
4000
		case 'verify_secret_1_missing' :
4001
		case 'verify_secret_1_malformed' :
4002
		case 'verify_secrets_missing' :
4003
		case 'verify_secrets_mismatch' :
4004
			$error = esc_html( $error );
4005
			$this->error = sprintf( __( '<strong>Your Jetpack has a glitch.</strong>  We&#8217;re sorry for the inconvenience. Please try again later, if the issue continues please contact support with this message: %s', 'jetpack' ), "<code>$error</code>" );
4006
			if ( ! Jetpack::is_active() ) {
4007
				$this->error .= '<br />';
4008
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
4009
			}
4010
			break;
4011
		}
4012
4013
		$message_code = Jetpack::state( 'message' );
4014
4015
		$active_state = Jetpack::state( 'activated_modules' );
4016
		if ( ! empty( $active_state ) ) {
4017
			$available    = Jetpack::get_available_modules();
4018
			$active_state = explode( ',', $active_state );
4019
			$active_state = array_intersect( $active_state, $available );
4020
			if ( count( $active_state ) ) {
4021
				foreach ( $active_state as $mod ) {
4022
					$this->stat( 'module-activated', $mod );
4023
				}
4024
			} else {
4025
				$active_state = false;
4026
			}
4027
		}
4028
		if( Jetpack::state( 'optin-manage' ) ) {
4029
			$activated_manage = $message_code;
4030
			$message_code = 'jetpack-manage';
4031
4032
		}
4033
		switch ( $message_code ) {
4034
		case 'modules_activated' :
4035
			$this->message = sprintf(
4036
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
4037
				JETPACK__VERSION
4038
			);
4039
4040
			if ( $active_state ) {
4041
				$titles = array();
4042 View Code Duplication
				foreach ( $active_state as $mod ) {
4043
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4044
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4045
					}
4046
				}
4047
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
4048
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
4049
				}
4050
			}
4051
4052
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
4053
				$titles = array();
4054 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4055
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4056
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4057
					}
4058
				}
4059
				if ( $titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

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