Completed
Push — add/sync-action ( 9c2804...6a3641 )
by
unknown
192:45 queued 183:25
created

class.jetpack.php (12 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
			if ( did_action( 'plugins_loaded' ) )
311
				self::plugin_textdomain();
312
			else
313
				add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
314
315
			self::$instance = new Jetpack;
316
317
			self::$instance->plugin_upgrade();
318
319
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
320
321
		}
322
323
		return self::$instance;
324
	}
325
326
	/**
327
	 * Must never be called statically
328
	 */
329
	function plugin_upgrade() {
330
		if ( Jetpack::is_active() ) {
331
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
332
			if ( JETPACK__VERSION != $version ) {
333
334
				// Check which active modules actually exist and remove others from active_modules list
335
				$unfiltered_modules = Jetpack::get_active_modules();
336
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
337
				if ( array_diff( $unfiltered_modules, $modules ) ) {
338
					Jetpack_Options::update_option( 'active_modules', $modules );
339
				}
340
341
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
342
				/**
343
				 * Fires when synchronizing all registered options and constants.
344
				 *
345
				 * @since 3.3.0
346
				 */
347
				do_action( 'jetpack_sync_all_registered_options' );
348
			}
349
		}
350
	}
351
352
	static function activate_manage( ) {
353
354
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
355
			self::activate_module( 'manage', false, false );
356
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
357
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
358
		}
359
360
	}
361
362
	/**
363
	 * Constructor.  Initializes WordPress hooks
364
	 */
365
	private function __construct() {
366
		/*
367
		 * Check for and alert any deprecated hooks
368
		 */
369
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
370
371
		/**
372
		 * Trigger a wp_version sync when updating WP versions
373
		 **/
374
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
375
376
		/*
377
		 * Load things that should only be in Network Admin.
378
		 *
379
		 * For now blow away everything else until a more full
380
		 * understanding of what is needed at the network level is
381
		 * available
382
		 */
383
		if( is_multisite() ) {
384
			Jetpack_Network::init();
385
		}
386
387
		// Unlink user before deleting the user from .com
388
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
389
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
390
391
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
392
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
393
394
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
395
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
396
397
			$this->require_jetpack_authentication();
398
399
			if ( Jetpack::is_active() ) {
400
				// Hack to preserve $HTTP_RAW_POST_DATA
401
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
402
403
				$signed = $this->verify_xml_rpc_signature();
404
				if ( $signed && ! is_wp_error( $signed ) ) {
405
					// The actual API methods.
406
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
407
				} else {
408
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
409
					// active Jetpack connection, so that additional users can link their account.
410
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
411
				}
412
			} else {
413
				// The bootstrap API methods.
414
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
415
			}
416
417
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
418
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
419
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
420
			$this->require_jetpack_authentication();
421
			$this->add_remote_request_handlers();
422
		} else {
423
			if ( Jetpack::is_active() ) {
424
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
425
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
426
			}
427
		}
428
429
		if ( Jetpack::is_active() ) {
430
			Jetpack_Heartbeat::init();
431
		}
432
433
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
434
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
435
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
436
		}
437
438
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
439
440
		add_action( 'admin_init', array( $this, 'admin_init' ) );
441
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
442
443
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
444
445
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
446
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
447
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
448
449
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
450
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
451
452
		// Jump Start AJAX callback function
453
		add_action( 'wp_ajax_jetpack_jumpstart_ajax',  array( $this, 'jetpack_jumpstart_ajax_callback' ) );
454
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
455
456
		// Identity Crisis AJAX callback function
457
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
458
459
		// JITM AJAX callback function
460
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
461
462
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
463
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
464
465
		// Universal ajax callback for all tracking events triggered via js
466
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
467
468
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
469
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
470
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
471
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
472
473
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
474
475
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
476
477
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
478
479
		/**
480
		 * These actions run checks to load additional files.
481
		 * They check for external files or plugins, so they need to run as late as possible.
482
		 */
483
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
484
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
485
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
486
487
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
488
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
489
490
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
491
492
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
493
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
494
495
		// A filter to control all just in time messages
496
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
497
498
		/**
499
		 * This is the hack to concatinate all css files into one.
500
		 * For description and reasoning see the implode_frontend_css method
501
		 *
502
		 * Super late priority so we catch all the registered styles
503
		 */
504
		if( !is_admin() ) {
505
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
506
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
507
		}
508
509
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
510
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
511
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
512
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
513
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
514
515
	}
516
517
	/*
518
	 * Make sure any site icon added to core can get
519
	 * synced back to dotcom, so we can display it there.
520
	 */
521 View Code Duplication
	function jetpack_sync_core_icon() {
522
		if ( function_exists( 'get_site_icon_url' ) ) {
523
			$url = get_site_icon_url();
524
		} else {
525
			return;
526
		}
527
528
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
529
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
530
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
531
			// This is the option that is synced with dotcom
532
			Jetpack_Options::update_option( 'site_icon_url', $url );
533
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
534
			Jetpack_Options::delete_option( 'site_icon_url' );
535
		}
536
	}
537
538
	function jetpack_admin_ajax_tracks_callback() {
539
		// Check for nonce
540
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
541
			wp_die( 'Permissions check failed.' );
542
		}
543
544
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
545
			wp_die( 'No valid event name or type.' );
546
		}
547
548
		$tracks_data = array();
549
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
550
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
551
		}
552
553
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
554
		wp_send_json_success();
555
		wp_die();
556
	}
557
558
	function jetpack_admin_ajax_callback() {
559
		// Check for nonce
560 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
561
			wp_die( 'permissions check failed' );
562
		}
563
564
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
565
			$slug = $_REQUEST['thisModuleSlug'];
566
567
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
568
				wp_die( 'That is not a Jetpack module slug' );
569
			}
570
571
			if ( Jetpack::is_module_active( $slug ) ) {
572
				Jetpack::deactivate_module( $slug );
573
			} else {
574
				Jetpack::activate_module( $slug, false, false );
575
			}
576
577
			$modules = Jetpack_Admin::init()->get_modules();
578
			echo json_encode( $modules[ $slug ] );
579
580
			exit;
581
		}
582
583
		wp_die();
584
	}
585
586
	/*
587
	 * Sometimes we need to refresh the data,
588
	 * especially if the page is visited via a 'history'
589
	 * event like back/forward
590
	 */
591
	function jetpack_admin_ajax_refresh_data() {
592
		// Check for nonce
593 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
594
			wp_die( 'permissions check failed' );
595
		}
596
597
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
598
			$modules = Jetpack_Admin::init()->get_modules();
599
			echo json_encode( $modules );
600
			exit;
601
		}
602
603
		wp_die();
604
	}
605
606
	/**
607
	 * The callback for the Jump Start ajax requests.
608
	 */
609
	function jetpack_jumpstart_ajax_callback() {
610
		// Check for nonce
611
		if ( ! isset( $_REQUEST['jumpstartNonce'] ) || ! wp_verify_nonce( $_REQUEST['jumpstartNonce'], 'jetpack-jumpstart-nonce' ) )
612
			wp_die( 'permissions check failed' );
613
614
		if ( isset( $_REQUEST['jumpStartActivate'] ) && 'jump-start-activate' == $_REQUEST['jumpStartActivate'] ) {
615
			// Update the jumpstart option
616
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
617
				Jetpack_Options::update_option( 'jumpstart', 'jumpstart_activated' );
618
			}
619
620
			// Loops through the requested "Jump Start" modules, and activates them.
621
			// Custom 'no_message' state, so that no message will be shown on reload.
622
			$modules = $_REQUEST['jumpstartModSlug'];
623
			$module_slugs = array();
624
			foreach( $modules as $module => $value ) {
625
				$module_slugs[] = $value['module_slug'];
626
			}
627
628
			// Check for possible conflicting plugins
629
			$module_slugs_filtered = $this->filter_default_modules( $module_slugs );
630
631
			foreach ( $module_slugs_filtered as $module_slug ) {
632
				Jetpack::log( 'activate', $module_slug );
633
				Jetpack::activate_module( $module_slug, false, false );
634
				Jetpack::state( 'message', 'no_message' );
635
			}
636
637
			// Set the default sharing buttons and set to display on posts if none have been set.
638
			$sharing_services = get_option( 'sharing-services' );
639
			$sharing_options  = get_option( 'sharing-options' );
640
			if ( empty( $sharing_services['visible'] ) ) {
641
				// Default buttons to set
642
				$visible = array(
643
					'twitter',
644
					'facebook',
645
					'google-plus-1',
646
				);
647
				$hidden = array();
648
649
				// Set some sharing settings
650
				$sharing = new Sharing_Service();
651
				$sharing_options['global'] = array(
652
					'button_style'  => 'icon',
653
					'sharing_label' => $sharing->default_sharing_label,
654
					'open_links'    => 'same',
655
					'show'          => array( 'post' ),
656
					'custom'        => isset( $sharing_options['global']['custom'] ) ? $sharing_options['global']['custom'] : array()
657
				);
658
659
				update_option( 'sharing-options', $sharing_options );
660
661
				// Send a success response so that we can display an error message.
662
				$success = update_option( 'sharing-services', array( 'visible' => $visible, 'hidden' => $hidden ) );
663
				echo json_encode( $success );
664
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method jetpack_jumpstart_ajax_callback() contains an exit expression.

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

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

Loading history...
665
			}
666
667
		} elseif ( isset( $_REQUEST['disableJumpStart'] ) && true == $_REQUEST['disableJumpStart'] ) {
668
			// If dismissed, flag the jumpstart option as such.
669
			// Send a success response so that we can display an error message.
670
			if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
671
				$success = Jetpack_Options::update_option( 'jumpstart', 'jumpstart_dismissed' );
672
				echo json_encode( $success );
673
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method jetpack_jumpstart_ajax_callback() contains an exit expression.

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

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

Loading history...
674
			}
675
676
		} elseif ( isset( $_REQUEST['jumpStartDeactivate'] ) && 'jump-start-deactivate' == $_REQUEST['jumpStartDeactivate'] ) {
677
678
			// FOR TESTING ONLY
679
			// @todo remove
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
680
			$modules = (array) $_REQUEST['jumpstartModSlug'];
681
			foreach( $modules as $module => $value ) {
682
				if ( !in_array( $value['module_slug'], Jetpack::get_default_modules() ) ) {
683
					Jetpack::log( 'deactivate', $value['module_slug'] );
684
					Jetpack::deactivate_module( $value['module_slug'] );
685
					Jetpack::state( 'message', 'no_message' );
686
				} else {
687
					Jetpack::log( 'activate', $value['module_slug'] );
688
					Jetpack::activate_module( $value['module_slug'], false, false );
689
					Jetpack::state( 'message', 'no_message' );
690
				}
691
			}
692
693
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
694
			echo "reload the page";
695
		}
696
697
		wp_die();
698
	}
699
700
	/**
701
	 * The callback for the JITM ajax requests.
702
	 */
703
	function jetpack_jitm_ajax_callback() {
704
		// Check for nonce
705
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
706
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
707
		}
708
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
709
			$module_slug = $_REQUEST['jitmModule'];
710
			Jetpack::log( 'activate', $module_slug );
711
			Jetpack::activate_module( $module_slug, false, false );
712
			Jetpack::state( 'message', 'no_message' );
713
714
			//A Jetpack module is being activated through a JITM, track it
715
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
716
			$this->do_stats( 'server_side' );
717
718
			wp_send_json_success();
719
		}
720
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
721
			// get the hide_jitm options array
722
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
723
			$module_slug = $_REQUEST['jitmModule'];
724
725
			if( ! $jetpack_hide_jitm ) {
726
				$jetpack_hide_jitm = array(
727
					$module_slug => 'hide'
728
				);
729
			} else {
730
				$jetpack_hide_jitm[$module_slug] = 'hide';
731
			}
732
733
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
734
735
			//jitm is being dismissed forever, track it
736
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
737
			$this->do_stats( 'server_side' );
738
739
			wp_send_json_success();
740
		}
741 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
742
			$module_slug = $_REQUEST['jitmModule'];
743
744
			// User went to WordPress.com, track this
745
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
746
			$this->do_stats( 'server_side' );
747
748
			wp_send_json_success();
749
		}
750 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
751
			$track = $_REQUEST['jitmModule'];
752
753
			// User is viewing JITM, track it.
754
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
755
			$this->do_stats( 'server_side' );
756
757
			wp_send_json_success();
758
		}
759
	}
760
761
	/**
762
	 * If there are any stats that need to be pushed, but haven't been, push them now.
763
	 */
764
	function __destruct() {
765
		if ( ! empty( $this->stats ) ) {
766
			$this->do_stats( 'server_side' );
767
		}
768
	}
769
770
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
771
		switch( $cap ) {
772
			case 'jetpack_connect' :
773
			case 'jetpack_reconnect' :
774
				if ( Jetpack::is_development_mode() ) {
775
					$caps = array( 'do_not_allow' );
776
					break;
777
				}
778
				/**
779
				 * Pass through. If it's not development mode, these should match disconnect.
780
				 * Let users disconnect if it's development mode, just in case things glitch.
781
				 */
782
			case 'jetpack_disconnect' :
783
				/**
784
				 * In multisite, can individual site admins manage their own connection?
785
				 *
786
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
787
				 */
788
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
789
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
790
						/**
791
						 * We need to update the option name -- it's terribly unclear which
792
						 * direction the override goes.
793
						 *
794
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
795
						 */
796
						$caps = array( 'do_not_allow' );
797
						break;
798
					}
799
				}
800
801
				$caps = array( 'manage_options' );
802
				break;
803
			case 'jetpack_manage_modules' :
804
			case 'jetpack_activate_modules' :
805
			case 'jetpack_deactivate_modules' :
806
				$caps = array( 'manage_options' );
807
				break;
808
			case 'jetpack_configure_modules' :
809
				$caps = array( 'manage_options' );
810
				break;
811
			case 'jetpack_network_admin_page':
812
			case 'jetpack_network_settings_page':
813
				$caps = array( 'manage_network_plugins' );
814
				break;
815
			case 'jetpack_network_sites_page':
816
				$caps = array( 'manage_sites' );
817
				break;
818
			case 'jetpack_admin_page' :
819
				if ( Jetpack::is_development_mode() ) {
820
					$caps = array( 'manage_options' );
821
					break;
822
				}
823
824
				// Don't ever show to subscribers, but allow access to the page if they're trying to unlink.
825
				if ( ! current_user_can( 'edit_posts' ) ) {
826
					if ( isset( $_GET['redirect'] ) && 'sub-unlink' == $_GET['redirect'] ) {
827
						// We need this in order to unlink the user.
828
						$this->admin_page_load();
829
					}
830
					if ( ! wp_verify_nonce( 'jetpack-unlink' ) ) {
831
						$caps = array( 'do_not_allow' );
832
						break;
833
					}
834
				}
835
836
				if ( ! self::is_active() && ! current_user_can( 'jetpack_connect' ) ) {
837
					$caps = array( 'do_not_allow' );
838
					break;
839
				}
840
				/**
841
				 * Pass through. If it's not development mode, these should match the admin page.
842
				 * Let users disconnect if it's development mode, just in case things glitch.
843
				 */
844
			case 'jetpack_connect_user' :
845
				if ( Jetpack::is_development_mode() ) {
846
					$caps = array( 'do_not_allow' );
847
					break;
848
				}
849
				$caps = array( 'read' );
850
				break;
851
		}
852
		return $caps;
853
	}
854
855
	function require_jetpack_authentication() {
856
		// Don't let anyone authenticate
857
		$_COOKIE = array();
858
		remove_all_filters( 'authenticate' );
859
860
		/**
861
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
862
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
863
		 * generate false-positives.
864
		 */
865
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
866
867
		if ( Jetpack::is_active() ) {
868
			// Allow Jetpack authentication
869
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
870
		}
871
	}
872
873
	/**
874
	 * Load language files
875
	 */
876
	public static function plugin_textdomain() {
877
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
878
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
879
	}
880
881
	/**
882
	 * Register assets for use in various modules and the Jetpack admin page.
883
	 *
884
	 * @uses wp_script_is, wp_register_script, plugins_url
885
	 * @action wp_loaded
886
	 * @return null
887
	 */
888
	public function register_assets() {
889
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
890
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
891
		}
892
893 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
894
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
895
		}
896
897 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
898
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
899
		}
900
901 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
902
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
903
		}
904
905
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
906
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
907
908
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
909
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
910
			if ( ! is_numeric( $fb_app_id ) ) {
911
				$fb_app_id = '';
912
			}
913
			wp_localize_script(
914
				'jetpack-facebook-embed',
915
				'jpfbembed',
916
				array(
917
					'appid' => $fb_app_id,
918
					'locale' => $this->get_locale(),
919
				)
920
			);
921
		}
922
923
		/**
924
		 * As jetpack_register_genericons is by default fired off a hook,
925
		 * the hook may have already fired by this point.
926
		 * So, let's just trigger it manually.
927
		 */
928
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
929
		jetpack_register_genericons();
930
931 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
932
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
933
	}
934
935
	/**
936
	 * Guess locale from language code.
937
	 *
938
	 * @param string $lang Language code.
939
	 * @return string|bool
940
	 */
941 View Code Duplication
	function guess_locale_from_lang( $lang ) {
942
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
943
			return 'en_US';
944
		}
945
946
		if ( ! class_exists( 'GP_Locales' ) ) {
947
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
948
				return false;
949
			}
950
951
			require JETPACK__GLOTPRESS_LOCALES_PATH;
952
		}
953
954
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
955
			// WP.com: get_locale() returns 'it'
956
			$locale = GP_Locales::by_slug( $lang );
957
		} else {
958
			// Jetpack: get_locale() returns 'it_IT';
959
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
960
		}
961
962
		if ( ! $locale ) {
963
			return false;
964
		}
965
966
		if ( empty( $locale->facebook_locale ) ) {
967
			if ( empty( $locale->wp_locale ) ) {
968
				return false;
969
			} else {
970
				// Facebook SDK is smart enough to fall back to en_US if a
971
				// locale isn't supported. Since supported Facebook locales
972
				// can fall out of sync, we'll attempt to use the known
973
				// wp_locale value and rely on said fallback.
974
				return $locale->wp_locale;
975
			}
976
		}
977
978
		return $locale->facebook_locale;
979
	}
980
981
	/**
982
	 * Get the locale.
983
	 *
984
	 * @return string|bool
985
	 */
986
	function get_locale() {
987
		$locale = $this->guess_locale_from_lang( get_locale() );
988
989
		if ( ! $locale ) {
990
			$locale = 'en_US';
991
		}
992
993
		return $locale;
994
	}
995
996
	/**
997
	 * Device Pixels support
998
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
999
	 */
1000
	function devicepx() {
1001
		if ( Jetpack::is_active() ) {
1002
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
1003
		}
1004
	}
1005
1006
	/**
1007
	 * Return the network_site_url so that .com knows what network this site is a part of.
1008
	 * @param  bool $option
1009
	 * @return string
1010
	 */
1011
	public function jetpack_main_network_site_option( $option ) {
1012
		return network_site_url();
1013
	}
1014
	/**
1015
	 * Network Name.
1016
	 */
1017
	static function network_name( $option = null ) {
1018
		global $current_site;
1019
		return $current_site->site_name;
1020
	}
1021
	/**
1022
	 * Does the network allow new user and site registrations.
1023
	 * @return string
1024
	 */
1025
	static function network_allow_new_registrations( $option = null ) {
1026
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1027
	}
1028
	/**
1029
	 * Does the network allow admins to add new users.
1030
	 * @return boolian
1031
	 */
1032
	static function network_add_new_users( $option = null ) {
1033
		return (bool) get_site_option( 'add_new_users' );
1034
	}
1035
	/**
1036
	 * File upload psace left per site in MB.
1037
	 *  -1 means NO LIMIT.
1038
	 * @return number
1039
	 */
1040
	static function network_site_upload_space( $option = null ) {
1041
		// value in MB
1042
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1043
	}
1044
1045
	/**
1046
	 * Network allowed file types.
1047
	 * @return string
1048
	 */
1049
	static function network_upload_file_types( $option = null ) {
1050
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1051
	}
1052
1053
	/**
1054
	 * Maximum file upload size set by the network.
1055
	 * @return number
1056
	 */
1057
	static function network_max_upload_file_size( $option = null ) {
1058
		// value in KB
1059
		return get_site_option( 'fileupload_maxk', 300 );
1060
	}
1061
1062
	/**
1063
	 * Lets us know if a site allows admins to manage the network.
1064
	 * @return array
1065
	 */
1066
	static function network_enable_administration_menus( $option = null ) {
1067
		return get_site_option( 'menu_items' );
1068
	}
1069
1070
	/**
1071
	 * Return whether we are dealing with a multi network setup or not.
1072
	 * The reason we are type casting this is because we want to avoid the situation where
1073
	 * the result is false since when is_main_network_option return false it cases
1074
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1075
	 * database which could be set to anything as opposed to what this function returns.
1076
	 * @param  bool  $option
1077
	 *
1078
	 * @return boolean
1079
	 */
1080
	public function is_main_network_option( $option ) {
1081
		// return '1' or ''
1082
		return (string) (bool) Jetpack::is_multi_network();
1083
	}
1084
1085
	/**
1086
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1087
	 *
1088
	 * @param  string  $option
1089
	 * @return boolean
1090
	 */
1091
	public function is_multisite( $option ) {
1092
		return (string) (bool) is_multisite();
1093
	}
1094
1095
	/**
1096
	 * Implemented since there is no core is multi network function
1097
	 * Right now there is no way to tell if we which network is the dominant network on the system
1098
	 *
1099
	 * @since  3.3
1100
	 * @return boolean
1101
	 */
1102
	public static function is_multi_network() {
1103
		global  $wpdb;
1104
1105
		// if we don't have a multi site setup no need to do any more
1106
		if ( ! is_multisite() ) {
1107
			return false;
1108
		}
1109
1110
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1111
		if ( $num_sites > 1 ) {
1112
			return true;
1113
		} else {
1114
			return false;
1115
		}
1116
	}
1117
1118
	/**
1119
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1120
	 * @return null
1121
	 */
1122
	function update_jetpack_main_network_site_option() {
1123
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1124
		/**
1125
		 * Fires when the site URL is updated.
1126
		 * Determines if the site is the main site of a Mulitiste network.
1127
		 *
1128
		 * @since 3.3.0
1129
		 *
1130
		 * @param string jetpack_main_network_site.
1131
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1132
		 */
1133
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1134
		/**
1135
		 * Fires when the site URL is updated.
1136
		 * Determines if the is part of a multi network.
1137
		 *
1138
		 * @since 3.3.0
1139
		 *
1140
		 * @param string jetpack_is_main_network.
1141
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1142
		 */
1143
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1144
		/**
1145
		 * Fires when the site URL is updated.
1146
		 * Determines if the site is part of a multisite network.
1147
		 *
1148
		 * @since 3.4.0
1149
		 *
1150
		 * @param string jetpack_is_multi_site.
1151
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1152
		 */
1153
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1154
	}
1155
	/**
1156
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1157
	 *
1158
	 */
1159
	function update_jetpack_network_settings() {
1160
		// Only sync this info for the main network site.
1161
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1162
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1163
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1164
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1165
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1166
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1167
1168
	}
1169
1170
	/**
1171
	 * Get back if the current site is single user site.
1172
	 *
1173
	 * @return bool
1174
	 */
1175
	public static function is_single_user_site() {
1176
1177
		$user_query = new WP_User_Query( array(
1178
			'blog_id' => get_current_blog_id(),
1179
			'fields'  => 'ID',
1180
			'number' => 2
1181
		) );
1182
		return 1 === (int) $user_query->get_total();
1183
	}
1184
1185
	/**
1186
	 * Returns true if the site has file write access false otherwise.
1187
	 * @return string ( '1' | '0' )
1188
	 **/
1189 View Code Duplication
	public static function file_system_write_access() {
1190
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1191
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1192
		}
1193
1194
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1195
1196
		$filesystem_method = get_filesystem_method();
1197
		if ( $filesystem_method === 'direct' ) {
1198
			return 1;
1199
		}
1200
1201
		ob_start();
1202
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1203
		ob_end_clean();
1204
		if ( $filesystem_credentials_are_stored ) {
1205
			return 1;
1206
		}
1207
		return 0;
1208
	}
1209
1210
	/**
1211
	 * Finds out if a site is using a version control system.
1212
	 * @return string ( '1' | '0' )
1213
	 **/
1214 View Code Duplication
	public static function is_version_controlled() {
1215
1216
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1217
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1218
		}
1219
		$updater = new WP_Automatic_Updater();
1220
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1221
		// transients should not be empty
1222
		if ( empty( $is_version_controlled ) ) {
1223
			$is_version_controlled = '0';
1224
		}
1225
		return $is_version_controlled;
1226
	}
1227
1228
	/**
1229
	 * Determines whether the current theme supports featured images or not.
1230
	 * @return string ( '1' | '0' )
1231
	 */
1232
	public static function featured_images_enabled() {
1233
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1234
	}
1235
1236
	/*
1237
	 * Sync back wp_version
1238
	 */
1239
	public static function get_wp_version() {
1240
		global $wp_version;
1241
		return $wp_version;
1242
	}
1243
1244
	/**
1245
	 * Keeps wp_version in sync with .com when WordPress core updates
1246
	 **/
1247
	public static function update_get_wp_version( $update, $meta_data ) {
1248
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1249
			/** This action is documented in wp-includes/option.php */
1250
			/**
1251
			 * This triggers the sync for the jetpack version
1252
			 * See Jetpack_Sync options method for more info.
1253
			 */
1254
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1255
		}
1256
	}
1257
1258
	/**
1259
	 * jetpack_updates is saved in the following schema:
1260
	 *
1261
	 * array (
1262
	 *      'plugins'                       => (int) Number of plugin updates available.
1263
	 *      'themes'                        => (int) Number of theme updates available.
1264
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1265
	 *      'translations'                  => (int) Number of translation updates available.
1266
	 *      'total'                         => (int) Total of all available updates.
1267
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1268
	 * )
1269
	 * @return array
1270
	 */
1271
	public static function get_updates() {
1272
		$update_data = wp_get_update_data();
1273
1274
		// Stores the individual update counts as well as the total count.
1275
		if ( isset( $update_data['counts'] ) ) {
1276
			$updates = $update_data['counts'];
1277
		}
1278
1279
		// If we need to update WordPress core, let's find the latest version number.
1280 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1281
			$cur = get_preferred_from_update_core();
1282
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1283
				$updates['wp_update_version'] = $cur->current;
1284
			}
1285
		}
1286
		return isset( $updates ) ? $updates : array();
1287
	}
1288
1289
	public static function get_update_details() {
1290
		$update_details = array(
1291
			'update_core' => get_site_transient( 'update_core' ),
1292
			'update_plugins' => get_site_transient( 'update_plugins' ),
1293
			'update_themes' => get_site_transient( 'update_themes' ),
1294
		);
1295
		return $update_details;
1296
	}
1297
1298
	public static function refresh_update_data() {
1299
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1300
			/**
1301
			 * Fires whenever the amount of updates needed for a site changes.
1302
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1303
			 *
1304
			 * @since 3.7.0
1305
			 *
1306
			 * @param string jetpack_updates
1307
			 * @param array Update counts calculated by Jetpack::get_updates
1308
			 */
1309
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1310
		}
1311
		/**
1312
		 * Fires whenever the amount of updates needed for a site changes.
1313
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1314
		 *
1315
		 * @since 3.7.0
1316
		 *
1317
		 * @param string jetpack_update_details
1318
		 * @param array Update details calculated by Jetpack::get_update_details
1319
		 */
1320
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1321
	}
1322
1323
	public static function refresh_theme_data() {
1324
		/**
1325
		 * Fires whenever a theme change is made.
1326
		 *
1327
		 * @since 3.8.1
1328
		 *
1329
		 * @param string featured_images_enabled
1330
		 * @param boolean Whether featured images are enabled or not
1331
		 */
1332
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1333
	}
1334
1335
	/**
1336
	 * Is Jetpack active?
1337
	 */
1338
	public static function is_active() {
1339
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1340
	}
1341
1342
	/**
1343
	 * Is Jetpack in development (offline) mode?
1344
	 */
1345
	public static function is_development_mode() {
1346
		$development_mode = false;
1347
1348
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1349
			$development_mode = JETPACK_DEV_DEBUG;
1350
		}
1351
1352
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1353
			$development_mode = true;
1354
		}
1355
		/**
1356
		 * Filters Jetpack's development mode.
1357
		 *
1358
		 * @see http://jetpack.com/support/development-mode/
1359
		 *
1360
		 * @since 2.2.1
1361
		 *
1362
		 * @param bool $development_mode Is Jetpack's development mode active.
1363
		 */
1364
		return apply_filters( 'jetpack_development_mode', $development_mode );
1365
	}
1366
1367
	/**
1368
	* Get Jetpack development mode notice text and notice class.
1369
	*
1370
	* Mirrors the checks made in Jetpack::is_development_mode
1371
	*
1372
	*/
1373
	public static function show_development_mode_notice() {
1374
		if ( Jetpack::is_development_mode() ) {
1375
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1376
				$notice = sprintf(
1377
					/* translators: %s is a URL */
1378
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1379
					'http://jetpack.com/support/development-mode/'
1380
				);
1381
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1382
				$notice = sprintf(
1383
					/* translators: %s is a URL */
1384
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1385
					'http://jetpack.com/support/development-mode/'
1386
				);
1387
			} else {
1388
				$notice = sprintf(
1389
					/* translators: %s is a URL */
1390
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1391
					'http://jetpack.com/support/development-mode/'
1392
				);
1393
			}
1394
1395
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1396
		}
1397
1398
		// Throw up a notice if using a development version and as for feedback.
1399
		if ( Jetpack::is_development_version() ) {
1400
			/* translators: %s is a URL */
1401
			$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/' );
1402
1403
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1404
		}
1405
		// Throw up a notice if using staging mode
1406
		if ( Jetpack::is_staging_site() ) {
1407
			/* translators: %s is a URL */
1408
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1409
1410
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1411
		}
1412
	}
1413
1414
	/**
1415
	 * Whether Jetpack's version maps to a public release, or a development version.
1416
	 */
1417
	public static function is_development_version() {
1418
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1419
	}
1420
1421
	/**
1422
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1423
	 */
1424
	public static function is_user_connected( $user_id = false ) {
1425
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1426
		if ( ! $user_id ) {
1427
			return false;
1428
		}
1429
		return (bool) Jetpack_Data::get_access_token( $user_id );
1430
	}
1431
1432
	/**
1433
	 * Get the wpcom user data of the current|specified connected user.
1434
	 */
1435 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1436
		if ( ! $user_id ) {
1437
			$user_id = get_current_user_id();
1438
		}
1439
		Jetpack::load_xml_rpc_client();
1440
		$xml = new Jetpack_IXR_Client( array(
1441
			'user_id' => $user_id,
1442
		) );
1443
		$xml->query( 'wpcom.getUser' );
1444
		if ( ! $xml->isError() ) {
1445
			return $xml->getResponse();
1446
		}
1447
		return false;
1448
	}
1449
1450
	/**
1451
	 * Get the wpcom email of the current|specified connected user.
1452
	 */
1453 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1454
		if ( ! $user_id ) {
1455
			$user_id = get_current_user_id();
1456
		}
1457
		Jetpack::load_xml_rpc_client();
1458
		$xml = new Jetpack_IXR_Client( array(
1459
			'user_id' => $user_id,
1460
		) );
1461
		$xml->query( 'wpcom.getUserEmail' );
1462
		if ( ! $xml->isError() ) {
1463
			return $xml->getResponse();
1464
		}
1465
		return false;
1466
	}
1467
1468
	/**
1469
	 * Get the wpcom email of the master user.
1470
	 */
1471
	public static function get_master_user_email() {
1472
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1473
		if ( $master_user_id ) {
1474
			return self::get_connected_user_email( $master_user_id );
1475
		}
1476
		return '';
1477
	}
1478
1479
	function current_user_is_connection_owner() {
1480
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1481
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1482
	}
1483
1484
	/**
1485
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1486
	 */
1487
	function extra_oembed_providers() {
1488
		// Cloudup: https://dev.cloudup.com/#oembed
1489
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1490
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1491
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1492
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1493
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1494
	}
1495
1496
	/**
1497
	 * Synchronize connected user role changes
1498
	 */
1499
	function user_role_change( $user_id ) {
1500
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1501
			$current_user_id = get_current_user_id();
1502
			wp_set_current_user( $user_id );
1503
			$role = $this->translate_current_user_to_role();
1504
			$signed_role = $this->sign_role( $role );
1505
			wp_set_current_user( $current_user_id );
1506
1507
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1508
			$master_user_id = absint( $master_token->external_user_id );
1509
1510
			if ( ! $master_user_id )
1511
				return; // this shouldn't happen
1512
1513
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1514
			//@todo retry on failure
1515
1516
			//try to choose a new master if we're demoting the current one
1517 View Code Duplication
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1518
				$query = new WP_User_Query(
1519
					array(
1520
						'fields'  => array( 'id' ),
1521
						'role'    => 'administrator',
1522
						'orderby' => 'id',
1523
						'exclude' => array( $master_user_id ),
1524
					)
1525
				);
1526
				$new_master = false;
1527
				foreach ( $query->results as $result ) {
1528
					$uid = absint( $result->id );
1529
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1530
						$new_master = $uid;
1531
						break;
1532
					}
1533
				}
1534
1535
				if ( $new_master ) {
1536
					Jetpack_Options::update_option( 'master_user', $new_master );
1537
				}
1538
				// else disconnect..?
1539
			}
1540
		}
1541
	}
1542
1543
	/**
1544
	 * Loads the currently active modules.
1545
	 */
1546
	public static function load_modules() {
1547
		if ( ! self::is_active() && !self::is_development_mode() ) {
1548
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1549
				return;
1550
			}
1551
		}
1552
1553
		$version = Jetpack_Options::get_option( 'version' );
1554 View Code Duplication
		if ( ! $version ) {
1555
			$version = $old_version = JETPACK__VERSION . ':' . time();
1556
			/** This action is documented in class.jetpack.php */
1557
			do_action( 'updating_jetpack_version', $version, false );
1558
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1559
		}
1560
		list( $version ) = explode( ':', $version );
1561
1562
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1563
1564
		$modules_data = array();
1565
1566
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1567
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1568
			$updated_modules = array();
1569
			foreach ( $modules as $module ) {
1570
				$modules_data[ $module ] = Jetpack::get_module( $module );
1571
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1572
					continue;
1573
				}
1574
1575
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1576
					continue;
1577
				}
1578
1579
				$updated_modules[] = $module;
1580
			}
1581
1582
			$modules = array_diff( $modules, $updated_modules );
1583
		}
1584
1585
		$is_development_mode = Jetpack::is_development_mode();
1586
1587
		foreach ( $modules as $index => $module ) {
1588
			// If we're in dev mode, disable modules requiring a connection
1589
			if ( $is_development_mode ) {
1590
				// Prime the pump if we need to
1591
				if ( empty( $modules_data[ $module ] ) ) {
1592
					$modules_data[ $module ] = Jetpack::get_module( $module );
1593
				}
1594
				// If the module requires a connection, but we're in local mode, don't include it.
1595
				if ( $modules_data[ $module ]['requires_connection'] ) {
1596
					continue;
1597
				}
1598
			}
1599
1600
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1601
				continue;
1602
			}
1603
1604
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1605
				unset( $modules[ $index ] );
1606
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1607
				continue;
1608
			}
1609
1610
			/**
1611
			 * Fires when a specific module is loaded.
1612
			 * The dynamic part of the hook, $module, is the module slug.
1613
			 *
1614
			 * @since 1.1.0
1615
			 */
1616
			do_action( 'jetpack_module_loaded_' . $module );
1617
		}
1618
1619
		/**
1620
		 * Fires when all the modules are loaded.
1621
		 *
1622
		 * @since 1.1.0
1623
		 */
1624
		do_action( 'jetpack_modules_loaded' );
1625
1626
		// 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.
1627
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1628
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1629
	}
1630
1631
	/**
1632
	 * Check if Jetpack's REST API compat file should be included
1633
	 * @action plugins_loaded
1634
	 * @return null
1635
	 */
1636
	public function check_rest_api_compat() {
1637
		/**
1638
		 * Filters the list of REST API compat files to be included.
1639
		 *
1640
		 * @since 2.2.5
1641
		 *
1642
		 * @param array $args Array of REST API compat files to include.
1643
		 */
1644
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1645
1646
		if ( function_exists( 'bbpress' ) )
1647
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1648
1649
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1650
			require_once $_jetpack_rest_api_compat_include;
1651
	}
1652
1653
	/**
1654
	 * Gets all plugins currently active in values, regardless of whether they're
1655
	 * traditionally activated or network activated.
1656
	 *
1657
	 * @todo Store the result in core's object cache maybe?
1658
	 */
1659
	public static function get_active_plugins() {
1660
		$active_plugins = (array) get_option( 'active_plugins', array() );
1661
1662
		if ( is_multisite() ) {
1663
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1664
			// whereas active_plugins stores them in the values.
1665
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1666
			if ( $network_plugins ) {
1667
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1668
			}
1669
		}
1670
1671
		sort( $active_plugins );
1672
1673
		return array_unique( $active_plugins );
1674
	}
1675
1676
	/**
1677
	 * Gets and parses additional plugin data to send with the heartbeat data
1678
	 *
1679
	 * @since 3.8.1
1680
	 *
1681
	 * @return array Array of plugin data
1682
	 */
1683
	public static function get_parsed_plugin_data() {
1684
		if ( ! function_exists( 'get_plugins' ) ) {
1685
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1686
		}
1687
		$all_plugins    = get_plugins();
1688
		$active_plugins = Jetpack::get_active_plugins();
1689
1690
		$plugins = array();
1691
		foreach ( $all_plugins as $path => $plugin_data ) {
1692
			$plugins[ $path ] = array(
1693
					'is_active' => in_array( $path, $active_plugins ),
1694
					'file'      => $path,
1695
					'name'      => $plugin_data['Name'],
1696
					'version'   => $plugin_data['Version'],
1697
					'author'    => $plugin_data['Author'],
1698
			);
1699
		}
1700
1701
		return $plugins;
1702
	}
1703
1704
	/**
1705
	 * Gets and parses theme data to send with the heartbeat data
1706
	 *
1707
	 * @since 3.8.1
1708
	 *
1709
	 * @return array Array of theme data
1710
	 */
1711
	public static function get_parsed_theme_data() {
1712
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1713
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1714
1715
		$themes = array();
1716
		foreach ( $all_themes as $slug => $theme_data ) {
1717
			$theme_headers = array();
1718
			foreach ( $header_keys as $header_key ) {
1719
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1720
			}
1721
1722
			$themes[ $slug ] = array(
1723
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1724
					'slug' => $slug,
1725
					'theme_root' => $theme_data->get_theme_root_uri(),
1726
					'parent' => $theme_data->parent(),
1727
					'headers' => $theme_headers
1728
			);
1729
		}
1730
1731
		return $themes;
1732
	}
1733
1734
	/**
1735
	 * Checks whether a specific plugin is active.
1736
	 *
1737
	 * We don't want to store these in a static variable, in case
1738
	 * there are switch_to_blog() calls involved.
1739
	 */
1740
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1741
		return in_array( $plugin, self::get_active_plugins() );
1742
	}
1743
1744
	/**
1745
	 * Check if Jetpack's Open Graph tags should be used.
1746
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1747
	 *
1748
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1749
	 * @action plugins_loaded
1750
	 * @return null
1751
	 */
1752
	public function check_open_graph() {
1753
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1754
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1755
		}
1756
1757
		$active_plugins = self::get_active_plugins();
1758
1759
		if ( ! empty( $active_plugins ) ) {
1760
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1761
				if ( in_array( $plugin, $active_plugins ) ) {
1762
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1763
					break;
1764
				}
1765
			}
1766
		}
1767
1768
		/**
1769
		 * Allow the addition of Open Graph Meta Tags to all pages.
1770
		 *
1771
		 * @since 2.0.3
1772
		 *
1773
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1774
		 */
1775
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1776
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1777
		}
1778
	}
1779
1780
	/**
1781
	 * Check if Jetpack's Twitter tags should be used.
1782
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1783
	 *
1784
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1785
	 * @action plugins_loaded
1786
	 * @return null
1787
	 */
1788
	public function check_twitter_tags() {
1789
1790
		$active_plugins = self::get_active_plugins();
1791
1792
		if ( ! empty( $active_plugins ) ) {
1793
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1794
				if ( in_array( $plugin, $active_plugins ) ) {
1795
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1796
					break;
1797
				}
1798
			}
1799
		}
1800
1801
		/**
1802
		 * Allow Twitter Card Meta tags to be disabled.
1803
		 *
1804
		 * @since 2.6.0
1805
		 *
1806
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1807
		 */
1808
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1809
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1810
		}
1811
	}
1812
1813
1814
1815
1816
	/*
1817
	 *
1818
	 * Jetpack Security Reports
1819
	 *
1820
	 * Allowed types: login_form, backup, file_scanning, spam
1821
	 *
1822
	 * 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)
1823
	 *
1824
	 * 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)
1825
	 *
1826
	 *
1827
	 * Example code to submit a security report:
1828
	 *
1829
	 *  function akismet_submit_jetpack_security_report() {
1830
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1831
	 *  }
1832
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1833
	 *
1834
	 */
1835
1836
1837
	/**
1838
	 * Calls for security report submissions.
1839
	 *
1840
	 * @return null
1841
	 */
1842
	public static function perform_security_reporting() {
1843
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1844
1845
		if ( $no_check_needed ) {
1846
			return;
1847
		}
1848
1849
		/**
1850
		 * Fires before a security report is created.
1851
		 *
1852
		 * @since 3.4.0
1853
		 */
1854
		do_action( 'jetpack_security_report' );
1855
1856
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1857
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1858
	}
1859
1860
	/**
1861
	 * Allows plugins to submit security reports.
1862
 	 *
1863
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1864
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1865
	 * @param array   $args         See definitions above
1866
	 */
1867
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1868
1869
		if( !doing_action( 'jetpack_security_report' ) ) {
1870
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1871
		}
1872
1873
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1874
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1875
		}
1876
1877
		if( !function_exists( 'get_plugin_data' ) ) {
1878
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1879
		}
1880
1881
		//Get rid of any non-allowed args
1882
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1883
1884
		$plugin = get_plugin_data( $plugin_file );
1885
1886
		if ( !$plugin['Name'] ) {
1887
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1888
		}
1889
1890
		// Sanitize everything to make sure we're not syncing something wonky
1891
		$type = sanitize_key( $type );
1892
1893
		$args['plugin'] = $plugin;
1894
1895
		// Cast blocked, last and next as integers.
1896
		// Last and next should be in unix timestamp format
1897
		if ( isset( $args['blocked'] ) ) {
1898
			$args['blocked'] = (int) $args['blocked'];
1899
		}
1900
		if ( isset( $args['last'] ) ) {
1901
			$args['last'] = (int) $args['last'];
1902
		}
1903
		if ( isset( $args['next'] ) ) {
1904
			$args['next'] = (int) $args['next'];
1905
		}
1906
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1907
			$args['status'] = 'ok';
1908
		}
1909
		if ( isset( $args['message'] ) ) {
1910
1911
			if( $args['status'] == 'ok' ) {
1912
				unset( $args['message'] );
1913
			}
1914
1915
			$allowed_html = array(
1916
			    'a' => array(
1917
			        'href' => array(),
1918
			        'title' => array()
1919
			    ),
1920
			    'em' => array(),
1921
			    'strong' => array(),
1922
			);
1923
1924
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1925
		}
1926
1927
		$plugin_name = $plugin[ 'Name' ];
1928
1929
		self::$security_report[ $type ][ $plugin_name ] = $args;
1930
	}
1931
1932
	/**
1933
	 * Collects a new report if needed, then returns it.
1934
	 */
1935
	public function get_security_report() {
1936
		self::perform_security_reporting();
1937
		return Jetpack_Options::get_option( 'security_report' );
1938
	}
1939
1940
1941
/* Jetpack Options API */
1942
1943
	public static function get_option_names( $type = 'compact' ) {
1944
		return Jetpack_Options::get_option_names( $type );
1945
	}
1946
1947
	/**
1948
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1949
 	 *
1950
	 * @param string $name    Option name
1951
	 * @param mixed  $default (optional)
1952
	 */
1953
	public static function get_option( $name, $default = false ) {
1954
		return Jetpack_Options::get_option( $name, $default );
1955
	}
1956
1957
	/**
1958
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1959
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1960
	* $name must be a registered option name.
1961
	*/
1962
	public static function create_nonce( $name ) {
1963
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1964
1965
		Jetpack_Options::update_option( $name, $secret );
1966
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1967
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1968
			return new Jetpack_Error( 'missing_secrets' );
1969
1970
		return array(
1971
			'secret_1' => $secret_1,
1972
			'secret_2' => $secret_2,
1973
			'eol'      => $eol,
1974
		);
1975
	}
1976
1977
	/**
1978
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1979
 	 *
1980
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1981
	 * @param string $name  Option name
1982
	 * @param mixed  $value Option value
1983
	 */
1984
	public static function update_option( $name, $value ) {
1985
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1986
		return Jetpack_Options::update_option( $name, $value );
1987
	}
1988
1989
	/**
1990
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1991
 	 *
1992
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1993
	 * @param array $array array( option name => option value, ... )
1994
	 */
1995
	public static function update_options( $array ) {
1996
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1997
		return Jetpack_Options::update_options( $array );
1998
	}
1999
2000
	/**
2001
	 * Deletes the given option.  May be passed multiple option names as an array.
2002
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2003
	 *
2004
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2005
	 * @param string|array $names
2006
	 */
2007
	public static function delete_option( $names ) {
2008
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2009
		return Jetpack_Options::delete_option( $names );
2010
	}
2011
2012
	/**
2013
	 * Enters a user token into the user_tokens option
2014
	 *
2015
	 * @param int $user_id
2016
	 * @param string $token
2017
	 * return bool
2018
	 */
2019
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2020
		// not designed for concurrent updates
2021
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2022
		if ( ! is_array( $user_tokens ) )
2023
			$user_tokens = array();
2024
		$user_tokens[$user_id] = $token;
2025
		if ( $is_master_user ) {
2026
			$master_user = $user_id;
2027
			$options     = compact( 'user_tokens', 'master_user' );
2028
		} else {
2029
			$options = compact( 'user_tokens' );
2030
		}
2031
		return Jetpack_Options::update_options( $options );
2032
	}
2033
2034
	/**
2035
	 * Returns an array of all PHP files in the specified absolute path.
2036
	 * Equivalent to glob( "$absolute_path/*.php" ).
2037
	 *
2038
	 * @param string $absolute_path The absolute path of the directory to search.
2039
	 * @return array Array of absolute paths to the PHP files.
2040
	 */
2041
	public static function glob_php( $absolute_path ) {
2042
		if ( function_exists( 'glob' ) ) {
2043
			return glob( "$absolute_path/*.php" );
2044
		}
2045
2046
		$absolute_path = untrailingslashit( $absolute_path );
2047
		$files = array();
2048
		if ( ! $dir = @opendir( $absolute_path ) ) {
2049
			return $files;
2050
		}
2051
2052
		while ( false !== $file = readdir( $dir ) ) {
2053
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2054
				continue;
2055
			}
2056
2057
			$file = "$absolute_path/$file";
2058
2059
			if ( ! is_file( $file ) ) {
2060
				continue;
2061
			}
2062
2063
			$files[] = $file;
2064
		}
2065
2066
		closedir( $dir );
2067
2068
		return $files;
2069
	}
2070
2071
	public static function activate_new_modules( $redirect = false ) {
2072
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2073
			return;
2074
		}
2075
2076
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2077 View Code Duplication
		if ( ! $jetpack_old_version ) {
2078
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2079
			/** This action is documented in class.jetpack.php */
2080
			do_action( 'updating_jetpack_version', $version, false );
2081
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2082
		}
2083
2084
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2085
2086
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2087
			return;
2088
		}
2089
2090
		$active_modules     = Jetpack::get_active_modules();
2091
		$reactivate_modules = array();
2092
		foreach ( $active_modules as $active_module ) {
2093
			$module = Jetpack::get_module( $active_module );
2094
			if ( ! isset( $module['changed'] ) ) {
2095
				continue;
2096
			}
2097
2098
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2099
				continue;
2100
			}
2101
2102
			$reactivate_modules[] = $active_module;
2103
			Jetpack::deactivate_module( $active_module );
2104
		}
2105
2106
		$new_version = JETPACK__VERSION . ':' . time();
2107
		/** This action is documented in class.jetpack.php */
2108
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2109
		Jetpack_Options::update_options(
2110
			array(
2111
				'version'     => $new_version,
2112
				'old_version' => $jetpack_old_version,
2113
			)
2114
		);
2115
2116
		Jetpack::state( 'message', 'modules_activated' );
2117
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2118
2119
		if ( $redirect ) {
2120
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2121
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2122
				$page = $_GET['page'];
2123
			}
2124
2125
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2126
			exit;
2127
		}
2128
	}
2129
2130
	/**
2131
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2132
	 * Make sure to tuck away module "library" files in a sub-directory.
2133
	 */
2134
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2135
		static $modules = null;
2136
2137
		if ( ! isset( $modules ) ) {
2138
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2139
			// Use the cache if we're on the front-end and it's available...
2140
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2141
				$modules = $available_modules_option[ JETPACK__VERSION ];
2142
			} else {
2143
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2144
2145
				$modules = array();
2146
2147
				foreach ( $files as $file ) {
2148
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2149
						continue;
2150
					}
2151
2152
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2153
				}
2154
2155
				Jetpack_Options::update_option( 'available_modules', array(
2156
					JETPACK__VERSION => $modules,
2157
				) );
2158
			}
2159
		}
2160
2161
		/**
2162
		 * Filters the array of modules available to be activated.
2163
		 *
2164
		 * @since 2.4.0
2165
		 *
2166
		 * @param array $modules Array of available modules.
2167
		 * @param string $min_version Minimum version number required to use modules.
2168
		 * @param string $max_version Maximum version number required to use modules.
2169
		 */
2170
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2171
2172
		if ( ! $min_version && ! $max_version ) {
2173
			return array_keys( $mods );
2174
		}
2175
2176
		$r = array();
2177
		foreach ( $mods as $slug => $introduced ) {
2178
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2179
				continue;
2180
			}
2181
2182
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2183
				continue;
2184
			}
2185
2186
			$r[] = $slug;
2187
		}
2188
2189
		return $r;
2190
	}
2191
2192
	/**
2193
	 * Default modules loaded on activation.
2194
	 */
2195
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2196
		$return = array();
2197
2198
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2199
			$module_data = Jetpack::get_module( $module );
2200
2201
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2202
				case 'yes' :
2203
					$return[] = $module;
2204
					break;
2205
				case 'public' :
2206
					if ( Jetpack_Options::get_option( 'public' ) ) {
2207
						$return[] = $module;
2208
					}
2209
					break;
2210
				case 'no' :
2211
				default :
2212
					break;
2213
			}
2214
		}
2215
		/**
2216
		 * Filters the array of default modules.
2217
		 *
2218
		 * @since 2.5.0
2219
		 *
2220
		 * @param array $return Array of default modules.
2221
		 * @param string $min_version Minimum version number required to use modules.
2222
		 * @param string $max_version Maximum version number required to use modules.
2223
		 */
2224
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2225
	}
2226
2227
	/**
2228
	 * Checks activated modules during auto-activation to determine
2229
	 * if any of those modules are being deprecated.  If so, close
2230
	 * them out, and add any replacement modules.
2231
	 *
2232
	 * Runs at priority 99 by default.
2233
	 *
2234
	 * This is run late, so that it can still activate a module if
2235
	 * the new module is a replacement for another that the user
2236
	 * currently has active, even if something at the normal priority
2237
	 * would kibosh everything.
2238
	 *
2239
	 * @since 2.6
2240
	 * @uses jetpack_get_default_modules filter
2241
	 * @param array $modules
2242
	 * @return array
2243
	 */
2244
	function handle_deprecated_modules( $modules ) {
2245
		$deprecated_modules = array(
2246
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2247
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2248
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2249
		);
2250
2251
		// Don't activate SSO if they never completed activating WPCC.
2252
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2253
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2254
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2255
				$deprecated_modules['wpcc'] = null;
2256
			}
2257
		}
2258
2259
		foreach ( $deprecated_modules as $module => $replacement ) {
2260
			if ( Jetpack::is_module_active( $module ) ) {
2261
				self::deactivate_module( $module );
2262
				if ( $replacement ) {
2263
					$modules[] = $replacement;
2264
				}
2265
			}
2266
		}
2267
2268
		return array_unique( $modules );
2269
	}
2270
2271
	/**
2272
	 * Checks activated plugins during auto-activation to determine
2273
	 * if any of those plugins are in the list with a corresponding module
2274
	 * that is not compatible with the plugin. The module will not be allowed
2275
	 * to auto-activate.
2276
	 *
2277
	 * @since 2.6
2278
	 * @uses jetpack_get_default_modules filter
2279
	 * @param array $modules
2280
	 * @return array
2281
	 */
2282
	function filter_default_modules( $modules ) {
2283
2284
		$active_plugins = self::get_active_plugins();
2285
2286
		if ( ! empty( $active_plugins ) ) {
2287
2288
			// For each module we'd like to auto-activate...
2289
			foreach ( $modules as $key => $module ) {
2290
				// If there are potential conflicts for it...
2291
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2292
					// For each potential conflict...
2293
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2294
						// If that conflicting plugin is active...
2295
						if ( in_array( $plugin, $active_plugins ) ) {
2296
							// Remove that item from being auto-activated.
2297
							unset( $modules[ $key ] );
2298
						}
2299
					}
2300
				}
2301
			}
2302
		}
2303
2304
		return $modules;
2305
	}
2306
2307
	/**
2308
	 * Extract a module's slug from its full path.
2309
	 */
2310
	public static function get_module_slug( $file ) {
2311
		return str_replace( '.php', '', basename( $file ) );
2312
	}
2313
2314
	/**
2315
	 * Generate a module's path from its slug.
2316
	 */
2317
	public static function get_module_path( $slug ) {
2318
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2319
	}
2320
2321
	/**
2322
	 * Load module data from module file. Headers differ from WordPress
2323
	 * plugin headers to avoid them being identified as standalone
2324
	 * plugins on the WordPress plugins page.
2325
	 */
2326
	public static function get_module( $module ) {
2327
		$headers = array(
2328
			'name'                      => 'Module Name',
2329
			'description'               => 'Module Description',
2330
			'jumpstart_desc'            => 'Jumpstart Description',
2331
			'sort'                      => 'Sort Order',
2332
			'recommendation_order'      => 'Recommendation Order',
2333
			'introduced'                => 'First Introduced',
2334
			'changed'                   => 'Major Changes In',
2335
			'deactivate'                => 'Deactivate',
2336
			'free'                      => 'Free',
2337
			'requires_connection'       => 'Requires Connection',
2338
			'auto_activate'             => 'Auto Activate',
2339
			'module_tags'               => 'Module Tags',
2340
			'feature'                   => 'Feature',
2341
			'additional_search_queries' => 'Additional Search Queries',
2342
		);
2343
2344
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2345
2346
		$mod = Jetpack::get_file_data( $file, $headers );
2347
		if ( empty( $mod['name'] ) ) {
2348
			return false;
2349
		}
2350
2351
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2352
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2353
		$mod['deactivate']              = empty( $mod['deactivate'] );
2354
		$mod['free']                    = empty( $mod['free'] );
2355
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2356
2357
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2358
			$mod['auto_activate'] = 'No';
2359
		} else {
2360
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2361
		}
2362
2363
		if ( $mod['module_tags'] ) {
2364
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2365
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2366
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2367
		} else {
2368
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2369
		}
2370
2371
		if ( $mod['feature'] ) {
2372
			$mod['feature'] = explode( ',', $mod['feature'] );
2373
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2374
		} else {
2375
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2376
		}
2377
2378
		/**
2379
		 * Filters the feature array on a module.
2380
		 *
2381
		 * This filter allows you to control where each module is filtered: Recommended,
2382
		 * Jumpstart, and the default "Other" listing.
2383
		 *
2384
		 * @since 3.5.0
2385
		 *
2386
		 * @param array   $mod['feature'] The areas to feature this module:
2387
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2388
		 *     'Recommended' shows on the main Jetpack admin screen.
2389
		 *     'Other' should be the default if no other value is in the array.
2390
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2391
		 * @param array   $mod All the currently assembled module data.
2392
		 */
2393
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2394
2395
		/**
2396
		 * Filter the returned data about a module.
2397
		 *
2398
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2399
		 * so please be careful.
2400
		 *
2401
		 * @since 3.6.0
2402
		 *
2403
		 * @param array   $mod    The details of the requested module.
2404
		 * @param string  $module The slug of the module, e.g. sharedaddy
2405
		 * @param string  $file   The path to the module source file.
2406
		 */
2407
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2408
	}
2409
2410
	/**
2411
	 * Like core's get_file_data implementation, but caches the result.
2412
	 */
2413
	public static function get_file_data( $file, $headers ) {
2414
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2415
		$file_name = basename( $file );
2416
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2417
		$key              = md5( $file_name . serialize( $headers ) );
2418
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2419
2420
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2421
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2422
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2423
		}
2424
2425
		$data = get_file_data( $file, $headers );
2426
2427
		// Strip out any old Jetpack versions that are cluttering the option.
2428
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2429
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2430
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2431
2432
		return $data;
2433
	}
2434
2435
	/**
2436
	 * Return translated module tag.
2437
	 *
2438
	 * @param string $tag Tag as it appears in each module heading.
2439
	 *
2440
	 * @return mixed
2441
	 */
2442
	public static function translate_module_tag( $tag ) {
2443
		return jetpack_get_module_i18n_tag( $tag );
2444
	}
2445
2446
	/**
2447
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2448
	 *
2449
	 * @since 3.9.2
2450
	 *
2451
	 * @param array $modules
2452
	 *
2453
	 * @return string|void
2454
	 */
2455
	public static function get_translated_modules( $modules ) {
2456
		foreach ( $modules as $index => $module ) {
2457
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2458
			if ( isset( $module['name'] ) ) {
2459
				$modules[ $index ]['name'] = $i18n_module['name'];
2460
			}
2461
			if ( isset( $module['description'] ) ) {
2462
				$modules[ $index ]['description'] = $i18n_module['description'];
2463
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2464
			}
2465
		}
2466
		return $modules;
2467
	}
2468
2469
	/**
2470
	 * Get a list of activated modules as an array of module slugs.
2471
	 */
2472
	public static function get_active_modules() {
2473
		$active = Jetpack_Options::get_option( 'active_modules' );
2474
		if ( ! is_array( $active ) )
2475
			$active = array();
2476
		if ( is_admin() && ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) ) {
2477
			$active[] = 'vaultpress';
2478
		} else {
2479
			$active = array_diff( $active, array( 'vaultpress' ) );
2480
		}
2481
2482
		//If protect is active on the main site of a multisite, it should be active on all sites.
2483
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2484
			$active[] = 'protect';
2485
		}
2486
2487
		return array_unique( $active );
2488
	}
2489
2490
	/**
2491
	 * Check whether or not a Jetpack module is active.
2492
	 *
2493
	 * @param string $module The slug of a Jetpack module.
2494
	 * @return bool
2495
	 *
2496
	 * @static
2497
	 */
2498
	public static function is_module_active( $module ) {
2499
		return in_array( $module, self::get_active_modules() );
2500
	}
2501
2502
	public static function is_module( $module ) {
2503
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2504
	}
2505
2506
	/**
2507
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2508
	 *
2509
	 * @param bool $catch True to start catching, False to stop.
2510
	 *
2511
	 * @static
2512
	 */
2513
	public static function catch_errors( $catch ) {
2514
		static $display_errors, $error_reporting;
2515
2516
		if ( $catch ) {
2517
			$display_errors  = @ini_set( 'display_errors', 1 );
2518
			$error_reporting = @error_reporting( E_ALL );
2519
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2520
		} else {
2521
			@ini_set( 'display_errors', $display_errors );
2522
			@error_reporting( $error_reporting );
2523
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2524
		}
2525
	}
2526
2527
	/**
2528
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2529
	 */
2530
	public static function catch_errors_on_shutdown() {
2531
		Jetpack::state( 'php_errors', ob_get_clean() );
2532
	}
2533
2534
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2535
		$jetpack = Jetpack::init();
2536
2537
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2538
		$modules = array_merge( $other_modules, $modules );
2539
2540
		// Look for standalone plugins and disable if active.
2541
2542
		$to_deactivate = array();
2543
		foreach ( $modules as $module ) {
2544
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2545
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2546
			}
2547
		}
2548
2549
		$deactivated = array();
2550
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2551
			list( $probable_file, $probable_title ) = $deactivate_me;
2552
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2553
				$deactivated[] = $module;
2554
			}
2555
		}
2556
2557
		if ( $deactivated && $redirect ) {
2558
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2559
2560
			$url = add_query_arg(
2561
				array(
2562
					'action'   => 'activate_default_modules',
2563
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2564
				),
2565
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2566
			);
2567
			wp_safe_redirect( $url );
2568
			exit;
2569
		}
2570
2571
		/**
2572
		 * Fires before default modules are activated.
2573
		 *
2574
		 * @since 1.9.0
2575
		 *
2576
		 * @param string $min_version Minimum version number required to use modules.
2577
		 * @param string $max_version Maximum version number required to use modules.
2578
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2579
		 */
2580
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2581
2582
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2583
		Jetpack::restate();
2584
		Jetpack::catch_errors( true );
2585
2586
		$active = Jetpack::get_active_modules();
2587
2588
		foreach ( $modules as $module ) {
2589
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2590
				$active[] = $module;
2591
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2592
				continue;
2593
			}
2594
2595
			if ( in_array( $module, $active ) ) {
2596
				$module_info = Jetpack::get_module( $module );
2597
				if ( ! $module_info['deactivate'] ) {
2598
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2599 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2600
						$active_state = explode( ',', $active_state );
2601
					} else {
2602
						$active_state = array();
2603
					}
2604
					$active_state[] = $module;
2605
					Jetpack::state( $state, implode( ',', $active_state ) );
2606
				}
2607
				continue;
2608
			}
2609
2610
			$file = Jetpack::get_module_path( $module );
2611
			if ( ! file_exists( $file ) ) {
2612
				continue;
2613
			}
2614
2615
			// we'll override this later if the plugin can be included without fatal error
2616
			if ( $redirect ) {
2617
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2618
			}
2619
			Jetpack::state( 'error', 'module_activation_failed' );
2620
			Jetpack::state( 'module', $module );
2621
			ob_start();
2622
			require $file;
2623
			/**
2624
			 * Fires when a specific module is activated.
2625
			 *
2626
			 * @since 1.9.0
2627
			 *
2628
			 * @param string $module Module slug.
2629
			 */
2630
			do_action( 'jetpack_activate_module', $module );
2631
			$active[] = $module;
2632
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2633 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2634
				$active_state = explode( ',', $active_state );
2635
			} else {
2636
				$active_state = array();
2637
			}
2638
			$active_state[] = $module;
2639
			Jetpack::state( $state, implode( ',', $active_state ) );
2640
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2641
			ob_end_clean();
2642
		}
2643
		Jetpack::state( 'error', false );
2644
		Jetpack::state( 'module', false );
2645
		Jetpack::catch_errors( false );
2646
		/**
2647
		 * Fires when default modules are activated.
2648
		 *
2649
		 * @since 1.9.0
2650
		 *
2651
		 * @param string $min_version Minimum version number required to use modules.
2652
		 * @param string $max_version Maximum version number required to use modules.
2653
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2654
		 */
2655
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2656
	}
2657
2658
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2659
		/**
2660
		 * Fires before a module is activated.
2661
		 *
2662
		 * @since 2.6.0
2663
		 *
2664
		 * @param string $module Module slug.
2665
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2666
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2667
		 */
2668
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2669
2670
		$jetpack = Jetpack::init();
2671
2672
		if ( ! strlen( $module ) )
2673
			return false;
2674
2675
		if ( ! Jetpack::is_module( $module ) )
2676
			return false;
2677
2678
		// If it's already active, then don't do it again
2679
		$active = Jetpack::get_active_modules();
2680
		foreach ( $active as $act ) {
2681
			if ( $act == $module )
2682
				return true;
2683
		}
2684
2685
		$module_data = Jetpack::get_module( $module );
2686
2687
		if ( ! Jetpack::is_active() ) {
2688
			if ( !Jetpack::is_development_mode() )
2689
				return false;
2690
2691
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2692
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2693
				return false;
2694
		}
2695
2696
		// Check and see if the old plugin is active
2697
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2698
			// Deactivate the old plugin
2699
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2700
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2701
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2702
				Jetpack::state( 'deactivated_plugins', $module );
2703
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2704
				exit;
2705
			}
2706
		}
2707
2708
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2709
		Jetpack::state( 'module', $module );
2710
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2711
2712
		Jetpack::catch_errors( true );
2713
		ob_start();
2714
		require Jetpack::get_module_path( $module );
2715
		/** This action is documented in class.jetpack.php */
2716
		do_action( 'jetpack_activate_module', $module );
2717
		$active[] = $module;
2718
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2719
		Jetpack::state( 'error', false ); // the override
2720
		Jetpack::state( 'message', 'module_activated' );
2721
		Jetpack::state( 'module', $module );
2722
		ob_end_clean();
2723
		Jetpack::catch_errors( false );
2724
2725
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2726 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2727
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2728
2729
			//Jump start is being dismissed send data to MC Stats
2730
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2731
2732
			$jetpack->do_stats( 'server_side' );
2733
		}
2734
2735
		if ( $redirect ) {
2736
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2737
		}
2738
		if ( $exit ) {
2739
			exit;
2740
		}
2741
		return true;
2742
	}
2743
2744
	function activate_module_actions( $module ) {
2745
		/**
2746
		 * Fires when a module is activated.
2747
		 * The dynamic part of the filter, $module, is the module slug.
2748
		 *
2749
		 * @since 1.9.0
2750
		 *
2751
		 * @param string $module Module slug.
2752
		 */
2753
		do_action( "jetpack_activate_module_$module", $module );
2754
	}
2755
2756
	public static function deactivate_module( $module ) {
2757
		/**
2758
		 * Fires when a module is deactivated.
2759
		 *
2760
		 * @since 1.9.0
2761
		 *
2762
		 * @param string $module Module slug.
2763
		 */
2764
		do_action( 'jetpack_pre_deactivate_module', $module );
2765
2766
		$jetpack = Jetpack::init();
2767
2768
		$active = Jetpack::get_active_modules();
2769
		$new    = array_filter( array_diff( $active, (array) $module ) );
2770
2771
		/**
2772
		 * Fires when a module is deactivated.
2773
		 * The dynamic part of the filter, $module, is the module slug.
2774
		 *
2775
		 * @since 1.9.0
2776
		 *
2777
		 * @param string $module Module slug.
2778
		 */
2779
		do_action( "jetpack_deactivate_module_$module", $module );
2780
2781
		// A flag for Jump Start so it's not shown again.
2782 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2783
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2784
2785
			//Jump start is being dismissed send data to MC Stats
2786
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2787
2788
			$jetpack->do_stats( 'server_side' );
2789
		}
2790
2791
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2792
	}
2793
2794
	public static function enable_module_configurable( $module ) {
2795
		$module = Jetpack::get_module_slug( $module );
2796
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2797
	}
2798
2799
	public static function module_configuration_url( $module ) {
2800
		$module = Jetpack::get_module_slug( $module );
2801
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2802
	}
2803
2804
	public static function module_configuration_load( $module, $method ) {
2805
		$module = Jetpack::get_module_slug( $module );
2806
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2807
	}
2808
2809
	public static function module_configuration_head( $module, $method ) {
2810
		$module = Jetpack::get_module_slug( $module );
2811
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2812
	}
2813
2814
	public static function module_configuration_screen( $module, $method ) {
2815
		$module = Jetpack::get_module_slug( $module );
2816
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2817
	}
2818
2819
	public static function module_configuration_activation_screen( $module, $method ) {
2820
		$module = Jetpack::get_module_slug( $module );
2821
		add_action( 'display_activate_module_setting_' . $module, $method );
2822
	}
2823
2824
/* Installation */
2825
2826
	public static function bail_on_activation( $message, $deactivate = true ) {
2827
?>
2828
<!doctype html>
2829
<html>
2830
<head>
2831
<meta charset="<?php bloginfo( 'charset' ); ?>">
2832
<style>
2833
* {
2834
	text-align: center;
2835
	margin: 0;
2836
	padding: 0;
2837
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2838
}
2839
p {
2840
	margin-top: 1em;
2841
	font-size: 18px;
2842
}
2843
</style>
2844
<body>
2845
<p><?php echo esc_html( $message ); ?></p>
2846
</body>
2847
</html>
2848
<?php
2849
		if ( $deactivate ) {
2850
			$plugins = get_option( 'active_plugins' );
2851
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2852
			$update  = false;
2853
			foreach ( $plugins as $i => $plugin ) {
2854
				if ( $plugin === $jetpack ) {
2855
					$plugins[$i] = false;
2856
					$update = true;
2857
				}
2858
			}
2859
2860
			if ( $update ) {
2861
				update_option( 'active_plugins', array_filter( $plugins ) );
2862
			}
2863
		}
2864
		exit;
2865
	}
2866
2867
	/**
2868
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2869
	 * @static
2870
	 */
2871
	public static function plugin_activation( $network_wide ) {
2872
		Jetpack_Options::update_option( 'activated', 1 );
2873
2874
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2875
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2876
		}
2877
2878
		if ( $network_wide )
2879
			Jetpack::state( 'network_nag', true );
2880
2881
		Jetpack::plugin_initialize();
2882
	}
2883
	/**
2884
	 * Runs before bumping version numbers up to a new version
2885
	 * @param  (string) $version    Version:timestamp
2886
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2887
	 * @return null              [description]
2888
	 */
2889
	public static function do_version_bump( $version, $old_version ) {
2890
2891
		if ( ! $old_version ) { // For new sites
2892
			// Setting up jetpack manage
2893
			Jetpack::activate_manage();
2894
		}
2895
	}
2896
2897
	/**
2898
	 * Sets the internal version number and activation state.
2899
	 * @static
2900
	 */
2901
	public static function plugin_initialize() {
2902
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2903
			Jetpack_Options::update_option( 'activated', 2 );
2904
		}
2905
2906 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2907
			$version = $old_version = JETPACK__VERSION . ':' . time();
2908
			/** This action is documented in class.jetpack.php */
2909
			do_action( 'updating_jetpack_version', $version, false );
2910
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2911
		}
2912
2913
		Jetpack::load_modules();
2914
2915
		Jetpack_Options::delete_option( 'do_activate' );
2916
	}
2917
2918
	/**
2919
	 * Removes all connection options
2920
	 * @static
2921
	 */
2922
	public static function plugin_deactivation( ) {
2923
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2924
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2925
			Jetpack_Network::init()->deactivate();
2926
		} else {
2927
			Jetpack::disconnect( false );
2928
			//Jetpack_Heartbeat::init()->deactivate();
2929
		}
2930
	}
2931
2932
	/**
2933
	 * Disconnects from the Jetpack servers.
2934
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2935
	 * @static
2936
	 */
2937
	public static function disconnect( $update_activated_state = true ) {
2938
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2939
		Jetpack::clean_nonces( true );
2940
2941
		Jetpack::load_xml_rpc_client();
2942
		$xml = new Jetpack_IXR_Client();
2943
		$xml->query( 'jetpack.deregister' );
2944
2945
		Jetpack_Options::delete_option(
2946
			array(
2947
				'register',
2948
				'blog_token',
2949
				'user_token',
2950
				'user_tokens',
2951
				'master_user',
2952
				'time_diff',
2953
				'fallback_no_verify_ssl_certs',
2954
			)
2955
		);
2956
2957
		if ( $update_activated_state ) {
2958
			Jetpack_Options::update_option( 'activated', 4 );
2959
		}
2960
2961
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2962
		// Check then record unique disconnection if site has never been disconnected previously
2963
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2964
			$jetpack_unique_connection['disconnected'] = 1;
2965
		}
2966
		else {
2967
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2968
				//track unique disconnect
2969
				$jetpack = Jetpack::init();
2970
2971
				$jetpack->stat( 'connections', 'unique-disconnect' );
2972
				$jetpack->do_stats( 'server_side' );
2973
			}
2974
			// increment number of times disconnected
2975
			$jetpack_unique_connection['disconnected'] += 1;
2976
		}
2977
2978
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2979
2980
		// Disable the Heartbeat cron
2981
		Jetpack_Heartbeat::init()->deactivate();
2982
	}
2983
2984
	/**
2985
	 * Unlinks the current user from the linked WordPress.com user
2986
	 */
2987
	public static function unlink_user( $user_id = null ) {
2988
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2989
			return false;
2990
2991
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2992
2993
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2994
			return false;
2995
2996
		if ( ! isset( $tokens[ $user_id ] ) )
2997
			return false;
2998
2999
		Jetpack::load_xml_rpc_client();
3000
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3001
		$xml->query( 'jetpack.unlink_user', $user_id );
3002
3003
		unset( $tokens[ $user_id ] );
3004
3005
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3006
3007
		return true;
3008
	}
3009
3010
	/**
3011
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3012
	 */
3013
	public static function try_registration() {
3014
		// Let's get some testing in beta versions and such.
3015
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3016
			// Before attempting to connect, let's make sure that the domains are viable.
3017
			$domains_to_check = array_unique( array(
3018
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3019
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3020
			) );
3021
			foreach ( $domains_to_check as $domain ) {
3022
				$result = Jetpack_Data::is_usable_domain( $domain );
3023
				if ( is_wp_error( $result ) ) {
3024
					return $result;
3025
				}
3026
			}
3027
		}
3028
3029
		$result = Jetpack::register();
3030
3031
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3032
		if ( ! $result || is_wp_error( $result ) ) {
3033
			return $result;
3034
		} else {
3035
			return true;
3036
		}
3037
	}
3038
3039
	/**
3040
	 * Tracking an internal event log. Try not to put too much chaff in here.
3041
	 *
3042
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3043
	 */
3044
	public static function log( $code, $data = null ) {
3045
		// only grab the latest 200 entries
3046
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3047
3048
		// Append our event to the log
3049
		$log_entry = array(
3050
			'time'    => time(),
3051
			'user_id' => get_current_user_id(),
3052
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3053
			'code'    => $code,
3054
		);
3055
		// Don't bother storing it unless we've got some.
3056
		if ( ! is_null( $data ) ) {
3057
			$log_entry['data'] = $data;
3058
		}
3059
		$log[] = $log_entry;
3060
3061
		// Try add_option first, to make sure it's not autoloaded.
3062
		// @todo: Add an add_option method to Jetpack_Options
3063
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3064
			Jetpack_Options::update_option( 'log', $log );
3065
		}
3066
3067
		/**
3068
		 * Fires when Jetpack logs an internal event.
3069
		 *
3070
		 * @since 3.0.0
3071
		 *
3072
		 * @param array $log_entry {
3073
		 *	Array of details about the log entry.
3074
		 *
3075
		 *	@param string time Time of the event.
3076
		 *	@param int user_id ID of the user who trigerred the event.
3077
		 *	@param int blog_id Jetpack Blog ID.
3078
		 *	@param string code Unique name for the event.
3079
		 *	@param string data Data about the event.
3080
		 * }
3081
		 */
3082
		do_action( 'jetpack_log_entry', $log_entry );
3083
	}
3084
3085
	/**
3086
	 * Get the internal event log.
3087
	 *
3088
	 * @param $event (string) - only return the specific log events
3089
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3090
	 *
3091
	 * @return array of log events || WP_Error for invalid params
3092
	 */
3093
	public static function get_log( $event = false, $num = false ) {
3094
		if ( $event && ! is_string( $event ) ) {
3095
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3096
		}
3097
3098
		if ( $num && ! is_numeric( $num ) ) {
3099
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3100
		}
3101
3102
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3103
3104
		// If nothing set - act as it did before, otherwise let's start customizing the output
3105
		if ( ! $num && ! $event ) {
3106
			return $entire_log;
3107
		} else {
3108
			$entire_log = array_reverse( $entire_log );
3109
		}
3110
3111
		$custom_log_output = array();
3112
3113
		if ( $event ) {
3114
			foreach ( $entire_log as $log_event ) {
3115
				if ( $event == $log_event[ 'code' ] ) {
3116
					$custom_log_output[] = $log_event;
3117
				}
3118
			}
3119
		} else {
3120
			$custom_log_output = $entire_log;
3121
		}
3122
3123
		if ( $num ) {
3124
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3125
		}
3126
3127
		return $custom_log_output;
3128
	}
3129
3130
	/**
3131
	 * Log modification of important settings.
3132
	 */
3133
	public static function log_settings_change( $option, $old_value, $value ) {
3134
		switch( $option ) {
3135
			case 'jetpack_sync_non_public_post_stati':
3136
				self::log( $option, $value );
3137
				break;
3138
		}
3139
	}
3140
3141
	/**
3142
	 * Return stat data for WPCOM sync
3143
	 */
3144
	function get_stat_data() {
3145
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3146
		$additional_data = $this->get_additional_stat_data();
3147
3148
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3149
	}
3150
3151
	/**
3152
	 * Get additional stat data to sync to WPCOM
3153
	 */
3154
	function get_additional_stat_data( $prefix = '' ) {
3155
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
3156
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3157
		$return["{$prefix}users"]          = count_users();
3158
		$return["{$prefix}site-count"]     = 0;
3159
		if ( function_exists( 'get_blog_count' ) ) {
3160
			$return["{$prefix}site-count"] = get_blog_count();
3161
		}
3162
		return $return;
3163
	}
3164
3165
	/* Admin Pages */
3166
3167
	function admin_init() {
3168
		// If the plugin is not connected, display a connect message.
3169
		if (
3170
			// the plugin was auto-activated and needs its candy
3171
			Jetpack_Options::get_option( 'do_activate' )
3172
		||
3173
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3174
			! Jetpack_Options::get_option( 'activated' )
3175
		) {
3176
			Jetpack::plugin_initialize();
3177
		}
3178
3179
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3180
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3181
				// Show connect notice on dashboard and plugins pages
3182
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3183
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3184
			}
3185
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3186
			// Upgrade: 1.1 -> 1.1.1
3187
			// Check and see if host can verify the Jetpack servers' SSL certificate
3188
			$args = array();
3189
			Jetpack_Client::_wp_remote_request(
3190
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3191
				$args,
3192
				true
3193
			);
3194
		} else {
3195
			// Show the notice on the Dashboard only for now
3196
3197
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3198
3199
			// Identity crisis notices
3200
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3201
		}
3202
3203
		// If the plugin has just been disconnected from WP.com, show the survey notice
3204
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3205
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3206
		}
3207
3208
		if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3209
			add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
3210
		}
3211
3212
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3213
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3214
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3215
3216
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3217
			// Artificially throw errors in certain whitelisted cases during plugin activation
3218
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3219
3220
			// Kick off synchronization of user role when it changes
3221
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3222
		}
3223
3224
		// Jetpack Manage Activation Screen from .com
3225
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3226
	}
3227
3228
	function admin_body_class( $admin_body_class = '' ) {
3229
		$classes = explode( ' ', trim( $admin_body_class ) );
3230
3231
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3232
3233
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3234
		return " $admin_body_class ";
3235
	}
3236
3237
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3238
		return $admin_body_class . ' jetpack-pagestyles ';
3239
	}
3240
3241
	function prepare_connect_notice() {
3242
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3243
3244
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3245
3246
		if ( Jetpack::state( 'network_nag' ) )
3247
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3248
	}
3249
	/**
3250
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3251
	 *
3252
	 * @return null
3253
	 */
3254
	function prepare_manage_jetpack_notice() {
3255
3256
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3257
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3258
	}
3259
3260
	function manage_activate_screen() {
3261
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3262
	}
3263
	/**
3264
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3265
	 * This function artificially throws errors for such cases (whitelisted).
3266
	 *
3267
	 * @param string $plugin The activated plugin.
3268
	 */
3269
	function throw_error_on_activate_plugin( $plugin ) {
3270
		$active_modules = Jetpack::get_active_modules();
3271
3272
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3273
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3274
			$throw = false;
3275
3276
			// Try and make sure it really was the stats plugin
3277
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3278
				if ( 'stats.php' == basename( $plugin ) ) {
3279
					$throw = true;
3280
				}
3281
			} else {
3282
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3283
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3284
					$throw = true;
3285
				}
3286
			}
3287
3288
			if ( $throw ) {
3289
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3290
			}
3291
		}
3292
	}
3293
3294
	function intercept_plugin_error_scrape_init() {
3295
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3296
	}
3297
3298
	function intercept_plugin_error_scrape( $action, $result ) {
3299
		if ( ! $result ) {
3300
			return;
3301
		}
3302
3303
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3304
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3305
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3306
			}
3307
		}
3308
	}
3309
3310
	function add_remote_request_handlers() {
3311
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3312
	}
3313
3314
	function remote_request_handlers() {
3315
		switch ( current_filter() ) {
3316
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3317
			$response = $this->upload_handler();
3318
			break;
3319
		default :
3320
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3321
			break;
3322
		}
3323
3324
		if ( ! $response ) {
3325
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3326
		}
3327
3328
		if ( is_wp_error( $response ) ) {
3329
			$status_code       = $response->get_error_data();
3330
			$error             = $response->get_error_code();
3331
			$error_description = $response->get_error_message();
3332
3333
			if ( ! is_int( $status_code ) ) {
3334
				$status_code = 400;
3335
			}
3336
3337
			status_header( $status_code );
3338
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3339
		}
3340
3341
		status_header( 200 );
3342
		if ( true === $response ) {
3343
			exit;
3344
		}
3345
3346
		die( json_encode( (object) $response ) );
3347
	}
3348
3349
	function upload_handler() {
3350
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3351
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3352
		}
3353
3354
		$user = wp_authenticate( '', '' );
3355
		if ( ! $user || is_wp_error( $user ) ) {
3356
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3357
		}
3358
3359
		wp_set_current_user( $user->ID );
3360
3361
		if ( ! current_user_can( 'upload_files' ) ) {
3362
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3363
		}
3364
3365
		if ( empty( $_FILES ) ) {
3366
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3367
		}
3368
3369
		foreach ( array_keys( $_FILES ) as $files_key ) {
3370
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3371
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3372
			}
3373
		}
3374
3375
		$media_keys = array_keys( $_FILES['media'] );
3376
3377
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3378
		if ( ! $token || is_wp_error( $token ) ) {
3379
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3380
		}
3381
3382
		$uploaded_files = array();
3383
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3384
		unset( $GLOBALS['post'] );
3385
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3386
			$file = array();
3387
			foreach ( $media_keys as $media_key ) {
3388
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3389
			}
3390
3391
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3392
3393
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3394
			if ( $hmac_provided !== $hmac_file ) {
3395
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3396
				continue;
3397
			}
3398
3399
			$_FILES['.jetpack.upload.'] = $file;
3400
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3401
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3402
				$post_id = 0;
3403
			}
3404
			$attachment_id = media_handle_upload(
3405
				'.jetpack.upload.',
3406
				$post_id,
3407
				array(),
3408
				array(
3409
					'action' => 'jetpack_upload_file',
3410
				)
3411
			);
3412
3413
			if ( ! $attachment_id ) {
3414
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3415
			} elseif ( is_wp_error( $attachment_id ) ) {
3416
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3417
			} else {
3418
				$attachment = get_post( $attachment_id );
3419
				$uploaded_files[$index] = (object) array(
3420
					'id'   => (string) $attachment_id,
3421
					'file' => $attachment->post_title,
3422
					'url'  => wp_get_attachment_url( $attachment_id ),
3423
					'type' => $attachment->post_mime_type,
3424
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3425
				);
3426
			}
3427
		}
3428
		if ( ! is_null( $global_post ) ) {
3429
			$GLOBALS['post'] = $global_post;
3430
		}
3431
3432
		return $uploaded_files;
3433
	}
3434
3435
	/**
3436
	 * Add help to the Jetpack page
3437
	 *
3438
	 * @since Jetpack (1.2.3)
3439
	 * @return false if not the Jetpack page
3440
	 */
3441
	function admin_help() {
3442
		$current_screen = get_current_screen();
3443
3444
		// Overview
3445
		$current_screen->add_help_tab(
3446
			array(
3447
				'id'		=> 'home',
3448
				'title'		=> __( 'Home', 'jetpack' ),
3449
				'content'	=>
3450
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3451
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3452
					'<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>',
3453
			)
3454
		);
3455
3456
		// Screen Content
3457
		if ( current_user_can( 'manage_options' ) ) {
3458
			$current_screen->add_help_tab(
3459
				array(
3460
					'id'		=> 'settings',
3461
					'title'		=> __( 'Settings', 'jetpack' ),
3462
					'content'	=>
3463
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3464
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3465
						'<ol>' .
3466
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3467
							'<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>' .
3468
						'</ol>' .
3469
						'<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>'
3470
				)
3471
			);
3472
		}
3473
3474
		// Help Sidebar
3475
		$current_screen->set_help_sidebar(
3476
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3477
			'<p><a href="http://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3478
			'<p><a href="http://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3479
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3480
		);
3481
	}
3482
3483
	function admin_menu_css() {
3484
		wp_enqueue_style( 'jetpack-icons' );
3485
	}
3486
3487
	function admin_menu_order() {
3488
		return true;
3489
	}
3490
3491 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3492
		$jp_menu_order = array();
3493
3494
		foreach ( $menu_order as $index => $item ) {
3495
			if ( $item != 'jetpack' ) {
3496
				$jp_menu_order[] = $item;
3497
			}
3498
3499
			if ( $index == 0 ) {
3500
				$jp_menu_order[] = 'jetpack';
3501
			}
3502
		}
3503
3504
		return $jp_menu_order;
3505
	}
3506
3507
	function admin_head() {
3508 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3509
			/** This action is documented in class.jetpack-admin-page.php */
3510
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3511
	}
3512
3513
	function admin_banner_styles() {
3514
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3515
3516
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3517
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3518
		wp_style_add_data( 'jetpack', 'suffix', $min );
3519
	}
3520
3521
	function admin_scripts() {
3522
		wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
3523
		wp_localize_script(
3524
			'jetpack-js',
3525
			'jetpackL10n',
3526
			array(
3527
				'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
3528
				'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?",
3529
				'ays_dismiss'    => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
3530
			)
3531
		);
3532
		add_action( 'admin_footer', array( $this, 'do_stats' ) );
3533
	}
3534
3535
	function plugin_action_links( $actions ) {
3536
3537
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3538
3539
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3540
			return array_merge(
3541
				$jetpack_home,
3542
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3543
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3544
				$actions
3545
				);
3546
			}
3547
3548
		return array_merge( $jetpack_home, $actions );
3549
	}
3550
3551
	function admin_connect_notice() {
3552
		// Don't show the connect notice anywhere but the plugins.php after activating
3553
		$current = get_current_screen();
3554
		if ( 'plugins' !== $current->parent_base )
3555
			return;
3556
3557
		if ( ! current_user_can( 'jetpack_connect' ) )
3558
			return;
3559
3560
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3561
		?>
3562
		<div id="message" class="updated jetpack-message jp-banner" style="display:block !important;">
3563
			<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>
3564
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3565
				<div class="jp-banner__content is-connection">
3566
					<h2><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3567
					<p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
3568
				</div>
3569
				<div class="jp-banner__action-container is-connection">
3570
						<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>
3571
				</div>
3572 View Code Duplication
			<?php else : ?>
3573
				<div class="jp-banner__content">
3574
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3575
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3576
				</div>
3577
				<div class="jp-banner__action-container">
3578
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3579
				</div>
3580
			<?php endif; ?>
3581
		</div>
3582
3583
		<?php
3584
	}
3585
3586
	/**
3587
	 * This is the first banner
3588
	 * It should be visible only to user that can update the option
3589
	 * Are not connected
3590
	 *
3591
	 * @return null
3592
	 */
3593
	function admin_jetpack_manage_notice() {
3594
		$screen = get_current_screen();
3595
3596
		// Don't show the connect notice on the jetpack settings page.
3597
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3598
			return;
3599
3600
		// Only show it if don't have the managment option set.
3601
		// And not dismissed it already.
3602
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3603
			return;
3604
		}
3605
3606
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3607
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3608
		/**
3609
		 * I think it would be great to have different wordsing depending on where you are
3610
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3611
		 * etc..
3612
		 */
3613
3614
		?>
3615
		<div id="message" class="updated jetpack-message jp-banner is-opt-in" style="display:block !important;">
3616
			<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>
3617
			<div class="jp-banner__content">
3618
				<h2><?php esc_html_e( 'New in Jetpack: Centralized Site Management', 'jetpack' ); ?></h2>
3619
				<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>
3620
			</div>
3621
			<div class="jp-banner__action-container is-opt-in">
3622
				<a href="<?php echo esc_url( $opt_in_url ); ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Activate now', 'jetpack' ); ?></a>
3623
			</div>
3624
		</div>
3625
		<?php
3626
	}
3627
3628
	/**
3629
	 * Returns the url that the user clicks to remove the notice for the big banner
3630
	 * @return (string)
3631
	 */
3632
	function opt_out_jetpack_manage_url() {
3633
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3634
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3635
	}
3636
	/**
3637
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3638
	 * @return (string)
3639
	 */
3640
	function opt_in_jetpack_manage_url() {
3641
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3642
	}
3643
3644
	function opt_in_jetpack_manage_notice() {
3645
		?>
3646
		<div class="wrap">
3647
			<div id="message" class="jetpack-message is-opt-in">
3648
				<?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' ); ?>
3649
			</div>
3650
		</div>
3651
		<?php
3652
3653
	}
3654
	/**
3655
	 * Determines whether to show the notice of not true = display notice
3656
	 * @return (bool)
3657
	 */
3658
	function can_display_jetpack_manage_notice() {
3659
		// never display the notice to users that can't do anything about it anyways
3660
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3661
			return false;
3662
3663
		// don't display if we are in development more
3664
		if( Jetpack::is_development_mode() ) {
3665
			return false;
3666
		}
3667
		// don't display if the site is private
3668
		if(  ! Jetpack_Options::get_option( 'public' ) )
3669
			return false;
3670
3671
		/**
3672
		 * Should the Jetpack Remote Site Management notice be displayed.
3673
		 *
3674
		 * @since 3.3.0
3675
		 *
3676
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3677
		 */
3678
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3679
	}
3680
3681
	function network_connect_notice() {
3682
		?>
3683
		<div id="message" class="updated jetpack-message">
3684
			<div class="squeezer">
3685
				<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>
3686
			</div>
3687
		</div>
3688
		<?php
3689
	}
3690
3691
	public static function jetpack_comment_notice() {
3692
		if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
3693
			return '';
3694
		}
3695
3696
		$jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
3697
		$jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
3698
3699
		if ( $jetpack_old_version ) {
3700
			if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
3701
				return '';
3702
			}
3703
		}
3704
3705
		if ( $jetpack_new_version ) {
3706
			if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
3707
				return '';
3708
			}
3709
		}
3710
3711
		return '<br /><br />' . sprintf(
3712
			__( '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' ),
3713
			wp_nonce_url(
3714
				Jetpack::admin_url(
3715
					array(
3716
						'page'   => 'jetpack',
3717
						'action' => 'activate',
3718
						'module' => 'comments',
3719
					)
3720
				),
3721
				'jetpack_activate-comments'
3722
			),
3723
			__( 'click here', 'jetpack' )
3724
		);
3725
	}
3726
3727
	/**
3728
	 * Show the survey link when the user has just disconnected Jetpack.
3729
	 */
3730
	function disconnect_survey_notice() {
3731
		?>
3732
		<div class="wrap">
3733
			<div id="message" class="jetpack-message stay-visible">
3734
				<div class="squeezer">
3735
					<h2>
3736
						<?php _e( 'You have successfully disconnected Jetpack.', 'jetpack' ); ?>
3737
						<br />
3738
						<?php echo sprintf(
3739
							__( 'Would you tell us why? Just <a href="%1$s" target="%2$s">answering two simple questions</a> would help us improve Jetpack.', 'jetpack' ),
3740
							'https://jetpack.com/survey-disconnected/',
3741
							'_blank'
3742
						); ?>
3743
					</h2>
3744
				</div>
3745
			</div>
3746
		</div>
3747
		<?php
3748
	}
3749
3750
	/*
3751
	 * Registration flow:
3752
	 * 1 - ::admin_page_load() action=register
3753
	 * 2 - ::try_registration()
3754
	 * 3 - ::register()
3755
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3756
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3757
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3758
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3759
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3760
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3761
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3762
	 *       jetpack_id, jetpack_secret, jetpack_public
3763
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3764
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3765
	 * 5 - user logs in with WP.com account
3766
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3767
	 *		- Jetpack_Client_Server::authorize()
3768
	 *		- Jetpack_Client_Server::get_token()
3769
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3770
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3771
	 *			- which responds with access_token, token_type, scope
3772
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3773
	 *		- Jetpack::activate_default_modules()
3774
	 *     		- Deactivates deprecated plugins
3775
	 *     		- Activates all default modules
3776
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3777
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3778
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3779
	 *     Done!
3780
	 */
3781
3782
	/**
3783
	 * Handles the page load events for the Jetpack admin page
3784
	 */
3785
	function admin_page_load() {
3786
		$error = false;
3787
3788
		// Make sure we have the right body class to hook stylings for subpages off of.
3789
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3790
3791
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3792
			// Should only be used in intermediate redirects to preserve state across redirects
3793
			Jetpack::restate();
3794
		}
3795
3796
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3797
			// User clicked in the iframe to link their accounts
3798
			if ( ! Jetpack::is_user_connected() ) {
3799
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3800
				if ( isset( $_GET['notes_iframe'] ) )
3801
					$connect_url .= '&notes_iframe';
3802
				wp_redirect( $connect_url );
3803
				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...
3804
			} else {
3805
				Jetpack::state( 'message', 'already_authorized' );
3806
				wp_safe_redirect( Jetpack::admin_url() );
3807
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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