Completed
Push — add/jetpack-state-notices ( e76dc7...f6efe9 )
by
unknown
10:27
created

class.jetpack.php (7 issues)

Upgrade to new PHP Analysis Engine

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

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