Completed
Push — add/sync-action ( 45ef1e...ba7a9e )
by
unknown
65:55 queued 56:50
created

class.jetpack.php (10 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'tiled-gallery',
46
		'widget-conditions',
47
		'jetpack_display_posts_widget',
48
		'gravatar-profile-widget',
49
		'widget-grid-and-list',
50
		'jetpack-widgets',
51
		'goodreads-widget',
52
		'jetpack_social_media_icons_widget',
53
	);
54
55
	public $plugins_to_deactivate = array(
56
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
57
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
63
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
64
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
65
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
66
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
67
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
68
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
69
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
70
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
71
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
72
	);
73
74
	public $capability_translations = array(
75
		'administrator' => 'manage_options',
76
		'editor'        => 'edit_others_posts',
77
		'author'        => 'publish_posts',
78
		'contributor'   => 'edit_posts',
79
		'subscriber'    => 'read',
80
	);
81
82
	/**
83
	 * Map of modules that have conflicts with plugins and should not be auto-activated
84
	 * if the plugins are active.  Used by filter_default_modules
85
	 *
86
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
87
	 * change `module-slug` and add this to your plugin:
88
	 *
89
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
90
	 * function my_jetpack_get_default_modules( $modules ) {
91
	 *     return array_diff( $modules, array( 'module-slug' ) );
92
	 * }
93
	 *
94
	 * @var array
95
	 */
96
	private $conflicting_plugins = array(
97
		'comments'          => array(
98
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
99
			'Disqus'                               => 'disqus-comment-system/disqus.php',
100
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
101
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
102
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
103
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
104
		),
105
		'contact-form'      => array(
106
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
107
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
108
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
109
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
110
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
111
		),
112
		'minileven'         => array(
113
			'WPtouch'                              => 'wptouch/wptouch.php',
114
		),
115
		'latex'             => array(
116
			'LaTeX for WordPress'                  => 'latex/latex.php',
117
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
118
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
119
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
120
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
121
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
122
		),
123
		'protect'           => array(
124
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
125
			'Captcha'                              => 'captcha/captcha.php',
126
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
127
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
128
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
129
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
130
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
131
			'Security-protection'                  => 'security-protection/security-protection.php',
132
			'Login Security'                       => 'login-security/login-security.php',
133
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
134
			'Wordfence Security'                   => 'wordfence/wordfence.php',
135
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
136
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
137
		),
138
		'random-redirect'   => array(
139
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
140
		),
141
		'related-posts'     => array(
142
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
143
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
144
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
145
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
146
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
147
			'outbrain'                             => 'outbrain/outbrain.php',
148
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
149
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
150
		),
151
		'sharedaddy'        => array(
152
			'AddThis'                              => 'addthis/addthis_social_widget.php',
153
			'Add To Any'                           => 'add-to-any/add-to-any.php',
154
			'ShareThis'                            => 'share-this/sharethis.php',
155
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
156
		),
157
		'verification-tools' => array(
158
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
159
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
160
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
161
		),
162
		'widget-visibility' => array(
163
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
164
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
165
		),
166
		'sitemaps' => array(
167
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
168
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
169
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
170
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
171
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
172
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
173
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
174
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
175
			'Sitemap'                              => 'sitemap/sitemap.php',
176
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
177
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
178
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
179
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
180
		),
181
	);
182
183
	/**
184
	 * Plugins for which we turn off our Facebook OG Tags implementation.
185
	 *
186
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
187
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
188
	 *
189
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
190
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
191
	 */
192
	private $open_graph_conflicting_plugins = array(
193
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
194
		                                                         // 2 Click Social Media Buttons
195
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
196
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
197
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
198
		'facebook/facebook.php',                                 // Facebook (official plugin)
199
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
200
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
201
		                                                         // Facebook Featured Image & OG Meta Tags
202
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
203
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
204
		                                                         // Facebook Open Graph Meta Tags for WordPress
205
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
206
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
207
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
208
		                                                         // Fedmich's Facebook Open Graph Meta
209
		'header-footer/plugin.php',                              // Header and Footer
210
		'network-publisher/networkpub.php',                      // Network Publisher
211
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
212
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
213
		                                                         // NextScripts SNAP
214
		'opengraph/opengraph.php',                               // Open Graph
215
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
216
		                                                         // Open Graph Protocol Framework
217
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
218
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
219
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
220
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
221
		'sharepress/sharepress.php',                             // SharePress
222
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
223
		'social-discussions/social-discussions.php',             // Social Discussions
224
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
225
		'socialize/socialize.php',                               // Socialize
226
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
227
		                                                         // Tweet, Like, Google +1 and Share
228
		'wordbooker/wordbooker.php',                             // Wordbooker
229
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
230
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
231
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
232
		                                                         // WP Facebook Like Send & Open Graph Meta
233
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
234
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
235
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
236
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
237
	);
238
239
	/**
240
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
241
	 */
242
	private $twitter_cards_conflicting_plugins = array(
243
	//	'twitter/twitter.php',                       // The official one handles this on its own.
244
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
245
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
246
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
247
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
248
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
249
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
250
		'twitter-cards/twitter-cards.php',           // Twitter Cards
251
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
252
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
253
	);
254
255
	/**
256
	 * Message to display in admin_notice
257
	 * @var string
258
	 */
259
	public $message = '';
260
261
	/**
262
	 * Error to display in admin_notice
263
	 * @var string
264
	 */
265
	public $error = '';
266
267
	/**
268
	 * Modules that need more privacy description.
269
	 * @var string
270
	 */
271
	public $privacy_checks = '';
272
273
	/**
274
	 * Stats to record once the page loads
275
	 *
276
	 * @var array
277
	 */
278
	public $stats = array();
279
280
	/**
281
	 * Allows us to build a temporary security report
282
	 *
283
	 * @var array
284
	 */
285
	static $security_report = array();
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	static $instance = false;
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			self::$instance = new Jetpack;
311
312
			self::$instance->plugin_upgrade();
313
314
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
315
316
		}
317
318
		return self::$instance;
319
	}
320
321
	/**
322
	 * Must never be called statically
323
	 */
324
	function plugin_upgrade() {
325
		if ( Jetpack::is_active() ) {
326
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
327
			if ( JETPACK__VERSION != $version ) {
328
329
				// Check which active modules actually exist and remove others from active_modules list
330
				$unfiltered_modules = Jetpack::get_active_modules();
331
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
332
				if ( array_diff( $unfiltered_modules, $modules ) ) {
333
					Jetpack_Options::update_option( 'active_modules', $modules );
334
				}
335
336
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
337
				/**
338
				 * Fires when synchronizing all registered options and constants.
339
				 *
340
				 * @since 3.3.0
341
				 */
342
				do_action( 'jetpack_sync_all_registered_options' );
343
			}
344
		}
345
	}
346
347
	static function activate_manage( ) {
348
349
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
350
			self::activate_module( 'manage', false, false );
351
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
352
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
353
		}
354
355
	}
356
357
	/**
358
	 * Constructor.  Initializes WordPress hooks
359
	 */
360
	private function __construct() {
361
		/*
362
		 * Check for and alert any deprecated hooks
363
		 */
364
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
365
366
		/**
367
		 * Trigger a wp_version sync when updating WP versions
368
		 **/
369
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
370
371
		/*
372
		 * Load things that should only be in Network Admin.
373
		 *
374
		 * For now blow away everything else until a more full
375
		 * understanding of what is needed at the network level is
376
		 * available
377
		 */
378
		if( is_multisite() ) {
379
			Jetpack_Network::init();
380
		}
381
382
		// Unlink user before deleting the user from .com
383
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
384
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
385
386
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
387
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
388
389
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
390
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
391
392
			$this->require_jetpack_authentication();
393
394
			if ( Jetpack::is_active() ) {
395
				// Hack to preserve $HTTP_RAW_POST_DATA
396
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
397
398
				$signed = $this->verify_xml_rpc_signature();
399
				if ( $signed && ! is_wp_error( $signed ) ) {
400
					// The actual API methods.
401
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
402
				} else {
403
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
404
					// active Jetpack connection, so that additional users can link their account.
405
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
406
				}
407
			} else {
408
				// The bootstrap API methods.
409
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
410
			}
411
412
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
413
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
414
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
415
			$this->require_jetpack_authentication();
416
			$this->add_remote_request_handlers();
417
		} else {
418
			if ( Jetpack::is_active() ) {
419
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
420
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
421
			}
422
		}
423
424
		if ( Jetpack::is_active() ) {
425
			Jetpack_Heartbeat::init();
426
		}
427
428
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
429
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
430
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
431
		}
432
433
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
434
435
		add_action( 'admin_init', array( $this, 'admin_init' ) );
436
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
437
438
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
439
440
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
441
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
442
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
443
444
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
445
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
446
447
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
448
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
449
450
		// Identity Crisis AJAX callback function
451
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
452
453
		// JITM AJAX callback function
454
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
455
456
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
457
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
458
459
		// Universal ajax callback for all tracking events triggered via js
460
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
461
462
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
463
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
464
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
465
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
466
467
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
468
469
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
470
471
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
472
473
		/**
474
		 * These actions run checks to load additional files.
475
		 * They check for external files or plugins, so they need to run as late as possible.
476
		 */
477
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
478
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
479
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
480
481
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
482
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
483
484
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
485
486
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
487
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
488
489
		// A filter to control all just in time messages
490
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
491
492
		/**
493
		 * This is the hack to concatinate all css files into one.
494
		 * For description and reasoning see the implode_frontend_css method
495
		 *
496
		 * Super late priority so we catch all the registered styles
497
		 */
498
		if( !is_admin() ) {
499
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
500
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
501
		}
502
503
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
504
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
505
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
506
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
507
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
508
509
	}
510
511
	/*
512
	 * Make sure any site icon added to core can get
513
	 * synced back to dotcom, so we can display it there.
514
	 */
515 View Code Duplication
	function jetpack_sync_core_icon() {
516
		if ( function_exists( 'get_site_icon_url' ) ) {
517
			$url = get_site_icon_url();
518
		} else {
519
			return;
520
		}
521
522
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
523
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
524
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
525
			// This is the option that is synced with dotcom
526
			Jetpack_Options::update_option( 'site_icon_url', $url );
527
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
528
			Jetpack_Options::delete_option( 'site_icon_url' );
529
		}
530
	}
531
532
	function jetpack_admin_ajax_tracks_callback() {
533
		// Check for nonce
534
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
535
			wp_die( 'Permissions check failed.' );
536
		}
537
538
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
539
			wp_die( 'No valid event name or type.' );
540
		}
541
542
		$tracks_data = array();
543
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
544
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
545
		}
546
547
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
548
		wp_send_json_success();
549
		wp_die();
550
	}
551
552
	function jetpack_admin_ajax_callback() {
553
		// Check for nonce
554 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
555
			wp_die( 'permissions check failed' );
556
		}
557
558
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
559
			$slug = $_REQUEST['thisModuleSlug'];
560
561
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
562
				wp_die( 'That is not a Jetpack module slug' );
563
			}
564
565
			if ( Jetpack::is_module_active( $slug ) ) {
566
				Jetpack::deactivate_module( $slug );
567
			} else {
568
				Jetpack::activate_module( $slug, false, false );
569
			}
570
571
			$modules = Jetpack_Admin::init()->get_modules();
572
			echo json_encode( $modules[ $slug ] );
573
574
			exit;
575
		}
576
577
		wp_die();
578
	}
579
580
	/*
581
	 * Sometimes we need to refresh the data,
582
	 * especially if the page is visited via a 'history'
583
	 * event like back/forward
584
	 */
585
	function jetpack_admin_ajax_refresh_data() {
586
		// Check for nonce
587 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
588
			wp_die( 'permissions check failed' );
589
		}
590
591
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
592
			$modules = Jetpack_Admin::init()->get_modules();
593
			echo json_encode( $modules );
594
			exit;
595
		}
596
597
		wp_die();
598
	}
599
600
	/**
601
	 * The callback for the JITM ajax requests.
602
	 */
603
	function jetpack_jitm_ajax_callback() {
604
		// Check for nonce
605
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
606
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
607
		}
608
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
609
			$module_slug = $_REQUEST['jitmModule'];
610
			Jetpack::log( 'activate', $module_slug );
611
			Jetpack::activate_module( $module_slug, false, false );
612
			Jetpack::state( 'message', 'no_message' );
613
614
			//A Jetpack module is being activated through a JITM, track it
615
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
616
			$this->do_stats( 'server_side' );
617
618
			wp_send_json_success();
619
		}
620
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
621
			// get the hide_jitm options array
622
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
623
			$module_slug = $_REQUEST['jitmModule'];
624
625
			if( ! $jetpack_hide_jitm ) {
626
				$jetpack_hide_jitm = array(
627
					$module_slug => 'hide'
628
				);
629
			} else {
630
				$jetpack_hide_jitm[$module_slug] = 'hide';
631
			}
632
633
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
634
635
			//jitm is being dismissed forever, track it
636
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
637
			$this->do_stats( 'server_side' );
638
639
			wp_send_json_success();
640
		}
641 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
642
			$module_slug = $_REQUEST['jitmModule'];
643
644
			// User went to WordPress.com, track this
645
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
646
			$this->do_stats( 'server_side' );
647
648
			wp_send_json_success();
649
		}
650 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
651
			$track = $_REQUEST['jitmModule'];
652
653
			// User is viewing JITM, track it.
654
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
655
			$this->do_stats( 'server_side' );
656
657
			wp_send_json_success();
658
		}
659
	}
660
661
	/**
662
	 * If there are any stats that need to be pushed, but haven't been, push them now.
663
	 */
664
	function __destruct() {
665
		if ( ! empty( $this->stats ) ) {
666
			$this->do_stats( 'server_side' );
667
		}
668
	}
669
670
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
671
		switch( $cap ) {
672
			case 'jetpack_connect' :
673
			case 'jetpack_reconnect' :
674
				if ( Jetpack::is_development_mode() ) {
675
					$caps = array( 'do_not_allow' );
676
					break;
677
				}
678
				/**
679
				 * Pass through. If it's not development mode, these should match disconnect.
680
				 * Let users disconnect if it's development mode, just in case things glitch.
681
				 */
682
			case 'jetpack_disconnect' :
683
				/**
684
				 * In multisite, can individual site admins manage their own connection?
685
				 *
686
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
687
				 */
688
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
689
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
690
						/**
691
						 * We need to update the option name -- it's terribly unclear which
692
						 * direction the override goes.
693
						 *
694
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
695
						 */
696
						$caps = array( 'do_not_allow' );
697
						break;
698
					}
699
				}
700
701
				$caps = array( 'manage_options' );
702
				break;
703
			case 'jetpack_manage_modules' :
704
			case 'jetpack_activate_modules' :
705
			case 'jetpack_deactivate_modules' :
706
				$caps = array( 'manage_options' );
707
				break;
708
			case 'jetpack_configure_modules' :
709
				$caps = array( 'manage_options' );
710
				break;
711
			case 'jetpack_network_admin_page':
712
			case 'jetpack_network_settings_page':
713
				$caps = array( 'manage_network_plugins' );
714
				break;
715
			case 'jetpack_network_sites_page':
716
				$caps = array( 'manage_sites' );
717
				break;
718
			case 'jetpack_admin_page' :
719
				if ( Jetpack::is_development_mode() ) {
720
					$caps = array( 'manage_options' );
721
					break;
722
				}
723
724
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
725
				if ( ! current_user_can( 'edit_posts' ) ) {
726
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
727
						// We need this in order to unlink the user.
728
						$this->admin_page_load();
729
					}
730
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
731
						$caps = array( 'do_not_allow' );
732
						break;
733
					}
734
				}
735
736
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
737
					$caps = array( 'do_not_allow' );
738
					break;
739
				}
740
				/**
741
				 * Pass through. If it's not development mode, these should match the admin page.
742
				 * Let users disconnect if it's development mode, just in case things glitch.
743
				 */
744
			case 'jetpack_connect_user' :
745
				if ( Jetpack::is_development_mode() ) {
746
					$caps = array( 'do_not_allow' );
747
					break;
748
				}
749
				$caps = array( 'read' );
750
				break;
751
		}
752
		return $caps;
753
	}
754
755
	function require_jetpack_authentication() {
756
		// Don't let anyone authenticate
757
		$_COOKIE = array();
758
		remove_all_filters( 'authenticate' );
759
760
		/**
761
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
762
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
763
		 * generate false-positives.
764
		 */
765
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
766
767
		if ( Jetpack::is_active() ) {
768
			// Allow Jetpack authentication
769
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
770
		}
771
	}
772
773
	/**
774
	 * Load language files
775
	 * @action plugins_loaded
776
	 */
777
	public static function plugin_textdomain() {
778
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
779
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
780
	}
781
782
	/**
783
	 * Register assets for use in various modules and the Jetpack admin page.
784
	 *
785
	 * @uses wp_script_is, wp_register_script, plugins_url
786
	 * @action wp_loaded
787
	 * @return null
788
	 */
789
	public function register_assets() {
790
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
791
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
792
		}
793
794 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
795
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
796
		}
797
798 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
799
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
800
		}
801
802 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
803
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
804
		}
805
806
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
807
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
808
809
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
810
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
811
			if ( ! is_numeric( $fb_app_id ) ) {
812
				$fb_app_id = '';
813
			}
814
			wp_localize_script(
815
				'jetpack-facebook-embed',
816
				'jpfbembed',
817
				array(
818
					'appid' => $fb_app_id,
819
					'locale' => $this->get_locale(),
820
				)
821
			);
822
		}
823
824
		/**
825
		 * As jetpack_register_genericons is by default fired off a hook,
826
		 * the hook may have already fired by this point.
827
		 * So, let's just trigger it manually.
828
		 */
829
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
830
		jetpack_register_genericons();
831
832 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
833
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
834
	}
835
836
	/**
837
	 * Guess locale from language code.
838
	 *
839
	 * @param string $lang Language code.
840
	 * @return string|bool
841
	 */
842 View Code Duplication
	function guess_locale_from_lang( $lang ) {
843
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
844
			return 'en_US';
845
		}
846
847
		if ( ! class_exists( 'GP_Locales' ) ) {
848
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
849
				return false;
850
			}
851
852
			require JETPACK__GLOTPRESS_LOCALES_PATH;
853
		}
854
855
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
856
			// WP.com: get_locale() returns 'it'
857
			$locale = GP_Locales::by_slug( $lang );
858
		} else {
859
			// Jetpack: get_locale() returns 'it_IT';
860
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
861
		}
862
863
		if ( ! $locale ) {
864
			return false;
865
		}
866
867
		if ( empty( $locale->facebook_locale ) ) {
868
			if ( empty( $locale->wp_locale ) ) {
869
				return false;
870
			} else {
871
				// Facebook SDK is smart enough to fall back to en_US if a
872
				// locale isn't supported. Since supported Facebook locales
873
				// can fall out of sync, we'll attempt to use the known
874
				// wp_locale value and rely on said fallback.
875
				return $locale->wp_locale;
876
			}
877
		}
878
879
		return $locale->facebook_locale;
880
	}
881
882
	/**
883
	 * Get the locale.
884
	 *
885
	 * @return string|bool
886
	 */
887
	function get_locale() {
888
		$locale = $this->guess_locale_from_lang( get_locale() );
889
890
		if ( ! $locale ) {
891
			$locale = 'en_US';
892
		}
893
894
		return $locale;
895
	}
896
897
	/**
898
	 * Device Pixels support
899
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
900
	 */
901
	function devicepx() {
902
		if ( Jetpack::is_active() ) {
903
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
904
		}
905
	}
906
907
	/**
908
	 * Return the network_site_url so that .com knows what network this site is a part of.
909
	 * @param  bool $option
910
	 * @return string
911
	 */
912
	public function jetpack_main_network_site_option( $option ) {
913
		return network_site_url();
914
	}
915
	/**
916
	 * Network Name.
917
	 */
918
	static function network_name( $option = null ) {
919
		global $current_site;
920
		return $current_site->site_name;
921
	}
922
	/**
923
	 * Does the network allow new user and site registrations.
924
	 * @return string
925
	 */
926
	static function network_allow_new_registrations( $option = null ) {
927
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
928
	}
929
	/**
930
	 * Does the network allow admins to add new users.
931
	 * @return boolian
932
	 */
933
	static function network_add_new_users( $option = null ) {
934
		return (bool) get_site_option( 'add_new_users' );
935
	}
936
	/**
937
	 * File upload psace left per site in MB.
938
	 *  -1 means NO LIMIT.
939
	 * @return number
940
	 */
941
	static function network_site_upload_space( $option = null ) {
942
		// value in MB
943
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
944
	}
945
946
	/**
947
	 * Network allowed file types.
948
	 * @return string
949
	 */
950
	static function network_upload_file_types( $option = null ) {
951
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
952
	}
953
954
	/**
955
	 * Maximum file upload size set by the network.
956
	 * @return number
957
	 */
958
	static function network_max_upload_file_size( $option = null ) {
959
		// value in KB
960
		return get_site_option( 'fileupload_maxk', 300 );
961
	}
962
963
	/**
964
	 * Lets us know if a site allows admins to manage the network.
965
	 * @return array
966
	 */
967
	static function network_enable_administration_menus( $option = null ) {
968
		return get_site_option( 'menu_items' );
969
	}
970
971
	/**
972
	 * Return whether we are dealing with a multi network setup or not.
973
	 * The reason we are type casting this is because we want to avoid the situation where
974
	 * the result is false since when is_main_network_option return false it cases
975
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
976
	 * database which could be set to anything as opposed to what this function returns.
977
	 * @param  bool  $option
978
	 *
979
	 * @return boolean
980
	 */
981
	public function is_main_network_option( $option ) {
982
		// return '1' or ''
983
		return (string) (bool) Jetpack::is_multi_network();
984
	}
985
986
	/**
987
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
988
	 *
989
	 * @param  string  $option
990
	 * @return boolean
991
	 */
992
	public function is_multisite( $option ) {
993
		return (string) (bool) is_multisite();
994
	}
995
996
	/**
997
	 * Implemented since there is no core is multi network function
998
	 * Right now there is no way to tell if we which network is the dominant network on the system
999
	 *
1000
	 * @since  3.3
1001
	 * @return boolean
1002
	 */
1003
	public static function is_multi_network() {
1004
		global  $wpdb;
1005
1006
		// if we don't have a multi site setup no need to do any more
1007
		if ( ! is_multisite() ) {
1008
			return false;
1009
		}
1010
1011
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1012
		if ( $num_sites > 1 ) {
1013
			return true;
1014
		} else {
1015
			return false;
1016
		}
1017
	}
1018
1019
	/**
1020
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1021
	 * @return null
1022
	 */
1023
	function update_jetpack_main_network_site_option() {
1024
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1025
		/**
1026
		 * Fires when the site URL is updated.
1027
		 * Determines if the site is the main site of a Mulitiste network.
1028
		 *
1029
		 * @since 3.3.0
1030
		 *
1031
		 * @param string jetpack_main_network_site.
1032
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1033
		 */
1034
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1035
		/**
1036
		 * Fires when the site URL is updated.
1037
		 * Determines if the is part of a multi network.
1038
		 *
1039
		 * @since 3.3.0
1040
		 *
1041
		 * @param string jetpack_is_main_network.
1042
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1043
		 */
1044
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1045
		/**
1046
		 * Fires when the site URL is updated.
1047
		 * Determines if the site is part of a multisite network.
1048
		 *
1049
		 * @since 3.4.0
1050
		 *
1051
		 * @param string jetpack_is_multi_site.
1052
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1053
		 */
1054
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1055
	}
1056
	/**
1057
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1058
	 *
1059
	 */
1060
	function update_jetpack_network_settings() {
1061
		// Only sync this info for the main network site.
1062
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1063
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1064
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1065
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1066
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1067
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1068
1069
	}
1070
1071
	/**
1072
	 * Get back if the current site is single user site.
1073
	 *
1074
	 * @return bool
1075
	 */
1076
	public static function is_single_user_site() {
1077
1078
		$user_query = new WP_User_Query( array(
1079
			'blog_id' => get_current_blog_id(),
1080
			'fields'  => 'ID',
1081
			'number' => 2
1082
		) );
1083
		return 1 === (int) $user_query->get_total();
1084
	}
1085
1086
	/**
1087
	 * Returns true if the site has file write access false otherwise.
1088
	 * @return string ( '1' | '0' )
1089
	 **/
1090 View Code Duplication
	public static function file_system_write_access() {
1091
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1092
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1093
		}
1094
1095
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1096
1097
		$filesystem_method = get_filesystem_method();
1098
		if ( $filesystem_method === 'direct' ) {
1099
			return 1;
1100
		}
1101
1102
		ob_start();
1103
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1104
		ob_end_clean();
1105
		if ( $filesystem_credentials_are_stored ) {
1106
			return 1;
1107
		}
1108
		return 0;
1109
	}
1110
1111
	/**
1112
	 * Finds out if a site is using a version control system.
1113
	 * @return string ( '1' | '0' )
1114
	 **/
1115 View Code Duplication
	public static function is_version_controlled() {
1116
1117
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1118
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1119
		}
1120
		$updater = new WP_Automatic_Updater();
1121
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1122
		// transients should not be empty
1123
		if ( empty( $is_version_controlled ) ) {
1124
			$is_version_controlled = '0';
1125
		}
1126
		return $is_version_controlled;
1127
	}
1128
1129
	/**
1130
	 * Determines whether the current theme supports featured images or not.
1131
	 * @return string ( '1' | '0' )
1132
	 */
1133
	public static function featured_images_enabled() {
1134
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1135
	}
1136
1137
	/*
1138
	 * Sync back wp_version
1139
	 */
1140
	public static function get_wp_version() {
1141
		global $wp_version;
1142
		return $wp_version;
1143
	}
1144
1145
	/**
1146
	 * Keeps wp_version in sync with .com when WordPress core updates
1147
	 **/
1148
	public static function update_get_wp_version( $update, $meta_data ) {
1149
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1150
			/** This action is documented in wp-includes/option.php */
1151
			/**
1152
			 * This triggers the sync for the jetpack version
1153
			 * See Jetpack_Sync options method for more info.
1154
			 */
1155
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1156
		}
1157
	}
1158
1159
	/**
1160
	 * jetpack_updates is saved in the following schema:
1161
	 *
1162
	 * array (
1163
	 *      'plugins'                       => (int) Number of plugin updates available.
1164
	 *      'themes'                        => (int) Number of theme updates available.
1165
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1166
	 *      'translations'                  => (int) Number of translation updates available.
1167
	 *      'total'                         => (int) Total of all available updates.
1168
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1169
	 * )
1170
	 * @return array
1171
	 */
1172
	public static function get_updates() {
1173
		$update_data = wp_get_update_data();
1174
1175
		// Stores the individual update counts as well as the total count.
1176
		if ( isset( $update_data['counts'] ) ) {
1177
			$updates = $update_data['counts'];
1178
		}
1179
1180
		// If we need to update WordPress core, let's find the latest version number.
1181 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1182
			$cur = get_preferred_from_update_core();
1183
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1184
				$updates['wp_update_version'] = $cur->current;
1185
			}
1186
		}
1187
		return isset( $updates ) ? $updates : array();
1188
	}
1189
1190
	public static function get_update_details() {
1191
		$update_details = array(
1192
			'update_core' => get_site_transient( 'update_core' ),
1193
			'update_plugins' => get_site_transient( 'update_plugins' ),
1194
			'update_themes' => get_site_transient( 'update_themes' ),
1195
		);
1196
		return $update_details;
1197
	}
1198
1199
	public static function refresh_update_data() {
1200
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1201
			/**
1202
			 * Fires whenever the amount of updates needed for a site changes.
1203
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1204
			 *
1205
			 * @since 3.7.0
1206
			 *
1207
			 * @param string jetpack_updates
1208
			 * @param array Update counts calculated by Jetpack::get_updates
1209
			 */
1210
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1211
		}
1212
		/**
1213
		 * Fires whenever the amount of updates needed for a site changes.
1214
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1215
		 *
1216
		 * @since 3.7.0
1217
		 *
1218
		 * @param string jetpack_update_details
1219
		 * @param array Update details calculated by Jetpack::get_update_details
1220
		 */
1221
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1222
	}
1223
1224
	public static function refresh_theme_data() {
1225
		/**
1226
		 * Fires whenever a theme change is made.
1227
		 *
1228
		 * @since 3.8.1
1229
		 *
1230
		 * @param string featured_images_enabled
1231
		 * @param boolean Whether featured images are enabled or not
1232
		 */
1233
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1234
	}
1235
1236
	/**
1237
	 * Is Jetpack active?
1238
	 */
1239
	public static function is_active() {
1240
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1241
	}
1242
1243
	/**
1244
	 * Is Jetpack in development (offline) mode?
1245
	 */
1246
	public static function is_development_mode() {
1247
		$development_mode = false;
1248
1249
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1250
			$development_mode = JETPACK_DEV_DEBUG;
1251
		}
1252
1253
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1254
			$development_mode = true;
1255
		}
1256
		/**
1257
		 * Filters Jetpack's development mode.
1258
		 *
1259
		 * @see http://jetpack.com/support/development-mode/
1260
		 *
1261
		 * @since 2.2.1
1262
		 *
1263
		 * @param bool $development_mode Is Jetpack's development mode active.
1264
		 */
1265
		return apply_filters( 'jetpack_development_mode', $development_mode );
1266
	}
1267
1268
	/**
1269
	* Get Jetpack development mode notice text and notice class.
1270
	*
1271
	* Mirrors the checks made in Jetpack::is_development_mode
1272
	*
1273
	*/
1274
	public static function show_development_mode_notice() {
1275
		if ( Jetpack::is_development_mode() ) {
1276
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1277
				$notice = sprintf(
1278
					/* translators: %s is a URL */
1279
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1280
					'http://jetpack.com/support/development-mode/'
1281
				);
1282
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1283
				$notice = sprintf(
1284
					/* translators: %s is a URL */
1285
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1286
					'http://jetpack.com/support/development-mode/'
1287
				);
1288
			} else {
1289
				$notice = sprintf(
1290
					/* translators: %s is a URL */
1291
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1292
					'http://jetpack.com/support/development-mode/'
1293
				);
1294
			}
1295
1296
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1297
		}
1298
1299
		// Throw up a notice if using a development version and as for feedback.
1300
		if ( Jetpack::is_development_version() ) {
1301
			/* translators: %s is a URL */
1302
			$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/' );
1303
1304
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1305
		}
1306
		// Throw up a notice if using staging mode
1307
		if ( Jetpack::is_staging_site() ) {
1308
			/* translators: %s is a URL */
1309
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1310
1311
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1312
		}
1313
	}
1314
1315
	/**
1316
	 * Whether Jetpack's version maps to a public release, or a development version.
1317
	 */
1318
	public static function is_development_version() {
1319
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1320
	}
1321
1322
	/**
1323
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1324
	 */
1325
	public static function is_user_connected( $user_id = false ) {
1326
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1327
		if ( ! $user_id ) {
1328
			return false;
1329
		}
1330
		return (bool) Jetpack_Data::get_access_token( $user_id );
1331
	}
1332
1333
	/**
1334
	 * Get the wpcom user data of the current|specified connected user.
1335
	 */
1336 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1337
		if ( ! $user_id ) {
1338
			$user_id = get_current_user_id();
1339
		}
1340
		Jetpack::load_xml_rpc_client();
1341
		$xml = new Jetpack_IXR_Client( array(
1342
			'user_id' => $user_id,
1343
		) );
1344
		$xml->query( 'wpcom.getUser' );
1345
		if ( ! $xml->isError() ) {
1346
			return $xml->getResponse();
1347
		}
1348
		return false;
1349
	}
1350
1351
	/**
1352
	 * Get the wpcom email of the current|specified connected user.
1353
	 */
1354 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1355
		if ( ! $user_id ) {
1356
			$user_id = get_current_user_id();
1357
		}
1358
		Jetpack::load_xml_rpc_client();
1359
		$xml = new Jetpack_IXR_Client( array(
1360
			'user_id' => $user_id,
1361
		) );
1362
		$xml->query( 'wpcom.getUserEmail' );
1363
		if ( ! $xml->isError() ) {
1364
			return $xml->getResponse();
1365
		}
1366
		return false;
1367
	}
1368
1369
	/**
1370
	 * Get the wpcom email of the master user.
1371
	 */
1372
	public static function get_master_user_email() {
1373
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1374
		if ( $master_user_id ) {
1375
			return self::get_connected_user_email( $master_user_id );
1376
		}
1377
		return '';
1378
	}
1379
1380
	function current_user_is_connection_owner() {
1381
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1382
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1383
	}
1384
1385
	/**
1386
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1387
	 */
1388
	function extra_oembed_providers() {
1389
		// Cloudup: https://dev.cloudup.com/#oembed
1390
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1391
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1392
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1393
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1394
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1395
	}
1396
1397
	/**
1398
	 * Synchronize connected user role changes
1399
	 */
1400
	function user_role_change( $user_id ) {
1401
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1402
			$current_user_id = get_current_user_id();
1403
			wp_set_current_user( $user_id );
1404
			$role = $this->translate_current_user_to_role();
1405
			$signed_role = $this->sign_role( $role );
1406
			wp_set_current_user( $current_user_id );
1407
1408
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1409
			$master_user_id = absint( $master_token->external_user_id );
1410
1411
			if ( ! $master_user_id )
1412
				return; // this shouldn't happen
1413
1414
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1415
			//@todo retry on failure
1416
1417
			//try to choose a new master if we're demoting the current one
1418 View Code Duplication
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1419
				$query = new WP_User_Query(
1420
					array(
1421
						'fields'  => array( 'id' ),
1422
						'role'    => 'administrator',
1423
						'orderby' => 'id',
1424
						'exclude' => array( $master_user_id ),
1425
					)
1426
				);
1427
				$new_master = false;
1428
				foreach ( $query->results as $result ) {
1429
					$uid = absint( $result->id );
1430
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1431
						$new_master = $uid;
1432
						break;
1433
					}
1434
				}
1435
1436
				if ( $new_master ) {
1437
					Jetpack_Options::update_option( 'master_user', $new_master );
1438
				}
1439
				// else disconnect..?
1440
			}
1441
		}
1442
	}
1443
1444
	/**
1445
	 * Loads the currently active modules.
1446
	 */
1447
	public static function load_modules() {
1448
		if ( ! self::is_active() && !self::is_development_mode() ) {
1449
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1450
				return;
1451
			}
1452
		}
1453
1454
		$version = Jetpack_Options::get_option( 'version' );
1455 View Code Duplication
		if ( ! $version ) {
1456
			$version = $old_version = JETPACK__VERSION . ':' . time();
1457
			/** This action is documented in class.jetpack.php */
1458
			do_action( 'updating_jetpack_version', $version, false );
1459
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1460
		}
1461
		list( $version ) = explode( ':', $version );
1462
1463
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1464
1465
		$modules_data = array();
1466
1467
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1468
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1469
			$updated_modules = array();
1470
			foreach ( $modules as $module ) {
1471
				$modules_data[ $module ] = Jetpack::get_module( $module );
1472
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1473
					continue;
1474
				}
1475
1476
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1477
					continue;
1478
				}
1479
1480
				$updated_modules[] = $module;
1481
			}
1482
1483
			$modules = array_diff( $modules, $updated_modules );
1484
		}
1485
1486
		$is_development_mode = Jetpack::is_development_mode();
1487
1488
		foreach ( $modules as $index => $module ) {
1489
			// If we're in dev mode, disable modules requiring a connection
1490
			if ( $is_development_mode ) {
1491
				// Prime the pump if we need to
1492
				if ( empty( $modules_data[ $module ] ) ) {
1493
					$modules_data[ $module ] = Jetpack::get_module( $module );
1494
				}
1495
				// If the module requires a connection, but we're in local mode, don't include it.
1496
				if ( $modules_data[ $module ]['requires_connection'] ) {
1497
					continue;
1498
				}
1499
			}
1500
1501
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1502
				continue;
1503
			}
1504
1505
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1506
				unset( $modules[ $index ] );
1507
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1508
				continue;
1509
			}
1510
1511
			/**
1512
			 * Fires when a specific module is loaded.
1513
			 * The dynamic part of the hook, $module, is the module slug.
1514
			 *
1515
			 * @since 1.1.0
1516
			 */
1517
			do_action( 'jetpack_module_loaded_' . $module );
1518
		}
1519
1520
		/**
1521
		 * Fires when all the modules are loaded.
1522
		 *
1523
		 * @since 1.1.0
1524
		 */
1525
		do_action( 'jetpack_modules_loaded' );
1526
1527
		// 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.
1528
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1529
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1530
	}
1531
1532
	/**
1533
	 * Check if Jetpack's REST API compat file should be included
1534
	 * @action plugins_loaded
1535
	 * @return null
1536
	 */
1537
	public function check_rest_api_compat() {
1538
		/**
1539
		 * Filters the list of REST API compat files to be included.
1540
		 *
1541
		 * @since 2.2.5
1542
		 *
1543
		 * @param array $args Array of REST API compat files to include.
1544
		 */
1545
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1546
1547
		if ( function_exists( 'bbpress' ) )
1548
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1549
1550
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1551
			require_once $_jetpack_rest_api_compat_include;
1552
	}
1553
1554
	/**
1555
	 * Gets all plugins currently active in values, regardless of whether they're
1556
	 * traditionally activated or network activated.
1557
	 *
1558
	 * @todo Store the result in core's object cache maybe?
1559
	 */
1560
	public static function get_active_plugins() {
1561
		$active_plugins = (array) get_option( 'active_plugins', array() );
1562
1563
		if ( is_multisite() ) {
1564
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1565
			// whereas active_plugins stores them in the values.
1566
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1567
			if ( $network_plugins ) {
1568
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1569
			}
1570
		}
1571
1572
		sort( $active_plugins );
1573
1574
		return array_unique( $active_plugins );
1575
	}
1576
1577
	/**
1578
	 * Gets and parses additional plugin data to send with the heartbeat data
1579
	 *
1580
	 * @since 3.8.1
1581
	 *
1582
	 * @return array Array of plugin data
1583
	 */
1584
	public static function get_parsed_plugin_data() {
1585
		if ( ! function_exists( 'get_plugins' ) ) {
1586
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1587
		}
1588
		$all_plugins    = get_plugins();
1589
		$active_plugins = Jetpack::get_active_plugins();
1590
1591
		$plugins = array();
1592
		foreach ( $all_plugins as $path => $plugin_data ) {
1593
			$plugins[ $path ] = array(
1594
					'is_active' => in_array( $path, $active_plugins ),
1595
					'file'      => $path,
1596
					'name'      => $plugin_data['Name'],
1597
					'version'   => $plugin_data['Version'],
1598
					'author'    => $plugin_data['Author'],
1599
			);
1600
		}
1601
1602
		return $plugins;
1603
	}
1604
1605
	/**
1606
	 * Gets and parses theme data to send with the heartbeat data
1607
	 *
1608
	 * @since 3.8.1
1609
	 *
1610
	 * @return array Array of theme data
1611
	 */
1612
	public static function get_parsed_theme_data() {
1613
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1614
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1615
1616
		$themes = array();
1617
		foreach ( $all_themes as $slug => $theme_data ) {
1618
			$theme_headers = array();
1619
			foreach ( $header_keys as $header_key ) {
1620
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1621
			}
1622
1623
			$themes[ $slug ] = array(
1624
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1625
					'slug' => $slug,
1626
					'theme_root' => $theme_data->get_theme_root_uri(),
1627
					'parent' => $theme_data->parent(),
1628
					'headers' => $theme_headers
1629
			);
1630
		}
1631
1632
		return $themes;
1633
	}
1634
1635
	/**
1636
	 * Checks whether a specific plugin is active.
1637
	 *
1638
	 * We don't want to store these in a static variable, in case
1639
	 * there are switch_to_blog() calls involved.
1640
	 */
1641
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1642
		return in_array( $plugin, self::get_active_plugins() );
1643
	}
1644
1645
	/**
1646
	 * Check if Jetpack's Open Graph tags should be used.
1647
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1648
	 *
1649
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1650
	 * @action plugins_loaded
1651
	 * @return null
1652
	 */
1653
	public function check_open_graph() {
1654
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1655
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1656
		}
1657
1658
		$active_plugins = self::get_active_plugins();
1659
1660
		if ( ! empty( $active_plugins ) ) {
1661
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1662
				if ( in_array( $plugin, $active_plugins ) ) {
1663
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1664
					break;
1665
				}
1666
			}
1667
		}
1668
1669
		/**
1670
		 * Allow the addition of Open Graph Meta Tags to all pages.
1671
		 *
1672
		 * @since 2.0.3
1673
		 *
1674
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1675
		 */
1676
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1677
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1678
		}
1679
	}
1680
1681
	/**
1682
	 * Check if Jetpack's Twitter tags should be used.
1683
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1684
	 *
1685
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1686
	 * @action plugins_loaded
1687
	 * @return null
1688
	 */
1689
	public function check_twitter_tags() {
1690
1691
		$active_plugins = self::get_active_plugins();
1692
1693
		if ( ! empty( $active_plugins ) ) {
1694
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1695
				if ( in_array( $plugin, $active_plugins ) ) {
1696
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1697
					break;
1698
				}
1699
			}
1700
		}
1701
1702
		/**
1703
		 * Allow Twitter Card Meta tags to be disabled.
1704
		 *
1705
		 * @since 2.6.0
1706
		 *
1707
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1708
		 */
1709
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1710
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1711
		}
1712
	}
1713
1714
1715
1716
1717
	/*
1718
	 *
1719
	 * Jetpack Security Reports
1720
	 *
1721
	 * Allowed types: login_form, backup, file_scanning, spam
1722
	 *
1723
	 * 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)
1724
	 *
1725
	 * 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)
1726
	 *
1727
	 *
1728
	 * Example code to submit a security report:
1729
	 *
1730
	 *  function akismet_submit_jetpack_security_report() {
1731
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1732
	 *  }
1733
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1734
	 *
1735
	 */
1736
1737
1738
	/**
1739
	 * Calls for security report submissions.
1740
	 *
1741
	 * @return null
1742
	 */
1743
	public static function perform_security_reporting() {
1744
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1745
1746
		if ( $no_check_needed ) {
1747
			return;
1748
		}
1749
1750
		/**
1751
		 * Fires before a security report is created.
1752
		 *
1753
		 * @since 3.4.0
1754
		 */
1755
		do_action( 'jetpack_security_report' );
1756
1757
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1758
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1759
	}
1760
1761
	/**
1762
	 * Allows plugins to submit security reports.
1763
 	 *
1764
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1765
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1766
	 * @param array   $args         See definitions above
1767
	 */
1768
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1769
1770
		if( !doing_action( 'jetpack_security_report' ) ) {
1771
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1772
		}
1773
1774
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1775
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1776
		}
1777
1778
		if( !function_exists( 'get_plugin_data' ) ) {
1779
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1780
		}
1781
1782
		//Get rid of any non-allowed args
1783
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1784
1785
		$plugin = get_plugin_data( $plugin_file );
1786
1787
		if ( !$plugin['Name'] ) {
1788
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1789
		}
1790
1791
		// Sanitize everything to make sure we're not syncing something wonky
1792
		$type = sanitize_key( $type );
1793
1794
		$args['plugin'] = $plugin;
1795
1796
		// Cast blocked, last and next as integers.
1797
		// Last and next should be in unix timestamp format
1798
		if ( isset( $args['blocked'] ) ) {
1799
			$args['blocked'] = (int) $args['blocked'];
1800
		}
1801
		if ( isset( $args['last'] ) ) {
1802
			$args['last'] = (int) $args['last'];
1803
		}
1804
		if ( isset( $args['next'] ) ) {
1805
			$args['next'] = (int) $args['next'];
1806
		}
1807
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1808
			$args['status'] = 'ok';
1809
		}
1810
		if ( isset( $args['message'] ) ) {
1811
1812
			if( $args['status'] == 'ok' ) {
1813
				unset( $args['message'] );
1814
			}
1815
1816
			$allowed_html = array(
1817
			    'a' => array(
1818
			        'href' => array(),
1819
			        'title' => array()
1820
			    ),
1821
			    'em' => array(),
1822
			    'strong' => array(),
1823
			);
1824
1825
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1826
		}
1827
1828
		$plugin_name = $plugin[ 'Name' ];
1829
1830
		self::$security_report[ $type ][ $plugin_name ] = $args;
1831
	}
1832
1833
	/**
1834
	 * Collects a new report if needed, then returns it.
1835
	 */
1836
	public function get_security_report() {
1837
		self::perform_security_reporting();
1838
		return Jetpack_Options::get_option( 'security_report' );
1839
	}
1840
1841
1842
/* Jetpack Options API */
1843
1844
	public static function get_option_names( $type = 'compact' ) {
1845
		return Jetpack_Options::get_option_names( $type );
1846
	}
1847
1848
	/**
1849
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1850
 	 *
1851
	 * @param string $name    Option name
1852
	 * @param mixed  $default (optional)
1853
	 */
1854
	public static function get_option( $name, $default = false ) {
1855
		return Jetpack_Options::get_option( $name, $default );
1856
	}
1857
1858
	/**
1859
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1860
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1861
	* $name must be a registered option name.
1862
	*/
1863
	public static function create_nonce( $name ) {
1864
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1865
1866
		Jetpack_Options::update_option( $name, $secret );
1867
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1868
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1869
			return new Jetpack_Error( 'missing_secrets' );
1870
1871
		return array(
1872
			'secret_1' => $secret_1,
1873
			'secret_2' => $secret_2,
1874
			'eol'      => $eol,
1875
		);
1876
	}
1877
1878
	/**
1879
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1880
 	 *
1881
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1882
	 * @param string $name  Option name
1883
	 * @param mixed  $value Option value
1884
	 */
1885
	public static function update_option( $name, $value ) {
1886
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1887
		return Jetpack_Options::update_option( $name, $value );
1888
	}
1889
1890
	/**
1891
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1892
 	 *
1893
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1894
	 * @param array $array array( option name => option value, ... )
1895
	 */
1896
	public static function update_options( $array ) {
1897
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1898
		return Jetpack_Options::update_options( $array );
1899
	}
1900
1901
	/**
1902
	 * Deletes the given option.  May be passed multiple option names as an array.
1903
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1904
	 *
1905
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1906
	 * @param string|array $names
1907
	 */
1908
	public static function delete_option( $names ) {
1909
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1910
		return Jetpack_Options::delete_option( $names );
1911
	}
1912
1913
	/**
1914
	 * Enters a user token into the user_tokens option
1915
	 *
1916
	 * @param int $user_id
1917
	 * @param string $token
1918
	 * return bool
1919
	 */
1920
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1921
		// not designed for concurrent updates
1922
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1923
		if ( ! is_array( $user_tokens ) )
1924
			$user_tokens = array();
1925
		$user_tokens[$user_id] = $token;
1926
		if ( $is_master_user ) {
1927
			$master_user = $user_id;
1928
			$options     = compact( 'user_tokens', 'master_user' );
1929
		} else {
1930
			$options = compact( 'user_tokens' );
1931
		}
1932
		return Jetpack_Options::update_options( $options );
1933
	}
1934
1935
	/**
1936
	 * Returns an array of all PHP files in the specified absolute path.
1937
	 * Equivalent to glob( "$absolute_path/*.php" ).
1938
	 *
1939
	 * @param string $absolute_path The absolute path of the directory to search.
1940
	 * @return array Array of absolute paths to the PHP files.
1941
	 */
1942
	public static function glob_php( $absolute_path ) {
1943
		if ( function_exists( 'glob' ) ) {
1944
			return glob( "$absolute_path/*.php" );
1945
		}
1946
1947
		$absolute_path = untrailingslashit( $absolute_path );
1948
		$files = array();
1949
		if ( ! $dir = @opendir( $absolute_path ) ) {
1950
			return $files;
1951
		}
1952
1953
		while ( false !== $file = readdir( $dir ) ) {
1954
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1955
				continue;
1956
			}
1957
1958
			$file = "$absolute_path/$file";
1959
1960
			if ( ! is_file( $file ) ) {
1961
				continue;
1962
			}
1963
1964
			$files[] = $file;
1965
		}
1966
1967
		closedir( $dir );
1968
1969
		return $files;
1970
	}
1971
1972
	public static function activate_new_modules( $redirect = false ) {
1973
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1974
			return;
1975
		}
1976
1977
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1978 View Code Duplication
		if ( ! $jetpack_old_version ) {
1979
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1980
			/** This action is documented in class.jetpack.php */
1981
			do_action( 'updating_jetpack_version', $version, false );
1982
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1983
		}
1984
1985
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1986
1987
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1988
			return;
1989
		}
1990
1991
		$active_modules     = Jetpack::get_active_modules();
1992
		$reactivate_modules = array();
1993
		foreach ( $active_modules as $active_module ) {
1994
			$module = Jetpack::get_module( $active_module );
1995
			if ( ! isset( $module['changed'] ) ) {
1996
				continue;
1997
			}
1998
1999
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2000
				continue;
2001
			}
2002
2003
			$reactivate_modules[] = $active_module;
2004
			Jetpack::deactivate_module( $active_module );
2005
		}
2006
2007
		$new_version = JETPACK__VERSION . ':' . time();
2008
		/** This action is documented in class.jetpack.php */
2009
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2010
		Jetpack_Options::update_options(
2011
			array(
2012
				'version'     => $new_version,
2013
				'old_version' => $jetpack_old_version,
2014
			)
2015
		);
2016
2017
		Jetpack::state( 'message', 'modules_activated' );
2018
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2019
2020
		if ( $redirect ) {
2021
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2022
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2023
				$page = $_GET['page'];
2024
			}
2025
2026
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2027
			exit;
2028
		}
2029
	}
2030
2031
	/**
2032
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2033
	 * Make sure to tuck away module "library" files in a sub-directory.
2034
	 */
2035
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2036
		static $modules = null;
2037
2038
		if ( ! isset( $modules ) ) {
2039
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2040
			// Use the cache if we're on the front-end and it's available...
2041
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2042
				$modules = $available_modules_option[ JETPACK__VERSION ];
2043
			} else {
2044
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2045
2046
				$modules = array();
2047
2048
				foreach ( $files as $file ) {
2049
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2050
						continue;
2051
					}
2052
2053
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2054
				}
2055
2056
				Jetpack_Options::update_option( 'available_modules', array(
2057
					JETPACK__VERSION => $modules,
2058
				) );
2059
			}
2060
		}
2061
2062
		/**
2063
		 * Filters the array of modules available to be activated.
2064
		 *
2065
		 * @since 2.4.0
2066
		 *
2067
		 * @param array $modules Array of available modules.
2068
		 * @param string $min_version Minimum version number required to use modules.
2069
		 * @param string $max_version Maximum version number required to use modules.
2070
		 */
2071
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2072
2073
		if ( ! $min_version && ! $max_version ) {
2074
			return array_keys( $mods );
2075
		}
2076
2077
		$r = array();
2078
		foreach ( $mods as $slug => $introduced ) {
2079
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2080
				continue;
2081
			}
2082
2083
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2084
				continue;
2085
			}
2086
2087
			$r[] = $slug;
2088
		}
2089
2090
		return $r;
2091
	}
2092
2093
	/**
2094
	 * Default modules loaded on activation.
2095
	 */
2096
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2097
		$return = array();
2098
2099
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2100
			$module_data = Jetpack::get_module( $module );
2101
2102
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2103
				case 'yes' :
2104
					$return[] = $module;
2105
					break;
2106
				case 'public' :
2107
					if ( Jetpack_Options::get_option( 'public' ) ) {
2108
						$return[] = $module;
2109
					}
2110
					break;
2111
				case 'no' :
2112
				default :
2113
					break;
2114
			}
2115
		}
2116
		/**
2117
		 * Filters the array of default modules.
2118
		 *
2119
		 * @since 2.5.0
2120
		 *
2121
		 * @param array $return Array of default modules.
2122
		 * @param string $min_version Minimum version number required to use modules.
2123
		 * @param string $max_version Maximum version number required to use modules.
2124
		 */
2125
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2126
	}
2127
2128
	/**
2129
	 * Checks activated modules during auto-activation to determine
2130
	 * if any of those modules are being deprecated.  If so, close
2131
	 * them out, and add any replacement modules.
2132
	 *
2133
	 * Runs at priority 99 by default.
2134
	 *
2135
	 * This is run late, so that it can still activate a module if
2136
	 * the new module is a replacement for another that the user
2137
	 * currently has active, even if something at the normal priority
2138
	 * would kibosh everything.
2139
	 *
2140
	 * @since 2.6
2141
	 * @uses jetpack_get_default_modules filter
2142
	 * @param array $modules
2143
	 * @return array
2144
	 */
2145
	function handle_deprecated_modules( $modules ) {
2146
		$deprecated_modules = array(
2147
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2148
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2149
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2150
		);
2151
2152
		// Don't activate SSO if they never completed activating WPCC.
2153
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2154
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2155
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2156
				$deprecated_modules['wpcc'] = null;
2157
			}
2158
		}
2159
2160
		foreach ( $deprecated_modules as $module => $replacement ) {
2161
			if ( Jetpack::is_module_active( $module ) ) {
2162
				self::deactivate_module( $module );
2163
				if ( $replacement ) {
2164
					$modules[] = $replacement;
2165
				}
2166
			}
2167
		}
2168
2169
		return array_unique( $modules );
2170
	}
2171
2172
	/**
2173
	 * Checks activated plugins during auto-activation to determine
2174
	 * if any of those plugins are in the list with a corresponding module
2175
	 * that is not compatible with the plugin. The module will not be allowed
2176
	 * to auto-activate.
2177
	 *
2178
	 * @since 2.6
2179
	 * @uses jetpack_get_default_modules filter
2180
	 * @param array $modules
2181
	 * @return array
2182
	 */
2183
	function filter_default_modules( $modules ) {
2184
2185
		$active_plugins = self::get_active_plugins();
2186
2187
		if ( ! empty( $active_plugins ) ) {
2188
2189
			// For each module we'd like to auto-activate...
2190
			foreach ( $modules as $key => $module ) {
2191
				// If there are potential conflicts for it...
2192
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2193
					// For each potential conflict...
2194
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2195
						// If that conflicting plugin is active...
2196
						if ( in_array( $plugin, $active_plugins ) ) {
2197
							// Remove that item from being auto-activated.
2198
							unset( $modules[ $key ] );
2199
						}
2200
					}
2201
				}
2202
			}
2203
		}
2204
2205
		return $modules;
2206
	}
2207
2208
	/**
2209
	 * Extract a module's slug from its full path.
2210
	 */
2211
	public static function get_module_slug( $file ) {
2212
		return str_replace( '.php', '', basename( $file ) );
2213
	}
2214
2215
	/**
2216
	 * Generate a module's path from its slug.
2217
	 */
2218
	public static function get_module_path( $slug ) {
2219
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2220
	}
2221
2222
	/**
2223
	 * Load module data from module file. Headers differ from WordPress
2224
	 * plugin headers to avoid them being identified as standalone
2225
	 * plugins on the WordPress plugins page.
2226
	 */
2227
	public static function get_module( $module ) {
2228
		$headers = array(
2229
			'name'                      => 'Module Name',
2230
			'description'               => 'Module Description',
2231
			'jumpstart_desc'            => 'Jumpstart Description',
2232
			'sort'                      => 'Sort Order',
2233
			'recommendation_order'      => 'Recommendation Order',
2234
			'introduced'                => 'First Introduced',
2235
			'changed'                   => 'Major Changes In',
2236
			'deactivate'                => 'Deactivate',
2237
			'free'                      => 'Free',
2238
			'requires_connection'       => 'Requires Connection',
2239
			'auto_activate'             => 'Auto Activate',
2240
			'module_tags'               => 'Module Tags',
2241
			'feature'                   => 'Feature',
2242
			'additional_search_queries' => 'Additional Search Queries',
2243
		);
2244
2245
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2246
2247
		$mod = Jetpack::get_file_data( $file, $headers );
2248
		if ( empty( $mod['name'] ) ) {
2249
			return false;
2250
		}
2251
2252
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2253
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2254
		$mod['deactivate']              = empty( $mod['deactivate'] );
2255
		$mod['free']                    = empty( $mod['free'] );
2256
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2257
2258
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2259
			$mod['auto_activate'] = 'No';
2260
		} else {
2261
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2262
		}
2263
2264
		if ( $mod['module_tags'] ) {
2265
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2266
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2267
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2268
		} else {
2269
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2270
		}
2271
2272
		if ( $mod['feature'] ) {
2273
			$mod['feature'] = explode( ',', $mod['feature'] );
2274
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2275
		} else {
2276
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2277
		}
2278
2279
		/**
2280
		 * Filters the feature array on a module.
2281
		 *
2282
		 * This filter allows you to control where each module is filtered: Recommended,
2283
		 * Jumpstart, and the default "Other" listing.
2284
		 *
2285
		 * @since 3.5.0
2286
		 *
2287
		 * @param array   $mod['feature'] The areas to feature this module:
2288
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2289
		 *     'Recommended' shows on the main Jetpack admin screen.
2290
		 *     'Other' should be the default if no other value is in the array.
2291
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2292
		 * @param array   $mod All the currently assembled module data.
2293
		 */
2294
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2295
2296
		/**
2297
		 * Filter the returned data about a module.
2298
		 *
2299
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2300
		 * so please be careful.
2301
		 *
2302
		 * @since 3.6.0
2303
		 *
2304
		 * @param array   $mod    The details of the requested module.
2305
		 * @param string  $module The slug of the module, e.g. sharedaddy
2306
		 * @param string  $file   The path to the module source file.
2307
		 */
2308
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2309
	}
2310
2311
	/**
2312
	 * Like core's get_file_data implementation, but caches the result.
2313
	 */
2314
	public static function get_file_data( $file, $headers ) {
2315
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2316
		$file_name = basename( $file );
2317
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2318
		$key              = md5( $file_name . serialize( $headers ) );
2319
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2320
2321
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2322
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2323
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2324
		}
2325
2326
		$data = get_file_data( $file, $headers );
2327
2328
		// Strip out any old Jetpack versions that are cluttering the option.
2329
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2330
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2331
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2332
2333
		return $data;
2334
	}
2335
2336
	/**
2337
	 * Return translated module tag.
2338
	 *
2339
	 * @param string $tag Tag as it appears in each module heading.
2340
	 *
2341
	 * @return mixed
2342
	 */
2343
	public static function translate_module_tag( $tag ) {
2344
		return jetpack_get_module_i18n_tag( $tag );
2345
	}
2346
2347
	/**
2348
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2349
	 *
2350
	 * @since 3.9.2
2351
	 *
2352
	 * @param array $modules
2353
	 *
2354
	 * @return string|void
2355
	 */
2356
	public static function get_translated_modules( $modules ) {
2357
		foreach ( $modules as $index => $module ) {
2358
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2359
			if ( isset( $module['name'] ) ) {
2360
				$modules[ $index ]['name'] = $i18n_module['name'];
2361
			}
2362
			if ( isset( $module['description'] ) ) {
2363
				$modules[ $index ]['description'] = $i18n_module['description'];
2364
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2365
			}
2366
		}
2367
		return $modules;
2368
	}
2369
2370
	/**
2371
	 * Get a list of activated modules as an array of module slugs.
2372
	 */
2373
	public static function get_active_modules() {
2374
		$active = Jetpack_Options::get_option( 'active_modules' );
2375
		if ( ! is_array( $active ) )
2376
			$active = array();
2377
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2378
			$active[] = 'vaultpress';
2379
		} else {
2380
			$active = array_diff( $active, array( 'vaultpress' ) );
2381
		}
2382
2383
		//If protect is active on the main site of a multisite, it should be active on all sites.
2384
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2385
			$active[] = 'protect';
2386
		}
2387
2388
		return array_unique( $active );
2389
	}
2390
2391
	/**
2392
	 * Check whether or not a Jetpack module is active.
2393
	 *
2394
	 * @param string $module The slug of a Jetpack module.
2395
	 * @return bool
2396
	 *
2397
	 * @static
2398
	 */
2399
	public static function is_module_active( $module ) {
2400
		return in_array( $module, self::get_active_modules() );
2401
	}
2402
2403
	public static function is_module( $module ) {
2404
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2405
	}
2406
2407
	/**
2408
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2409
	 *
2410
	 * @param bool $catch True to start catching, False to stop.
2411
	 *
2412
	 * @static
2413
	 */
2414
	public static function catch_errors( $catch ) {
2415
		static $display_errors, $error_reporting;
2416
2417
		if ( $catch ) {
2418
			$display_errors  = @ini_set( 'display_errors', 1 );
2419
			$error_reporting = @error_reporting( E_ALL );
2420
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2421
		} else {
2422
			@ini_set( 'display_errors', $display_errors );
2423
			@error_reporting( $error_reporting );
2424
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2425
		}
2426
	}
2427
2428
	/**
2429
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2430
	 */
2431
	public static function catch_errors_on_shutdown() {
2432
		Jetpack::state( 'php_errors', ob_get_clean() );
2433
	}
2434
2435
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2436
		$jetpack = Jetpack::init();
2437
2438
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2439
		$modules = array_merge( $other_modules, $modules );
2440
2441
		// Look for standalone plugins and disable if active.
2442
2443
		$to_deactivate = array();
2444
		foreach ( $modules as $module ) {
2445
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2446
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2447
			}
2448
		}
2449
2450
		$deactivated = array();
2451
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2452
			list( $probable_file, $probable_title ) = $deactivate_me;
2453
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2454
				$deactivated[] = $module;
2455
			}
2456
		}
2457
2458
		if ( $deactivated && $redirect ) {
2459
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2460
2461
			$url = add_query_arg(
2462
				array(
2463
					'action'   => 'activate_default_modules',
2464
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2465
				),
2466
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2467
			);
2468
			wp_safe_redirect( $url );
2469
			exit;
2470
		}
2471
2472
		/**
2473
		 * Fires before default modules are activated.
2474
		 *
2475
		 * @since 1.9.0
2476
		 *
2477
		 * @param string $min_version Minimum version number required to use modules.
2478
		 * @param string $max_version Maximum version number required to use modules.
2479
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2480
		 */
2481
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2482
2483
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2484
		Jetpack::restate();
2485
		Jetpack::catch_errors( true );
2486
2487
		$active = Jetpack::get_active_modules();
2488
2489
		foreach ( $modules as $module ) {
2490
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2491
				$active[] = $module;
2492
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2493
				continue;
2494
			}
2495
2496
			if ( in_array( $module, $active ) ) {
2497
				$module_info = Jetpack::get_module( $module );
2498
				if ( ! $module_info['deactivate'] ) {
2499
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2500 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2501
						$active_state = explode( ',', $active_state );
2502
					} else {
2503
						$active_state = array();
2504
					}
2505
					$active_state[] = $module;
2506
					Jetpack::state( $state, implode( ',', $active_state ) );
2507
				}
2508
				continue;
2509
			}
2510
2511
			$file = Jetpack::get_module_path( $module );
2512
			if ( ! file_exists( $file ) ) {
2513
				continue;
2514
			}
2515
2516
			// we'll override this later if the plugin can be included without fatal error
2517
			if ( $redirect ) {
2518
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2519
			}
2520
			Jetpack::state( 'error', 'module_activation_failed' );
2521
			Jetpack::state( 'module', $module );
2522
			ob_start();
2523
			require $file;
2524
			/**
2525
			 * Fires when a specific module is activated.
2526
			 *
2527
			 * @since 1.9.0
2528
			 *
2529
			 * @param string $module Module slug.
2530
			 */
2531
			do_action( 'jetpack_activate_module', $module );
2532
			$active[] = $module;
2533
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2534 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2535
				$active_state = explode( ',', $active_state );
2536
			} else {
2537
				$active_state = array();
2538
			}
2539
			$active_state[] = $module;
2540
			Jetpack::state( $state, implode( ',', $active_state ) );
2541
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2542
			ob_end_clean();
2543
		}
2544
		Jetpack::state( 'error', false );
2545
		Jetpack::state( 'module', false );
2546
		Jetpack::catch_errors( false );
2547
		/**
2548
		 * Fires when default modules are activated.
2549
		 *
2550
		 * @since 1.9.0
2551
		 *
2552
		 * @param string $min_version Minimum version number required to use modules.
2553
		 * @param string $max_version Maximum version number required to use modules.
2554
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2555
		 */
2556
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2557
	}
2558
2559
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2560
		/**
2561
		 * Fires before a module is activated.
2562
		 *
2563
		 * @since 2.6.0
2564
		 *
2565
		 * @param string $module Module slug.
2566
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2567
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2568
		 */
2569
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2570
2571
		$jetpack = Jetpack::init();
2572
2573
		if ( ! strlen( $module ) )
2574
			return false;
2575
2576
		if ( ! Jetpack::is_module( $module ) )
2577
			return false;
2578
2579
		// If it's already active, then don't do it again
2580
		$active = Jetpack::get_active_modules();
2581
		foreach ( $active as $act ) {
2582
			if ( $act == $module )
2583
				return true;
2584
		}
2585
2586
		$module_data = Jetpack::get_module( $module );
2587
2588
		if ( ! Jetpack::is_active() ) {
2589
			if ( !Jetpack::is_development_mode() )
2590
				return false;
2591
2592
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2593
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2594
				return false;
2595
		}
2596
2597
		// Check and see if the old plugin is active
2598
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2599
			// Deactivate the old plugin
2600
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2601
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2602
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2603
				Jetpack::state( 'deactivated_plugins', $module );
2604
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2605
				exit;
2606
			}
2607
		}
2608
2609
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2610
		Jetpack::state( 'module', $module );
2611
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2612
2613
		Jetpack::catch_errors( true );
2614
		ob_start();
2615
		require Jetpack::get_module_path( $module );
2616
		/** This action is documented in class.jetpack.php */
2617
		do_action( 'jetpack_activate_module', $module );
2618
		$active[] = $module;
2619
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2620
		Jetpack::state( 'error', false ); // the override
2621
		Jetpack::state( 'message', 'module_activated' );
2622
		Jetpack::state( 'module', $module );
2623
		ob_end_clean();
2624
		Jetpack::catch_errors( false );
2625
2626
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2627 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2628
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2629
2630
			//Jump start is being dismissed send data to MC Stats
2631
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2632
2633
			$jetpack->do_stats( 'server_side' );
2634
		}
2635
2636
		if ( $redirect ) {
2637
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2638
		}
2639
		if ( $exit ) {
2640
			exit;
2641
		}
2642
		return true;
2643
	}
2644
2645
	function activate_module_actions( $module ) {
2646
		/**
2647
		 * Fires when a module is activated.
2648
		 * The dynamic part of the filter, $module, is the module slug.
2649
		 *
2650
		 * @since 1.9.0
2651
		 *
2652
		 * @param string $module Module slug.
2653
		 */
2654
		do_action( "jetpack_activate_module_$module", $module );
2655
	}
2656
2657
	public static function deactivate_module( $module ) {
2658
		/**
2659
		 * Fires when a module is deactivated.
2660
		 *
2661
		 * @since 1.9.0
2662
		 *
2663
		 * @param string $module Module slug.
2664
		 */
2665
		do_action( 'jetpack_pre_deactivate_module', $module );
2666
2667
		$jetpack = Jetpack::init();
2668
2669
		$active = Jetpack::get_active_modules();
2670
		$new    = array_filter( array_diff( $active, (array) $module ) );
2671
2672
		/**
2673
		 * Fires when a module is deactivated.
2674
		 * The dynamic part of the filter, $module, is the module slug.
2675
		 *
2676
		 * @since 1.9.0
2677
		 *
2678
		 * @param string $module Module slug.
2679
		 */
2680
		do_action( "jetpack_deactivate_module_$module", $module );
2681
2682
		// A flag for Jump Start so it's not shown again.
2683 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2684
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2685
2686
			//Jump start is being dismissed send data to MC Stats
2687
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2688
2689
			$jetpack->do_stats( 'server_side' );
2690
		}
2691
2692
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2693
	}
2694
2695
	public static function enable_module_configurable( $module ) {
2696
		$module = Jetpack::get_module_slug( $module );
2697
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2698
	}
2699
2700
	public static function module_configuration_url( $module ) {
2701
		$module = Jetpack::get_module_slug( $module );
2702
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2703
	}
2704
2705
	public static function module_configuration_load( $module, $method ) {
2706
		$module = Jetpack::get_module_slug( $module );
2707
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2708
	}
2709
2710
	public static function module_configuration_head( $module, $method ) {
2711
		$module = Jetpack::get_module_slug( $module );
2712
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2713
	}
2714
2715
	public static function module_configuration_screen( $module, $method ) {
2716
		$module = Jetpack::get_module_slug( $module );
2717
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2718
	}
2719
2720
	public static function module_configuration_activation_screen( $module, $method ) {
2721
		$module = Jetpack::get_module_slug( $module );
2722
		add_action( 'display_activate_module_setting_' . $module, $method );
2723
	}
2724
2725
/* Installation */
2726
2727
	public static function bail_on_activation( $message, $deactivate = true ) {
2728
?>
2729
<!doctype html>
2730
<html>
2731
<head>
2732
<meta charset="<?php bloginfo( 'charset' ); ?>">
2733
<style>
2734
* {
2735
	text-align: center;
2736
	margin: 0;
2737
	padding: 0;
2738
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2739
}
2740
p {
2741
	margin-top: 1em;
2742
	font-size: 18px;
2743
}
2744
</style>
2745
<body>
2746
<p><?php echo esc_html( $message ); ?></p>
2747
</body>
2748
</html>
2749
<?php
2750
		if ( $deactivate ) {
2751
			$plugins = get_option( 'active_plugins' );
2752
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2753
			$update  = false;
2754
			foreach ( $plugins as $i => $plugin ) {
2755
				if ( $plugin === $jetpack ) {
2756
					$plugins[$i] = false;
2757
					$update = true;
2758
				}
2759
			}
2760
2761
			if ( $update ) {
2762
				update_option( 'active_plugins', array_filter( $plugins ) );
2763
			}
2764
		}
2765
		exit;
2766
	}
2767
2768
	/**
2769
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2770
	 * @static
2771
	 */
2772
	public static function plugin_activation( $network_wide ) {
2773
		Jetpack_Options::update_option( 'activated', 1 );
2774
2775
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2776
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2777
		}
2778
2779
		if ( $network_wide )
2780
			Jetpack::state( 'network_nag', true );
2781
2782
		Jetpack::plugin_initialize();
2783
	}
2784
	/**
2785
	 * Runs before bumping version numbers up to a new version
2786
	 * @param  (string) $version    Version:timestamp
2787
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2788
	 * @return null              [description]
2789
	 */
2790
	public static function do_version_bump( $version, $old_version ) {
2791
2792
		if ( ! $old_version ) { // For new sites
2793
			// Setting up jetpack manage
2794
			Jetpack::activate_manage();
2795
		}
2796
	}
2797
2798
	/**
2799
	 * Sets the internal version number and activation state.
2800
	 * @static
2801
	 */
2802
	public static function plugin_initialize() {
2803
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2804
			Jetpack_Options::update_option( 'activated', 2 );
2805
		}
2806
2807 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2808
			$version = $old_version = JETPACK__VERSION . ':' . time();
2809
			/** This action is documented in class.jetpack.php */
2810
			do_action( 'updating_jetpack_version', $version, false );
2811
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2812
		}
2813
2814
		Jetpack::load_modules();
2815
2816
		Jetpack_Options::delete_option( 'do_activate' );
2817
	}
2818
2819
	/**
2820
	 * Removes all connection options
2821
	 * @static
2822
	 */
2823
	public static function plugin_deactivation( ) {
2824
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2825
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2826
			Jetpack_Network::init()->deactivate();
2827
		} else {
2828
			Jetpack::disconnect( false );
2829
			//Jetpack_Heartbeat::init()->deactivate();
2830
		}
2831
	}
2832
2833
	/**
2834
	 * Disconnects from the Jetpack servers.
2835
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2836
	 * @static
2837
	 */
2838
	public static function disconnect( $update_activated_state = true ) {
2839
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2840
		Jetpack::clean_nonces( true );
2841
2842
		Jetpack::load_xml_rpc_client();
2843
		$xml = new Jetpack_IXR_Client();
2844
		$xml->query( 'jetpack.deregister' );
2845
2846
		Jetpack_Options::delete_option(
2847
			array(
2848
				'register',
2849
				'blog_token',
2850
				'user_token',
2851
				'user_tokens',
2852
				'master_user',
2853
				'time_diff',
2854
				'fallback_no_verify_ssl_certs',
2855
			)
2856
		);
2857
2858
		if ( $update_activated_state ) {
2859
			Jetpack_Options::update_option( 'activated', 4 );
2860
		}
2861
2862
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2863
		// Check then record unique disconnection if site has never been disconnected previously
2864
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2865
			$jetpack_unique_connection['disconnected'] = 1;
2866
		}
2867
		else {
2868
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2869
				//track unique disconnect
2870
				$jetpack = Jetpack::init();
2871
2872
				$jetpack->stat( 'connections', 'unique-disconnect' );
2873
				$jetpack->do_stats( 'server_side' );
2874
			}
2875
			// increment number of times disconnected
2876
			$jetpack_unique_connection['disconnected'] += 1;
2877
		}
2878
2879
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2880
2881
		// Disable the Heartbeat cron
2882
		Jetpack_Heartbeat::init()->deactivate();
2883
	}
2884
2885
	/**
2886
	 * Unlinks the current user from the linked WordPress.com user
2887
	 */
2888
	public static function unlink_user( $user_id = null ) {
2889
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2890
			return false;
2891
2892
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2893
2894
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2895
			return false;
2896
2897
		if ( ! isset( $tokens[ $user_id ] ) )
2898
			return false;
2899
2900
		Jetpack::load_xml_rpc_client();
2901
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2902
		$xml->query( 'jetpack.unlink_user', $user_id );
2903
2904
		unset( $tokens[ $user_id ] );
2905
2906
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2907
2908
		/**
2909
		 * Fires after the current user has been unlinked from WordPress.com.
2910
		 *
2911
		 * @since 4.1.0
2912
		 *
2913
		 * @param int $user_id The current user's ID.
2914
		 */
2915
		do_action( 'jetpack_unlinked_user', $user_id );
2916
2917
		return true;
2918
	}
2919
2920
	/**
2921
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2922
	 */
2923
	public static function try_registration() {
2924
		// Let's get some testing in beta versions and such.
2925
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2926
			// Before attempting to connect, let's make sure that the domains are viable.
2927
			$domains_to_check = array_unique( array(
2928
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2929
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2930
			) );
2931
			foreach ( $domains_to_check as $domain ) {
2932
				$result = Jetpack_Data::is_usable_domain( $domain );
2933
				if ( is_wp_error( $result ) ) {
2934
					return $result;
2935
				}
2936
			}
2937
		}
2938
2939
		$result = Jetpack::register();
2940
2941
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2942
		if ( ! $result || is_wp_error( $result ) ) {
2943
			return $result;
2944
		} else {
2945
			return true;
2946
		}
2947
	}
2948
2949
	/**
2950
	 * Tracking an internal event log. Try not to put too much chaff in here.
2951
	 *
2952
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2953
	 */
2954
	public static function log( $code, $data = null ) {
2955
		// only grab the latest 200 entries
2956
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2957
2958
		// Append our event to the log
2959
		$log_entry = array(
2960
			'time'    => time(),
2961
			'user_id' => get_current_user_id(),
2962
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2963
			'code'    => $code,
2964
		);
2965
		// Don't bother storing it unless we've got some.
2966
		if ( ! is_null( $data ) ) {
2967
			$log_entry['data'] = $data;
2968
		}
2969
		$log[] = $log_entry;
2970
2971
		// Try add_option first, to make sure it's not autoloaded.
2972
		// @todo: Add an add_option method to Jetpack_Options
2973
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2974
			Jetpack_Options::update_option( 'log', $log );
2975
		}
2976
2977
		/**
2978
		 * Fires when Jetpack logs an internal event.
2979
		 *
2980
		 * @since 3.0.0
2981
		 *
2982
		 * @param array $log_entry {
2983
		 *	Array of details about the log entry.
2984
		 *
2985
		 *	@param string time Time of the event.
2986
		 *	@param int user_id ID of the user who trigerred the event.
2987
		 *	@param int blog_id Jetpack Blog ID.
2988
		 *	@param string code Unique name for the event.
2989
		 *	@param string data Data about the event.
2990
		 * }
2991
		 */
2992
		do_action( 'jetpack_log_entry', $log_entry );
2993
	}
2994
2995
	/**
2996
	 * Get the internal event log.
2997
	 *
2998
	 * @param $event (string) - only return the specific log events
2999
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3000
	 *
3001
	 * @return array of log events || WP_Error for invalid params
3002
	 */
3003
	public static function get_log( $event = false, $num = false ) {
3004
		if ( $event && ! is_string( $event ) ) {
3005
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3006
		}
3007
3008
		if ( $num && ! is_numeric( $num ) ) {
3009
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3010
		}
3011
3012
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3013
3014
		// If nothing set - act as it did before, otherwise let's start customizing the output
3015
		if ( ! $num && ! $event ) {
3016
			return $entire_log;
3017
		} else {
3018
			$entire_log = array_reverse( $entire_log );
3019
		}
3020
3021
		$custom_log_output = array();
3022
3023
		if ( $event ) {
3024
			foreach ( $entire_log as $log_event ) {
3025
				if ( $event == $log_event[ 'code' ] ) {
3026
					$custom_log_output[] = $log_event;
3027
				}
3028
			}
3029
		} else {
3030
			$custom_log_output = $entire_log;
3031
		}
3032
3033
		if ( $num ) {
3034
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3035
		}
3036
3037
		return $custom_log_output;
3038
	}
3039
3040
	/**
3041
	 * Log modification of important settings.
3042
	 */
3043
	public static function log_settings_change( $option, $old_value, $value ) {
3044
		switch( $option ) {
3045
			case 'jetpack_sync_non_public_post_stati':
3046
				self::log( $option, $value );
3047
				break;
3048
		}
3049
	}
3050
3051
	/**
3052
	 * Return stat data for WPCOM sync
3053
	 */
3054
	function get_stat_data() {
3055
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3056
		$additional_data = $this->get_additional_stat_data();
3057
3058
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3059
	}
3060
3061
	/**
3062
	 * Get additional stat data to sync to WPCOM
3063
	 */
3064
	function get_additional_stat_data( $prefix = '' ) {
3065
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3066
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3067
		$return["{$prefix}users"]          = count_users();
3068
		$return["{$prefix}site-count"]     = 0;
3069
		if ( function_exists( 'get_blog_count' ) ) {
3070
			$return["{$prefix}site-count"] = get_blog_count();
3071
		}
3072
		return $return;
3073
	}
3074
3075
	/* Admin Pages */
3076
3077
	function admin_init() {
3078
		// If the plugin is not connected, display a connect message.
3079
		if (
3080
			// the plugin was auto-activated and needs its candy
3081
			Jetpack_Options::get_option( 'do_activate' )
3082
		||
3083
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3084
			! Jetpack_Options::get_option( 'activated' )
3085
		) {
3086
			Jetpack::plugin_initialize();
3087
		}
3088
3089
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3090
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3091
				// Show connect notice on dashboard and plugins pages
3092
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3093
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3094
			}
3095
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3096
			// Upgrade: 1.1 -> 1.1.1
3097
			// Check and see if host can verify the Jetpack servers' SSL certificate
3098
			$args = array();
3099
			Jetpack_Client::_wp_remote_request(
3100
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3101
				$args,
3102
				true
3103
			);
3104
		} else {
3105
			// Show the notice on the Dashboard only for now
3106
3107
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3108
3109
			// Identity crisis notices
3110
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3111
		}
3112
3113
		// If the plugin has just been disconnected from WP.com, show the survey notice
3114
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3115
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3116
		}
3117
3118
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3119
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3120
		}
3121
3122
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3123
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3124
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3125
3126
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3127
			// Artificially throw errors in certain whitelisted cases during plugin activation
3128
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3129
3130
			// Kick off synchronization of user role when it changes
3131
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3132
		}
3133
3134
		// Jetpack Manage Activation Screen from .com
3135
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3136
	}
3137
3138
	function admin_body_class( $admin_body_class = '' ) {
3139
		$classes = explode( ' ', trim( $admin_body_class ) );
3140
3141
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3142
3143
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3144
		return " $admin_body_class ";
3145
	}
3146
3147
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3148
		return $admin_body_class . ' jetpack-pagestyles ';
3149
	}
3150
3151
	function prepare_connect_notice() {
3152
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3153
3154
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3155
3156
		if ( Jetpack::state( 'network_nag' ) )
3157
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3158
	}
3159
	/**
3160
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3161
	 *
3162
	 * @return null
3163
	 */
3164
	function prepare_manage_jetpack_notice() {
3165
3166
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3167
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3168
	}
3169
3170
	function manage_activate_screen() {
3171
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3172
	}
3173
	/**
3174
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3175
	 * This function artificially throws errors for such cases (whitelisted).
3176
	 *
3177
	 * @param string $plugin The activated plugin.
3178
	 */
3179
	function throw_error_on_activate_plugin( $plugin ) {
3180
		$active_modules = Jetpack::get_active_modules();
3181
3182
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3183
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3184
			$throw = false;
3185
3186
			// Try and make sure it really was the stats plugin
3187
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3188
				if ( 'stats.php' == basename( $plugin ) ) {
3189
					$throw = true;
3190
				}
3191
			} else {
3192
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3193
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3194
					$throw = true;
3195
				}
3196
			}
3197
3198
			if ( $throw ) {
3199
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3200
			}
3201
		}
3202
	}
3203
3204
	function intercept_plugin_error_scrape_init() {
3205
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3206
	}
3207
3208
	function intercept_plugin_error_scrape( $action, $result ) {
3209
		if ( ! $result ) {
3210
			return;
3211
		}
3212
3213
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3214
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3215
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3216
			}
3217
		}
3218
	}
3219
3220
	function add_remote_request_handlers() {
3221
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3222
	}
3223
3224
	function remote_request_handlers() {
3225
		switch ( current_filter() ) {
3226
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3227
			$response = $this->upload_handler();
3228
			break;
3229
		default :
3230
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3231
			break;
3232
		}
3233
3234
		if ( ! $response ) {
3235
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3236
		}
3237
3238
		if ( is_wp_error( $response ) ) {
3239
			$status_code       = $response->get_error_data();
3240
			$error             = $response->get_error_code();
3241
			$error_description = $response->get_error_message();
3242
3243
			if ( ! is_int( $status_code ) ) {
3244
				$status_code = 400;
3245
			}
3246
3247
			status_header( $status_code );
3248
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3249
		}
3250
3251
		status_header( 200 );
3252
		if ( true === $response ) {
3253
			exit;
3254
		}
3255
3256
		die( json_encode( (object) $response ) );
3257
	}
3258
3259
	function upload_handler() {
3260
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3261
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3262
		}
3263
3264
		$user = wp_authenticate( '', '' );
3265
		if ( ! $user || is_wp_error( $user ) ) {
3266
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3267
		}
3268
3269
		wp_set_current_user( $user->ID );
3270
3271
		if ( ! current_user_can( 'upload_files' ) ) {
3272
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3273
		}
3274
3275
		if ( empty( $_FILES ) ) {
3276
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3277
		}
3278
3279
		foreach ( array_keys( $_FILES ) as $files_key ) {
3280
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3281
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3282
			}
3283
		}
3284
3285
		$media_keys = array_keys( $_FILES['media'] );
3286
3287
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3288
		if ( ! $token || is_wp_error( $token ) ) {
3289
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3290
		}
3291
3292
		$uploaded_files = array();
3293
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3294
		unset( $GLOBALS['post'] );
3295
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3296
			$file = array();
3297
			foreach ( $media_keys as $media_key ) {
3298
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3299
			}
3300
3301
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3302
3303
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3304
			if ( $hmac_provided !== $hmac_file ) {
3305
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3306
				continue;
3307
			}
3308
3309
			$_FILES['.jetpack.upload.'] = $file;
3310
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3311
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3312
				$post_id = 0;
3313
			}
3314
			$attachment_id = media_handle_upload(
3315
				'.jetpack.upload.',
3316
				$post_id,
3317
				array(),
3318
				array(
3319
					'action' => 'jetpack_upload_file',
3320
				)
3321
			);
3322
3323
			if ( ! $attachment_id ) {
3324
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3325
			} elseif ( is_wp_error( $attachment_id ) ) {
3326
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3327
			} else {
3328
				$attachment = get_post( $attachment_id );
3329
				$uploaded_files[$index] = (object) array(
3330
					'id'   => (string) $attachment_id,
3331
					'file' => $attachment->post_title,
3332
					'url'  => wp_get_attachment_url( $attachment_id ),
3333
					'type' => $attachment->post_mime_type,
3334
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3335
				);
3336
			}
3337
		}
3338
		if ( ! is_null( $global_post ) ) {
3339
			$GLOBALS['post'] = $global_post;
3340
		}
3341
3342
		return $uploaded_files;
3343
	}
3344
3345
	/**
3346
	 * Add help to the Jetpack page
3347
	 *
3348
	 * @since Jetpack (1.2.3)
3349
	 * @return false if not the Jetpack page
3350
	 */
3351
	function admin_help() {
3352
		$current_screen = get_current_screen();
3353
3354
		// Overview
3355
		$current_screen->add_help_tab(
3356
			array(
3357
				'id'		=> 'home',
3358
				'title'		=> __( 'Home', 'jetpack' ),
3359
				'content'	=>
3360
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3361
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3362
					'<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>',
3363
			)
3364
		);
3365
3366
		// Screen Content
3367
		if ( current_user_can( 'manage_options' ) ) {
3368
			$current_screen->add_help_tab(
3369
				array(
3370
					'id'		=> 'settings',
3371
					'title'		=> __( 'Settings', 'jetpack' ),
3372
					'content'	=>
3373
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3374
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3375
						'<ol>' .
3376
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3377
							'<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>' .
3378
						'</ol>' .
3379
						'<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>'
3380
				)
3381
			);
3382
		}
3383
3384
		// Help Sidebar
3385
		$current_screen->set_help_sidebar(
3386
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3387
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3388
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3389
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3390
		);
3391
	}
3392
3393
	function admin_menu_css() {
3394
		wp_enqueue_style( 'jetpack-icons' );
3395
	}
3396
3397
	function admin_menu_order() {
3398
		return true;
3399
	}
3400
3401 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3402
		$jp_menu_order = array();
3403
3404
		foreach ( $menu_order as $index => $item ) {
3405
			if ( $item != 'jetpack' ) {
3406
				$jp_menu_order[] = $item;
3407
			}
3408
3409
			if ( $index == 0 ) {
3410
				$jp_menu_order[] = 'jetpack';
3411
			}
3412
		}
3413
3414
		return $jp_menu_order;
3415
	}
3416
3417
	function admin_head() {
3418 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3419
			/** This action is documented in class.jetpack-admin-page.php */
3420
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3421
	}
3422
3423
	function admin_banner_styles() {
3424
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3425
3426
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3427
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3428
		wp_style_add_data( 'jetpack', 'suffix', $min );
3429
	}
3430
3431
	function admin_scripts() {
3432
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3433
		wp_localize_script(
3434
			'jetpack-js',
3435
			'jetpackL10n',
3436
			array(
3437
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3438
				'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?",
3439
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3440
			)
3441
		);
3442
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3443
	}
3444
3445
	function plugin_action_links( $actions ) {
3446
3447
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3448
3449
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3450
			return array_merge(
3451
				$jetpack_home,
3452
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3453
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3454
				$actions
3455
				);
3456
			}
3457
3458
		return array_merge( $jetpack_home, $actions );
3459
	}
3460
3461
	function admin_connect_notice() {
3462
		// Don't show the connect notice anywhere but the plugins.php after activating
3463
		$current = get_current_screen();
3464
		if ( 'plugins' !== $current->parent_base )
3465
			return;
3466
3467
		if ( ! current_user_can( 'jetpack_connect' ) )
3468
			return;
3469
3470
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3471
		?>
3472
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3473
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"></a>
3474
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3475
				<div class="jp-banner__content is-connection">
3476
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3477
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3478
				</div>
3479
				<div class="jp-banner__action-container is-connection">
3480
						<a href="<?php echo $this->build_connect_url( false, false, 'banner' ) ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a>
3481
				</div>
3482 View Code Duplication
			<?php else : ?>
3483
				<div class="jp-banner__content">
3484
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3485
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3486
				</div>
3487
				<div class="jp-banner__action-container">
3488
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3489
				</div>
3490
			<?php endif; ?>
3491
		</div>
3492
3493
		<?php
3494
	}
3495
3496
	/**
3497
	 * This is the first banner
3498
	 * It should be visible only to user that can update the option
3499
	 * Are not connected
3500
	 *
3501
	 * @return null
3502
	 */
3503
	function admin_jetpack_manage_notice() {
3504
		$screen = get_current_screen();
3505
3506
		// Don't show the connect notice on the jetpack settings page.
3507
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3508
			return;
3509
3510
		// Only show it if don't have the managment option set.
3511
		// And not dismissed it already.
3512
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3513
			return;
3514
		}
3515
3516
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3517
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3518
		/**
3519
		 * I think it would be great to have different wordsing depending on where you are
3520
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3521
		 * etc..
3522
		 */
3523
3524
		?>
3525
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3526
			<a class="jp-banner__dismiss" href="<?php echo esc_url( $opt_out_url ); ?>" title="<?php esc_attr_e( 'Dismiss this notice for now.', 'jetpack' ); ?>"></a>
3527
			<div class="jp-banner__content">
3528
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3529
				<p><?php printf( __( 'Manage multiple sites from one dashboard at wordpress.com/sites. Enabling allows all existing, connected Administrators to modify your site from WordPress.com. <a href="%s" target="_blank">Learn More</a>.', 'jetpack' ), 'http://jetpack.com/support/site-management' ); ?></p>
3530
			</div>
3531
			<div class="jp-banner__action-container is-opt-in">
3532
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3533
			</div>
3534
		</div>
3535
		<?php
3536
	}
3537
3538
	/**
3539
	 * Returns the url that the user clicks to remove the notice for the big banner
3540
	 * @return (string)
3541
	 */
3542
	function opt_out_jetpack_manage_url() {
3543
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3544
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3545
	}
3546
	/**
3547
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3548
	 * @return (string)
3549
	 */
3550
	function opt_in_jetpack_manage_url() {
3551
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3552
	}
3553
3554
	function opt_in_jetpack_manage_notice() {
3555
		?>
3556
		<div class="wrap">
3557
			<div id="message" class="jetpack-message is-opt-in">
3558
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'http://jetpack.com/support/site-management' ); ?>
3559
			</div>
3560
		</div>
3561
		<?php
3562
3563
	}
3564
	/**
3565
	 * Determines whether to show the notice of not true = display notice
3566
	 * @return (bool)
3567
	 */
3568
	function can_display_jetpack_manage_notice() {
3569
		// never display the notice to users that can't do anything about it anyways
3570
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3571
			return false;
3572
3573
		// don't display if we are in development more
3574
		if( Jetpack::is_development_mode() ) {
3575
			return false;
3576
		}
3577
		// don't display if the site is private
3578
		if(  ! Jetpack_Options::get_option( 'public' ) )
3579
			return false;
3580
3581
		/**
3582
		 * Should the Jetpack Remote Site Management notice be displayed.
3583
		 *
3584
		 * @since 3.3.0
3585
		 *
3586
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3587
		 */
3588
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3589
	}
3590
3591
	function network_connect_notice() {
3592
		?>
3593
		<div id="message" class="updated jetpack-message">
3594
			<div class="squeezer">
3595
				<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>
3596
			</div>
3597
		</div>
3598
		<?php
3599
	}
3600
3601
	public static function jetpack_comment_notice() {
3602
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3603
			return '';
3604
		}
3605
3606
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3607
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3608
3609
		if ( $jetpack_old_version ) {
3610
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3611
				return '';
3612
			}
3613
		}
3614
3615
		if ( $jetpack_new_version ) {
3616
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3617
				return '';
3618
			}
3619
		}
3620
3621
		return '<br /><br />' . sprintf(
3622
			__( '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' ),
3623
			wp_nonce_url(
3624
				Jetpack::admin_url(
3625
					array(
3626
						'page'   => 'jetpack',
3627
						'action' => 'activate',
3628
						'module' => 'comments',
3629
					)
3630
				),
3631
				'jetpack_activate-comments'
3632
			),
3633
			__( 'click here', 'jetpack' )
3634
		);
3635
	}
3636
3637
	/**
3638
	 * Show the survey link when the user has just disconnected Jetpack.
3639
	 */
3640
	function disconnect_survey_notice() {
3641
		?>
3642
		<div class="wrap">
3643
			<div id="message" class="jetpack-message stay-visible">
3644
				<div class="squeezer">
3645
					<h2>
3646
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3647
						<br />
3648
						<?php echo sprintf(
3649
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3650
							'https://jetpack.com/survey-disconnected/',
3651
							'_blank'
3652
						); ?>
3653
					</h2>
3654
				</div>
3655
			</div>
3656
		</div>
3657
		<?php
3658
	}
3659
3660
	/*
3661
	 * Registration flow:
3662
	 * 1 - ::admin_page_load() action=register
3663
	 * 2 - ::try_registration()
3664
	 * 3 - ::register()
3665
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3666
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3667
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3668
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3669
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3670
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3671
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3672
	 *       jetpack_id, jetpack_secret, jetpack_public
3673
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3674
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3675
	 * 5 - user logs in with WP.com account
3676
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3677
	 *		- Jetpack_Client_Server::authorize()
3678
	 *		- Jetpack_Client_Server::get_token()
3679
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3680
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3681
	 *			- which responds with access_token, token_type, scope
3682
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3683
	 *		- Jetpack::activate_default_modules()
3684
	 *     		- Deactivates deprecated plugins
3685
	 *     		- Activates all default modules
3686
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3687
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3688
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3689
	 *     Done!
3690
	 */
3691
3692
	/**
3693
	 * Handles the page load events for the Jetpack admin page
3694
	 */
3695
	function admin_page_load() {
3696
		$error = false;
3697
3698
		// Make sure we have the right body class to hook stylings for subpages off of.
3699
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3700
3701
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3702
			// Should only be used in intermediate redirects to preserve state across redirects
3703
			Jetpack::restate();
3704
		}
3705
3706
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3707
			// User clicked in the iframe to link their accounts
3708
			if ( ! Jetpack::is_user_connected() ) {
3709
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3710
				if ( isset( $_GET['notes_iframe'] ) )
3711
					$connect_url .= '&notes_iframe';
3712
				wp_redirect( $connect_url );
3713
				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...
3714
			} else {
3715
				Jetpack::state( 'message', 'already_authorized' );
3716
				wp_safe_redirect( Jetpack::admin_url() );
3717
				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...
3718
			}
3719
		}
3720
3721
3722
		if ( isset( $_GET['action'] ) ) {
3723
			switch ( $_GET['action'] ) {
3724
			case 'authorize':
3725
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3726
					Jetpack::state( 'message', 'already_authorized' );
3727
					wp_safe_redirect( Jetpack::admin_url() );
3728
					exit;
3729
				}
3730
				Jetpack::log( 'authorize' );
3731
				$client_server = new Jetpack_Client_Server;
3732
				$client_server->client_authorize();
3733
				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...
3734
			case 'register' :
3735
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3736
					$error = 'cheatin';
3737
					break;
3738
				}
3739
				check_admin_referer( 'jetpack-register' );
3740
				Jetpack::log( 'register' );
3741
				Jetpack::maybe_set_version_option();
3742
				$registered = Jetpack::try_registration();
3743
				if ( is_wp_error( $registered ) ) {
3744
					$error = $registered->get_error_code();
3745
					Jetpack::state( 'error_description', $registered->get_error_message() );
3746
					break;
3747
				}
3748
3749
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3750
3751
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3752
				exit;
3753
			case 'activate' :
3754
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3755
					$error = 'cheatin';
3756
					break;
3757
				}
3758
3759
				$module = stripslashes( $_GET['module'] );
3760
				check_admin_referer( "jetpack_activate-$module" );
3761
				Jetpack::log( 'activate', $module );
3762
				Jetpack::activate_module( $module );
3763
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3764
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3765
				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...
3766
			case 'activate_default_modules' :
3767
				check_admin_referer( 'activate_default_modules' );
3768
				Jetpack::log( 'activate_default_modules' );
3769
				Jetpack::restate();
3770
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3771
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3772
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3773
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3774
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3775
				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...
3776
			case 'disconnect' :
3777
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3778
					$error = 'cheatin';
3779
					break;
3780
				}
3781
3782
				check_admin_referer( 'jetpack-disconnect' );
3783
				Jetpack::log( 'disconnect' );
3784
				Jetpack::disconnect();
3785
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3786
				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...
3787
			case 'reconnect' :
3788
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3789
					$error = 'cheatin';
3790
					break;
3791
				}
3792
3793
				check_admin_referer( 'jetpack-reconnect' );
3794
				Jetpack::log( 'reconnect' );
3795
				$this->disconnect();
3796
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3797
				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...
3798 View Code Duplication
			case 'deactivate' :
3799
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3800
					$error = 'cheatin';
3801
					break;
3802
				}
3803
3804
				$modules = stripslashes( $_GET['module'] );
3805
				check_admin_referer( "jetpack_deactivate-$modules" );
3806
				foreach ( explode( ',', $modules ) as $module ) {
3807
					Jetpack::log( 'deactivate', $module );
3808
					Jetpack::deactivate_module( $module );
3809
					Jetpack::state( 'message', 'module_deactivated' );
3810
				}
3811
				Jetpack::state( 'module', $modules );
3812
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3813
				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...
3814
			case 'unlink' :
3815
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3816
				check_admin_referer( 'jetpack-unlink' );
3817
				Jetpack::log( 'unlink' );
3818
				$this->unlink_user();
3819
				Jetpack::state( 'message', 'unlinked' );
3820
				if ( 'sub-unlink' == $redirect ) {
3821
					wp_safe_redirect( admin_url() );
3822
				} else {
3823
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3824
				}
3825
				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...
3826
			default:
3827
				/**
3828
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3829
				 *
3830
				 * @since 2.6.0
3831
				 *
3832
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3833
				 */
3834
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3835
			}
3836
		}
3837
3838
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3839
			self::activate_new_modules( true );
3840
		}
3841
3842
		switch ( $error ) {
3843
		case 'cheatin' :
3844
			$this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
3845
			break;
3846
		case 'access_denied' :
3847
			$this->error = sprintf( __( 'Would you mind telling us why you did not complete the Jetpack connection in this <a href="%s">1 question survey</a>?', 'jetpack' ), 'http://jetpack.com/cancelled-connection/' ) . '<br /><small>' . __( 'A Jetpack connection is required for our free security and traffic features to work.', 'jetpack' ) . '</small>';
3848
			break;
3849
		case 'wrong_state' :
3850
			$this->error = __( 'You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
3851
			break;
3852
		case 'invalid_client' :
3853
			// @todo re-register instead of deactivate/reactivate
3854
			$this->error = __( 'We had an issue connecting Jetpack; deactivate then reactivate the Jetpack plugin, then connect again.', 'jetpack' );
3855
			break;
3856
		case 'invalid_grant' :
3857
			$this->error = __( 'There was an issue connecting your Jetpack. Please click &#8220;Connect to WordPress.com&#8221; again.', 'jetpack' );
3858
			break;
3859
		case 'site_inaccessible' :
3860
		case 'site_requires_authorization' :
3861
			$this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
3862
			break;
3863
		case 'module_activation_failed' :
3864
			$module = Jetpack::state( 'module' );
3865
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3866
				$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'] );
3867
				if ( isset( $this->plugins_to_deactivate[$module] ) ) {
3868
					$this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
3869
				}
3870
			} else {
3871
				$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' );
3872
			}
3873
			if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
3874
				$this->error .= "<br />\n";
3875
				$this->error .= $php_errors;
3876
			}
3877
			break;
3878
		case 'master_user_required' :
3879
			$module = Jetpack::state( 'module' );
3880
			$module_name = '';
3881
			if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
3882
				$module_name = $mod['name'];
3883
			}
3884
3885
			$master_user = Jetpack_Options::get_option( 'master_user' );
3886
			$master_userdata = get_userdata( $master_user ) ;
3887
			if ( $master_userdata ) {
3888
				if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
3889
					$this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
3890
				} else {
3891
					$this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
3892
				}
3893
				$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 ) );
3894
3895
			} else {
3896
				$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 );
3897
			}
3898
			break;
3899
		case 'not_public' :
3900
			$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' );
3901
			break;
3902
		case 'wpcom_408' :
3903
		case 'wpcom_5??' :
3904
		case 'wpcom_bad_response' :
3905
		case 'wpcom_outage' :
3906
			$this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack.  Please try again later.', 'jetpack' );
3907
			break;
3908
		case 'register_http_request_failed' :
3909
		case 'token_http_request_failed' :
3910
			$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>" );
3911
			break;
3912
		default :
3913
			if ( empty( $error ) ) {
3914
				break;
3915
			}
3916
			$error = trim( substr( strip_tags( $error ), 0, 20 ) );
3917
			// no break: fall through
3918
		case 'no_role' :
3919
		case 'no_cap' :
3920
		case 'no_code' :
3921
		case 'no_state' :
3922
		case 'invalid_state' :
3923
		case 'invalid_request' :
3924
		case 'invalid_scope' :
3925
		case 'unsupported_response_type' :
3926
		case 'invalid_token' :
3927
		case 'no_token' :
3928
		case 'missing_secrets' :
3929
		case 'home_missing' :
3930
		case 'siteurl_missing' :
3931
		case 'gmt_offset_missing' :
3932
		case 'site_name_missing' :
3933
		case 'secret_1_missing' :
3934
		case 'secret_2_missing' :
3935
		case 'site_lang_missing' :
3936
		case 'home_malformed' :
3937
		case 'siteurl_malformed' :
3938
		case 'gmt_offset_malformed' :
3939
		case 'timezone_string_malformed' :
3940
		case 'site_name_malformed' :
3941
		case 'secret_1_malformed' :
3942
		case 'secret_2_malformed' :
3943
		case 'site_lang_malformed' :
3944
		case 'secrets_mismatch' :
3945
		case 'verify_secret_1_missing' :
3946
		case 'verify_secret_1_malformed' :
3947
		case 'verify_secrets_missing' :
3948
		case 'verify_secrets_mismatch' :
3949
			$error = esc_html( $error );
3950
			$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>" );
3951
			if ( ! Jetpack::is_active() ) {
3952
				$this->error .= '<br />';
3953
				$this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
3954
			}
3955
			break;
3956
		}
3957
3958
		$message_code = Jetpack::state( 'message' );
3959
3960
		$active_state = Jetpack::state( 'activated_modules' );
3961
		if ( ! empty( $active_state ) ) {
3962
			$available    = Jetpack::get_available_modules();
3963
			$active_state = explode( ',', $active_state );
3964
			$active_state = array_intersect( $active_state, $available );
3965
			if ( count( $active_state ) ) {
3966
				foreach ( $active_state as $mod ) {
3967
					$this->stat( 'module-activated', $mod );
3968
				}
3969
			} else {
3970
				$active_state = false;
3971
			}
3972
		}
3973
		if( Jetpack::state( 'optin-manage' ) ) {
3974
			$activated_manage = $message_code;
3975
			$message_code = 'jetpack-manage';
3976
3977
		}
3978
		switch ( $message_code ) {
3979
		case 'modules_activated' :
3980
			$this->message = sprintf(
3981
				__( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
3982
				JETPACK__VERSION
3983
			);
3984
3985
			if ( $active_state ) {
3986
				$titles = array();
3987 View Code Duplication
				foreach ( $active_state as $mod ) {
3988
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
3989
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
3990
					}
3991
				}
3992
				if ( $titles ) {
3993
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
3994
				}
3995
			}
3996
3997
			if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
3998
				$titles = array();
3999 View Code Duplication
				foreach ( explode( ',',  $reactive_state ) as $mod ) {
4000
					if ( $mod_headers = Jetpack::get_module( $mod ) ) {
4001
						$titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
4002
					}
4003
				}
4004
				if ( $titles ) {
4005
					$this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
4006
				}
4007
			}
4008
4009
			$this->message .= Jetpack::jetpack_comment_notice();
4010
			break;
4011
		case 'jetpack-manage':
4012
			$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>';
4013
			if ( $activated_manage ) {
4014
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4015
			}
4016
			break;
4017
		case 'module_activated' :
4018
			if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
4019
				$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'] );
4020
				$this->stat( 'module-activated', Jetpack::state( 'module' ) );
4021
			}
4022
			break;
4023
4024
		case 'module_deactivated' :
4025
			$modules = Jetpack::state( 'module' );
4026
			if ( ! $modules ) {
4027
				break;
4028
			}
4029
4030
			$module_names = array();
4031
			foreach ( explode( ',', $modules ) as $module_slug ) {
4032
				$module = Jetpack::get_module( $module_slug );
4033
				if ( $module ) {
4034
					$module_names[] = $module['name'];
4035
				}
4036
4037
				$this->stat( 'module-deactivated', $module_slug );
4038
			}
4039
4040
			if ( ! $module_names ) {
4041
				break;
4042
			}
4043
4044
			$this->message = wp_sprintf(
4045
				_nx(
4046
					'<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
4047
					'<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
4048
					count( $module_names ),
4049
					'%l = list of Jetpack module/feature names',
4050
					'jetpack'
4051
				),
4052
				$module_names
4053
			);
4054
			break;
4055
4056
		case 'module_configured' :
4057
			$this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
4058
			break;
4059
4060
		case 'already_authorized' :
4061
			$this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
4062
			break;
4063
4064
		case 'authorized' :
4065
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go, Jetpack is now active.</strong> ', 'jetpack' );
4066
			$this->message .= Jetpack::jetpack_comment_notice();
4067
			break;
4068
4069
		case 'linked' :
4070
			$this->message  = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
4071
			$this->message .= Jetpack::jetpack_comment_notice();
4072
			break;
4073
4074
		case 'unlinked' :
4075
			$user = wp_get_current_user();
4076
			$this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
4077
			break;
4078
4079
		case 'switch_master' :
4080
			global $current_user;
4081
			$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
4082
			$master_userdata = get_userdata( Jetpack_Options::get_option( 'master_user' ) );
4083
			if ( $is_master_user ) {
4084
				$this->message = __( 'You have successfully set yourself as Jetpack’s primary user.', 'jetpack' );
4085
			} else {
4086
				$this->message = sprintf( _x( 'You have successfully set %s as Jetpack’s primary user.', '%s is a username', 'jetpack' ), $master_userdata->user_login );
4087
			}
4088
			break;
4089
		}
4090
4091
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4092
4093
		if ( ! empty( $deactivated_plugins ) ) {
4094
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4095
			$deactivated_titles  = array();
4096
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4097
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4098
					continue;
4099
				}
4100
4101
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4102
			}
4103
4104
			if ( $deactivated_titles ) {
4105
				if ( $this->message ) {
4106
					$this->message .= "<br /><br />\n";
4107
				}
4108
4109
				$this->message .= wp_sprintf(
4110
					_n(
4111
						'Jetpack contains the most recent version of the old %l plugin.',
4112
						'Jetpack contains the most recent versions of the old %l plugins.',
4113
						count( $deactivated_titles ),
4114
						'jetpack'
4115
					),
4116
					$deactivated_titles
4117
				);
4118
4119
				$this->message .= "<br />\n";
4120
4121
				$this->message .= _n(
4122
					'The old version has been deactivated and can be removed from your site.',
4123
					'The old versions have been deactivated and can be removed from your site.',
4124
					count( $deactivated_titles ),
4125
					'jetpack'
4126
				);
4127
			}
4128
		}
4129
4130
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4131
4132
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4133
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4134
		}
4135
4136 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4137
			/**
4138
			 * Fires when a module configuration page is loaded.
4139
			 * The dynamic part of the hook is the configure parameter from the URL.
4140
			 *
4141
			 * @since 1.1.0
4142
			 */
4143
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4144
		}
4145
4146
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4147
	}
4148
4149
	function admin_notices() {
4150
4151
		if ( $this->error ) {
4152
?>
4153
<div id="message" class="jetpack-message jetpack-err">
4154
	<div class="squeezer">
4155
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4156
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4157
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4158
<?php	endif; ?>
4159
	</div>
4160
</div>
4161
<?php
4162
		}
4163
4164
		if ( $this->message ) {
4165
?>
4166
<div id="message" class="jetpack-message">
4167
	<div class="squeezer">
4168
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4169
	</div>
4170
</div>
4171
<?php
4172
		}
4173
4174
		if ( $this->privacy_checks ) :
4175
			$module_names = $module_slugs = array();
4176
4177
			$privacy_checks = explode( ',', $this->privacy_checks );
4178
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4179
			foreach ( $privacy_checks as $module_slug ) {
4180
				$module = Jetpack::get_module( $module_slug );
4181
				if ( ! $module ) {
4182
					continue;
4183
				}
4184
4185
				$module_slugs[] = $module_slug;
4186
				$module_names[] = "<strong>{$module['name']}</strong>";
4187
			}
4188
4189
			$module_slugs = join( ',', $module_slugs );
4190
?>
4191
<div id="message" class="jetpack-message jetpack-err">
4192
	<div class="squeezer">
4193
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4194
		<p><?php
4195
			echo wp_kses(
4196
				wptexturize(
4197
					wp_sprintf(
4198
						_nx(
4199
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4200
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4201
							count( $privacy_checks ),
4202
							'%l = list of Jetpack module/feature names',
4203
							'jetpack'
4204
						),
4205
						$module_names
4206
					)
4207
				),
4208
				array( 'strong' => true )
4209
			);
4210
4211
			echo "\n<br />\n";
4212
4213
			echo wp_kses(
4214
				sprintf(
4215
					_nx(
4216
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4217
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4218
						count( $privacy_checks ),
4219
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4220
						'jetpack'
4221
					),
4222
					wp_nonce_url(
4223
						Jetpack::admin_url(
4224
							array(
4225
								'page'   => 'jetpack',
4226
								'action' => 'deactivate',
4227
								'module' => urlencode( $module_slugs ),
4228
							)
4229
						),
4230
						"jetpack_deactivate-$module_slugs"
4231
					),
4232
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4233
				),
4234
				array( 'a' => array( 'href' => true, 'title' => true ) )
4235
			);
4236
		?></p>
4237
	</div>
4238
</div>
4239
<?php endif;
4240
	// only display the notice if the other stuff is not there
4241
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4242
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4243
			$this->opt_in_jetpack_manage_notice();
4244
		}
4245
	}
4246
4247
	/**
4248
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4249
	 */
4250
	function stat( $group, $detail ) {
4251
		if ( ! isset( $this->stats[ $group ] ) )
4252
			$this->stats[ $group ] = array();
4253
		$this->stats[ $group ][] = $detail;
4254
	}
4255
4256
	/**
4257
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4258
	 */
4259
	function do_stats( $method = '' ) {
4260
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4261
			foreach ( $this->stats as $group => $stats ) {
4262
				if ( is_array( $stats ) && count( $stats ) ) {
4263
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4264
					if ( 'server_side' === $method ) {
4265
						self::do_server_side_stat( $args );
4266
					} else {
4267
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4268
					}
4269
				}
4270
				unset( $this->stats[ $group ] );
4271
			}
4272
		}
4273
	}
4274
4275
	/**
4276
	 * Runs stats code for a one-off, server-side.
4277
	 *
4278
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4279
	 *
4280
	 * @return bool If it worked.
4281
	 */
4282
	static function do_server_side_stat( $args ) {
4283
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4284
		if ( is_wp_error( $response ) )
4285
			return false;
4286
4287
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4288
			return false;
4289
4290
		return true;
4291
	}
4292
4293
	/**
4294
	 * Builds the stats url.
4295
	 *
4296
	 * @param $args array|string The arguments to append to the URL.
4297
	 *
4298
	 * @return string The URL to be pinged.
4299
	 */
4300
	static function build_stats_url( $args ) {
4301
		$defaults = array(
4302
			'v'    => 'wpcom2',
4303
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4304
		);
4305
		$args     = wp_parse_args( $args, $defaults );
4306
		/**
4307
		 * Filter the URL used as the Stats tracking pixel.
4308
		 *
4309
		 * @since 2.3.2
4310
		 *
4311
		 * @param string $url Base URL used as the Stats tracking pixel.
4312
		 */
4313
		$base_url = apply_filters(
4314
			'jetpack_stats_base_url',
4315
			set_url_scheme( 'http://pixel.wp.com/g.gif' )
4316
		);
4317
		$url      = add_query_arg( $args, $base_url );
4318
		return $url;
4319
	}
4320
4321
	function translate_current_user_to_role() {
4322
		foreach ( $this->capability_translations as $role => $cap ) {
4323
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4324
				return $role;
4325
			}
4326
		}
4327
4328
		return false;
4329
	}
4330
4331
	function translate_role_to_cap( $role ) {
4332
		if ( ! isset( $this->capability_translations[$role] ) ) {
4333
			return false;
4334
		}
4335
4336
		return $this->capability_translations[$role];
4337
	}
4338
4339
	function sign_role( $role ) {
4340
		if ( ! $user_id = (int) get_current_user_id() ) {
4341
			return false;
4342
		}
4343
4344
		$token = Jetpack_Data::get_access_token();
4345
		if ( ! $token || is_wp_error( $token ) ) {
4346
			return false;
4347
		}
4348
4349
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4350
	}
4351
4352
4353
	/**
4354
	 * Builds a URL to the Jetpack connection auth page
4355
	 *
4356
	 * @since 3.9.5
4357
	 *
4358
	 * @param bool $raw If true, URL will not be escaped.
4359
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4360
	 *                              If string, will be a custom redirect.
4361
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4362
	 *
4363
	 * @return string Connect URL
4364
	 */
4365
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4366
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4367
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4368
			if( is_network_admin() ) {
4369
			    $url = add_query_arg( 'is_multisite', network_admin_url(
4370
			    'admin.php?page=jetpack-settings' ), $url );
4371
			}
4372
		} else {
4373
			require_once JETPACK__GLOTPRESS_LOCALES_PATH;
4374
			$role = $this->translate_current_user_to_role();
4375
			$signed_role = $this->sign_role( $role );
4376
4377
			$user = wp_get_current_user();
4378
4379
			$redirect = $redirect ? esc_url_raw( $redirect ) : esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4380
4381
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4382
4383
			if( isset( $_REQUEST['is_multisite'] ) ) {
4384
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4385
			}
4386
4387
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4388
			@list( $secret ) = explode( ':', $secrets );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

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