Completed
Push — update/gitignore ( 7f3e2e...30ec70 )
by
unknown
497:33 queued 488:24
created

class.jetpack.php (17 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'tiled-gallery',
46
		'widget-conditions',
47
		'jetpack_display_posts_widget',
48
		'gravatar-profile-widget',
49
		'widget-grid-and-list',
50
		'jetpack-widgets',
51
		'goodreads-widget',
52
		'jetpack_social_media_icons_widget',
53
	);
54
55
	public $plugins_to_deactivate = array(
56
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
57
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
58
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
59
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
60
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
61
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
62
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
63
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
64
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
65
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
66
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
67
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
68
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
69
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
70
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
71
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
72
	);
73
74
	public $capability_translations = array(
75
		'administrator' => 'manage_options',
76
		'editor'        => 'edit_others_posts',
77
		'author'        => 'publish_posts',
78
		'contributor'   => 'edit_posts',
79
		'subscriber'    => 'read',
80
	);
81
82
	/**
83
	 * Map of modules that have conflicts with plugins and should not be auto-activated
84
	 * if the plugins are active.  Used by filter_default_modules
85
	 *
86
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
87
	 * change `module-slug` and add this to your plugin:
88
	 *
89
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
90
	 * function my_jetpack_get_default_modules( $modules ) {
91
	 *     return array_diff( $modules, array( 'module-slug' ) );
92
	 * }
93
	 *
94
	 * @var array
95
	 */
96
	private $conflicting_plugins = array(
97
		'comments'          => array(
98
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
99
			'Disqus'                               => 'disqus-comment-system/disqus.php',
100
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
101
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
102
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
103
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
104
		),
105
		'contact-form'      => array(
106
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
107
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
108
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
109
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
110
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
111
		),
112
		'minileven'         => array(
113
			'WPtouch'                              => 'wptouch/wptouch.php',
114
		),
115
		'latex'             => array(
116
			'LaTeX for WordPress'                  => 'latex/latex.php',
117
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
118
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
119
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
120
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
121
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
122
		),
123
		'protect'           => array(
124
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
125
			'Captcha'                              => 'captcha/captcha.php',
126
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
127
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
128
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
129
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
130
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
131
			'Security-protection'                  => 'security-protection/security-protection.php',
132
			'Login Security'                       => 'login-security/login-security.php',
133
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
134
			'Wordfence Security'                   => 'wordfence/wordfence.php',
135
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
136
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
137
		),
138
		'random-redirect'   => array(
139
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
140
		),
141
		'related-posts'     => array(
142
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
143
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
144
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
145
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
146
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
147
			'outbrain'                             => 'outbrain/outbrain.php',
148
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
149
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
150
		),
151
		'sharedaddy'        => array(
152
			'AddThis'                              => 'addthis/addthis_social_widget.php',
153
			'Add To Any'                           => 'add-to-any/add-to-any.php',
154
			'ShareThis'                            => 'share-this/sharethis.php',
155
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
156
		),
157
		'verification-tools' => array(
158
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
159
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
160
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
161
		),
162
		'widget-visibility' => array(
163
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
164
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
165
		),
166
		'sitemaps' => array(
167
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
168
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
169
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
170
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
171
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
172
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
173
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
174
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
175
			'Sitemap'                              => 'sitemap/sitemap.php',
176
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
177
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
178
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
179
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
180
		),
181
	);
182
183
	/**
184
	 * Plugins for which we turn off our Facebook OG Tags implementation.
185
	 *
186
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
187
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
188
	 *
189
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
190
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
191
	 */
192
	private $open_graph_conflicting_plugins = array(
193
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
194
		                                                         // 2 Click Social Media Buttons
195
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
196
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
197
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
198
		'facebook/facebook.php',                                 // Facebook (official plugin)
199
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
200
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
201
		                                                         // Facebook Featured Image & OG Meta Tags
202
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
203
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
204
		                                                         // Facebook Open Graph Meta Tags for WordPress
205
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
206
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
207
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
208
		                                                         // Fedmich's Facebook Open Graph Meta
209
		'header-footer/plugin.php',                              // Header and Footer
210
		'network-publisher/networkpub.php',                      // Network Publisher
211
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
212
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
213
		                                                         // NextScripts SNAP
214
		'opengraph/opengraph.php',                               // Open Graph
215
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
216
		                                                         // Open Graph Protocol Framework
217
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
218
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
219
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
220
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
221
		'sharepress/sharepress.php',                             // SharePress
222
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
223
		'social-discussions/social-discussions.php',             // Social Discussions
224
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
225
		'socialize/socialize.php',                               // Socialize
226
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
227
		                                                         // Tweet, Like, Google +1 and Share
228
		'wordbooker/wordbooker.php',                             // Wordbooker
229
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
230
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
231
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
232
		                                                         // WP Facebook Like Send & Open Graph Meta
233
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
234
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
235
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
236
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
237
	);
238
239
	/**
240
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
241
	 */
242
	private $twitter_cards_conflicting_plugins = array(
243
	//	'twitter/twitter.php',                       // The official one handles this on its own.
244
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
245
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
246
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
247
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
248
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
249
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
250
		'twitter-cards/twitter-cards.php',           // Twitter Cards
251
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
252
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
253
	);
254
255
	/**
256
	 * Message to display in admin_notice
257
	 * @var string
258
	 */
259
	public $message = '';
260
261
	/**
262
	 * Error to display in admin_notice
263
	 * @var string
264
	 */
265
	public $error = '';
266
267
	/**
268
	 * Modules that need more privacy description.
269
	 * @var string
270
	 */
271
	public $privacy_checks = '';
272
273
	/**
274
	 * Stats to record once the page loads
275
	 *
276
	 * @var array
277
	 */
278
	public $stats = array();
279
280
	/**
281
	 * Allows us to build a temporary security report
282
	 *
283
	 * @var array
284
	 */
285
	static $security_report = array();
286
287
	/**
288
	 * Jetpack_Sync object
289
	 */
290
	public $sync;
291
292
	/**
293
	 * Verified data for JSON authorization request
294
	 */
295
	public $json_api_authorization_request = array();
296
297
	/**
298
	 * Holds the singleton instance of this class
299
	 * @since 2.3.3
300
	 * @var Jetpack
301
	 */
302
	static $instance = false;
303
304
	/**
305
	 * Singleton
306
	 * @static
307
	 */
308
	public static function init() {
309
		if ( ! self::$instance ) {
310
			self::$instance = new Jetpack;
311
312
			self::$instance->plugin_upgrade();
313
314
			add_action( 'init', array( __CLASS__, 'perform_security_reporting' ) );
315
316
		}
317
318
		return self::$instance;
319
	}
320
321
	/**
322
	 * Must never be called statically
323
	 */
324
	function plugin_upgrade() {
325
		if ( Jetpack::is_active() ) {
326
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
327
			if ( JETPACK__VERSION != $version ) {
328
329
				// Check which active modules actually exist and remove others from active_modules list
330
				$unfiltered_modules = Jetpack::get_active_modules();
331
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
332
				if ( array_diff( $unfiltered_modules, $modules ) ) {
333
					Jetpack_Options::update_option( 'active_modules', $modules );
334
				}
335
336
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
337
				/**
338
				 * Fires when synchronizing all registered options and constants.
339
				 *
340
				 * @since 3.3.0
341
				 */
342
				do_action( 'jetpack_sync_all_registered_options' );
343
			}
344
		}
345
	}
346
347
	static function activate_manage( ) {
348
349
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
350
			self::activate_module( 'manage', false, false );
351
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
352
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
353
		}
354
355
	}
356
357
	/**
358
	 * Constructor.  Initializes WordPress hooks
359
	 */
360
	private function __construct() {
361
		/*
362
		 * Check for and alert any deprecated hooks
363
		 */
364
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
365
366
		/**
367
		 * Trigger a wp_version sync when updating WP versions
368
		 **/
369
		add_action( 'upgrader_process_complete', array( 'Jetpack', 'update_get_wp_version' ), 10, 2 );
370
371
		/*
372
		 * Load things that should only be in Network Admin.
373
		 *
374
		 * For now blow away everything else until a more full
375
		 * understanding of what is needed at the network level is
376
		 * available
377
		 */
378
		if( is_multisite() ) {
379
			Jetpack_Network::init();
380
		}
381
382
		// Unlink user before deleting the user from .com
383
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
384
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
385
386
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
387
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
388
389
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
390
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
391
392
			$this->require_jetpack_authentication();
393
394
			if ( Jetpack::is_active() ) {
395
				// Hack to preserve $HTTP_RAW_POST_DATA
396
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
397
398
				$signed = $this->verify_xml_rpc_signature();
399
				if ( $signed && ! is_wp_error( $signed ) ) {
400
					// The actual API methods.
401
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
402
				} else {
403
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
404
					// active Jetpack connection, so that additional users can link their account.
405
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
406
				}
407
			} else {
408
				// The bootstrap API methods.
409
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
410
			}
411
412
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
413
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
414
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
415
			$this->require_jetpack_authentication();
416
			$this->add_remote_request_handlers();
417
		} else {
418
			if ( Jetpack::is_active() ) {
419
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
420
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
421
			}
422
		}
423
424
		if ( Jetpack::is_active() ) {
425
			Jetpack_Heartbeat::init();
426
		}
427
428
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
429
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
430
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
431
		}
432
433
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
434
435
		add_action( 'admin_init', array( $this, 'admin_init' ) );
436
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
437
438
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
439
440
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
441
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
442
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
443
444
		add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
445
		add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
446
447
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
448
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
449
450
		// Identity Crisis AJAX callback function
451
		add_action( 'wp_ajax_jetpack_resolve_identity_crisis', array( $this, 'resolve_identity_crisis_ajax_callback' ) );
452
453
		// JITM AJAX callback function
454
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
455
456
		add_action( 'wp_ajax_jetpack_admin_ajax',          array( $this, 'jetpack_admin_ajax_callback' ) );
457
		add_action( 'wp_ajax_jetpack_admin_ajax_refresh',  array( $this, 'jetpack_admin_ajax_refresh_data' ) );
458
459
		// Universal ajax callback for all tracking events triggered via js
460
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
461
462
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
463
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
464
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
465
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
466
467
		add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
468
469
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
470
471
		add_action( 'jetpack_notices', array( $this, 'show_development_mode_notice' ) );
472
473
		/**
474
		 * These actions run checks to load additional files.
475
		 * They check for external files or plugins, so they need to run as late as possible.
476
		 */
477
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
478
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
479
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
480
481
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
482
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
483
484
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
485
486
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
487
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
488
489
		// A filter to control all just in time messages
490
		add_filter( 'jetpack_just_in_time_msgs', '__return_false' );
491
492
		/**
493
		 * This is the hack to concatinate all css files into one.
494
		 * For description and reasoning see the implode_frontend_css method
495
		 *
496
		 * Super late priority so we catch all the registered styles
497
		 */
498
		if( !is_admin() ) {
499
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
500
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
501
		}
502
503
		// Sync Core Icon: Detect changes in Core's Site Icon and make it syncable.
504
		add_action( 'add_option_site_icon',    array( $this, 'jetpack_sync_core_icon' ) );
505
		add_action( 'update_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
506
		add_action( 'delete_option_site_icon', array( $this, 'jetpack_sync_core_icon' ) );
507
		add_action( 'jetpack_heartbeat',       array( $this, 'jetpack_sync_core_icon' ) );
508
509
	}
510
511
	/*
512
	 * Make sure any site icon added to core can get
513
	 * synced back to dotcom, so we can display it there.
514
	 */
515 View Code Duplication
	function jetpack_sync_core_icon() {
516
		if ( function_exists( 'get_site_icon_url' ) ) {
517
			$url = get_site_icon_url();
518
		} else {
519
			return;
520
		}
521
522
		require_once( JETPACK__PLUGIN_DIR . 'modules/site-icon/site-icon-functions.php' );
523
		// If there's a core icon, maybe update the option.  If not, fall back to Jetpack's.
524
		if ( ! empty( $url ) && $url !== jetpack_site_icon_url() ) {
525
			// This is the option that is synced with dotcom
526
			Jetpack_Options::update_option( 'site_icon_url', $url );
527
		} else if ( empty( $url ) && did_action( 'delete_option_site_icon' ) ) {
528
			Jetpack_Options::delete_option( 'site_icon_url' );
529
		}
530
	}
531
532
	function jetpack_admin_ajax_tracks_callback() {
533
		// Check for nonce
534
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
535
			wp_die( 'Permissions check failed.' );
536
		}
537
538
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
539
			wp_die( 'No valid event name or type.' );
540
		}
541
542
		$tracks_data = array();
543
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
544
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
545
		}
546
547
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
548
		wp_send_json_success();
549
		wp_die();
550
	}
551
552
	function jetpack_admin_ajax_callback() {
553
		// Check for nonce
554 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) || ! current_user_can( 'jetpack_manage_modules' ) ) {
555
			wp_die( 'permissions check failed' );
556
		}
557
558
		if ( isset( $_REQUEST['toggleModule'] ) && 'nux-toggle-module' == $_REQUEST['toggleModule'] ) {
559
			$slug = $_REQUEST['thisModuleSlug'];
560
561
			if ( ! in_array( $slug, Jetpack::get_available_modules() ) ) {
562
				wp_die( 'That is not a Jetpack module slug' );
563
			}
564
565
			if ( Jetpack::is_module_active( $slug ) ) {
566
				Jetpack::deactivate_module( $slug );
567
			} else {
568
				Jetpack::activate_module( $slug, false, false );
569
			}
570
571
			$modules = Jetpack_Admin::init()->get_modules();
572
			echo json_encode( $modules[ $slug ] );
573
574
			exit;
575
		}
576
577
		wp_die();
578
	}
579
580
	/*
581
	 * Sometimes we need to refresh the data,
582
	 * especially if the page is visited via a 'history'
583
	 * event like back/forward
584
	 */
585
	function jetpack_admin_ajax_refresh_data() {
586
		// Check for nonce
587 View Code Duplication
		if ( ! isset( $_REQUEST['adminNonce'] ) || ! wp_verify_nonce( $_REQUEST['adminNonce'], 'jetpack-admin-nonce' ) ) {
588
			wp_die( 'permissions check failed' );
589
		}
590
591
		if ( isset( $_REQUEST['refreshData'] ) && 'refresh' == $_REQUEST['refreshData'] ) {
592
			$modules = Jetpack_Admin::init()->get_modules();
593
			echo json_encode( $modules );
594
			exit;
595
		}
596
597
		wp_die();
598
	}
599
600
	/**
601
	 * The callback for the JITM ajax requests.
602
	 */
603
	function jetpack_jitm_ajax_callback() {
604
		// Check for nonce
605
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
606
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
607
		}
608
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
609
			$module_slug = $_REQUEST['jitmModule'];
610
			Jetpack::log( 'activate', $module_slug );
611
			Jetpack::activate_module( $module_slug, false, false );
612
			Jetpack::state( 'message', 'no_message' );
613
614
			//A Jetpack module is being activated through a JITM, track it
615
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
616
			$this->do_stats( 'server_side' );
617
618
			wp_send_json_success();
619
		}
620
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
621
			// get the hide_jitm options array
622
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
623
			$module_slug = $_REQUEST['jitmModule'];
624
625
			if( ! $jetpack_hide_jitm ) {
626
				$jetpack_hide_jitm = array(
627
					$module_slug => 'hide'
628
				);
629
			} else {
630
				$jetpack_hide_jitm[$module_slug] = 'hide';
631
			}
632
633
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
634
635
			//jitm is being dismissed forever, track it
636
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
637
			$this->do_stats( 'server_side' );
638
639
			wp_send_json_success();
640
		}
641 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
642
			$module_slug = $_REQUEST['jitmModule'];
643
644
			// User went to WordPress.com, track this
645
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
646
			$this->do_stats( 'server_side' );
647
648
			wp_send_json_success();
649
		}
650 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
651
			$track = $_REQUEST['jitmModule'];
652
653
			// User is viewing JITM, track it.
654
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
655
			$this->do_stats( 'server_side' );
656
657
			wp_send_json_success();
658
		}
659
	}
660
661
	/**
662
	 * If there are any stats that need to be pushed, but haven't been, push them now.
663
	 */
664
	function __destruct() {
665
		if ( ! empty( $this->stats ) ) {
666
			$this->do_stats( 'server_side' );
667
		}
668
	}
669
670
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
671
		switch( $cap ) {
672
			case 'jetpack_connect' :
673
			case 'jetpack_reconnect' :
674
				if ( Jetpack::is_development_mode() ) {
675
					$caps = array( 'do_not_allow' );
676
					break;
677
				}
678
				/**
679
				 * Pass through. If it's not development mode, these should match disconnect.
680
				 * Let users disconnect if it's development mode, just in case things glitch.
681
				 */
682
			case 'jetpack_disconnect' :
683
				/**
684
				 * In multisite, can individual site admins manage their own connection?
685
				 *
686
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
687
				 */
688
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
689
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
690
						/**
691
						 * We need to update the option name -- it's terribly unclear which
692
						 * direction the override goes.
693
						 *
694
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
695
						 */
696
						$caps = array( 'do_not_allow' );
697
						break;
698
					}
699
				}
700
701
				$caps = array( 'manage_options' );
702
				break;
703
			case 'jetpack_manage_modules' :
704
			case 'jetpack_activate_modules' :
705
			case 'jetpack_deactivate_modules' :
706
				$caps = array( 'manage_options' );
707
				break;
708
			case 'jetpack_configure_modules' :
709
				$caps = array( 'manage_options' );
710
				break;
711
			case 'jetpack_network_admin_page':
712
			case 'jetpack_network_settings_page':
713
				$caps = array( 'manage_network_plugins' );
714
				break;
715
			case 'jetpack_network_sites_page':
716
				$caps = array( 'manage_sites' );
717
				break;
718
			case 'jetpack_admin_page' :
719
				if ( Jetpack::is_development_mode() ) {
720
					$caps = array( 'manage_options' );
721
					break;
722
				} else {
723
					$caps = array( 'read' );
724
				}
725
				break;
726
			case 'jetpack_connect_user' :
727
				if ( Jetpack::is_development_mode() ) {
728
					$caps = array( 'do_not_allow' );
729
					break;
730
				}
731
				$caps = array( 'read' );
732
				break;
733
		}
734
		return $caps;
735
	}
736
737
	function require_jetpack_authentication() {
738
		// Don't let anyone authenticate
739
		$_COOKIE = array();
740
		remove_all_filters( 'authenticate' );
741
742
		/**
743
		 * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
744
		 * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
745
		 * generate false-positives.
746
		 */
747
		remove_filter( 'wp_login_failed', 'limit_login_failed' );
748
749
		if ( Jetpack::is_active() ) {
750
			// Allow Jetpack authentication
751
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
752
		}
753
	}
754
755
	/**
756
	 * Load language files
757
	 * @action plugins_loaded
758
	 */
759
	public static function plugin_textdomain() {
760
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
761
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
762
	}
763
764
	/**
765
	 * Register assets for use in various modules and the Jetpack admin page.
766
	 *
767
	 * @uses wp_script_is, wp_register_script, plugins_url
768
	 * @action wp_loaded
769
	 * @return null
770
	 */
771
	public function register_assets() {
772
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
773
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
774
		}
775
776 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
777
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
778
		}
779
780 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
781
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
782
		}
783
784 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
785
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
786
		}
787
788
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
789
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
790
791
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
792
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
793
			if ( ! is_numeric( $fb_app_id ) ) {
794
				$fb_app_id = '';
795
			}
796
			wp_localize_script(
797
				'jetpack-facebook-embed',
798
				'jpfbembed',
799
				array(
800
					'appid' => $fb_app_id,
801
					'locale' => $this->get_locale(),
802
				)
803
			);
804
		}
805
806
		/**
807
		 * As jetpack_register_genericons is by default fired off a hook,
808
		 * the hook may have already fired by this point.
809
		 * So, let's just trigger it manually.
810
		 */
811
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
812
		jetpack_register_genericons();
813
814 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
815
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
816
	}
817
818
	/**
819
	 * Guess locale from language code.
820
	 *
821
	 * @param string $lang Language code.
822
	 * @return string|bool
823
	 */
824 View Code Duplication
	function guess_locale_from_lang( $lang ) {
825
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
826
			return 'en_US';
827
		}
828
829
		if ( ! class_exists( 'GP_Locales' ) ) {
830
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
831
				return false;
832
			}
833
834
			require JETPACK__GLOTPRESS_LOCALES_PATH;
835
		}
836
837
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
838
			// WP.com: get_locale() returns 'it'
839
			$locale = GP_Locales::by_slug( $lang );
840
		} else {
841
			// Jetpack: get_locale() returns 'it_IT';
842
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
843
		}
844
845
		if ( ! $locale ) {
846
			return false;
847
		}
848
849
		if ( empty( $locale->facebook_locale ) ) {
850
			if ( empty( $locale->wp_locale ) ) {
851
				return false;
852
			} else {
853
				// Facebook SDK is smart enough to fall back to en_US if a
854
				// locale isn't supported. Since supported Facebook locales
855
				// can fall out of sync, we'll attempt to use the known
856
				// wp_locale value and rely on said fallback.
857
				return $locale->wp_locale;
858
			}
859
		}
860
861
		return $locale->facebook_locale;
862
	}
863
864
	/**
865
	 * Get the locale.
866
	 *
867
	 * @return string|bool
868
	 */
869
	function get_locale() {
870
		$locale = $this->guess_locale_from_lang( get_locale() );
871
872
		if ( ! $locale ) {
873
			$locale = 'en_US';
874
		}
875
876
		return $locale;
877
	}
878
879
	/**
880
	 * Device Pixels support
881
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
882
	 */
883
	function devicepx() {
884
		if ( Jetpack::is_active() ) {
885
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
886
		}
887
	}
888
889
	/**
890
	 * Return the network_site_url so that .com knows what network this site is a part of.
891
	 * @param  bool $option
892
	 * @return string
893
	 */
894
	public function jetpack_main_network_site_option( $option ) {
895
		return network_site_url();
896
	}
897
	/**
898
	 * Network Name.
899
	 */
900
	static function network_name( $option = null ) {
901
		global $current_site;
902
		return $current_site->site_name;
903
	}
904
	/**
905
	 * Does the network allow new user and site registrations.
906
	 * @return string
907
	 */
908
	static function network_allow_new_registrations( $option = null ) {
909
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
910
	}
911
	/**
912
	 * Does the network allow admins to add new users.
913
	 * @return boolian
914
	 */
915
	static function network_add_new_users( $option = null ) {
916
		return (bool) get_site_option( 'add_new_users' );
917
	}
918
	/**
919
	 * File upload psace left per site in MB.
920
	 *  -1 means NO LIMIT.
921
	 * @return number
922
	 */
923
	static function network_site_upload_space( $option = null ) {
924
		// value in MB
925
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
926
	}
927
928
	/**
929
	 * Network allowed file types.
930
	 * @return string
931
	 */
932
	static function network_upload_file_types( $option = null ) {
933
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
934
	}
935
936
	/**
937
	 * Maximum file upload size set by the network.
938
	 * @return number
939
	 */
940
	static function network_max_upload_file_size( $option = null ) {
941
		// value in KB
942
		return get_site_option( 'fileupload_maxk', 300 );
943
	}
944
945
	/**
946
	 * Lets us know if a site allows admins to manage the network.
947
	 * @return array
948
	 */
949
	static function network_enable_administration_menus( $option = null ) {
950
		return get_site_option( 'menu_items' );
951
	}
952
953
	/**
954
	 * Return whether we are dealing with a multi network setup or not.
955
	 * The reason we are type casting this is because we want to avoid the situation where
956
	 * the result is false since when is_main_network_option return false it cases
957
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
958
	 * database which could be set to anything as opposed to what this function returns.
959
	 * @param  bool  $option
960
	 *
961
	 * @return boolean
962
	 */
963
	public function is_main_network_option( $option ) {
964
		// return '1' or ''
965
		return (string) (bool) Jetpack::is_multi_network();
966
	}
967
968
	/**
969
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
970
	 *
971
	 * @param  string  $option
972
	 * @return boolean
973
	 */
974
	public function is_multisite( $option ) {
975
		return (string) (bool) is_multisite();
976
	}
977
978
	/**
979
	 * Implemented since there is no core is multi network function
980
	 * Right now there is no way to tell if we which network is the dominant network on the system
981
	 *
982
	 * @since  3.3
983
	 * @return boolean
984
	 */
985
	public static function is_multi_network() {
986
		global  $wpdb;
987
988
		// if we don't have a multi site setup no need to do any more
989
		if ( ! is_multisite() ) {
990
			return false;
991
		}
992
993
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
994
		if ( $num_sites > 1 ) {
995
			return true;
996
		} else {
997
			return false;
998
		}
999
	}
1000
1001
	/**
1002
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1003
	 * @return null
1004
	 */
1005
	function update_jetpack_main_network_site_option() {
1006
		// do_action( 'add_option_$option', '$option', '$value-of-the-option' );
1007
		/**
1008
		 * Fires when the site URL is updated.
1009
		 * Determines if the site is the main site of a Mulitiste network.
1010
		 *
1011
		 * @since 3.3.0
1012
		 *
1013
		 * @param string jetpack_main_network_site.
1014
		 * @param string network_site_url() Site URL for the "main" site of the current Multisite network.
1015
		 */
1016
		do_action( 'add_option_jetpack_main_network_site', 'jetpack_main_network_site', network_site_url() );
1017
		/**
1018
		 * Fires when the site URL is updated.
1019
		 * Determines if the is part of a multi network.
1020
		 *
1021
		 * @since 3.3.0
1022
		 *
1023
		 * @param string jetpack_is_main_network.
1024
		 * @param bool Jetpack::is_multi_network() Is the site part of a multi network.
1025
		 */
1026
		do_action( 'add_option_jetpack_is_main_network', 'jetpack_is_main_network', (string) (bool) Jetpack::is_multi_network() );
1027
		/**
1028
		 * Fires when the site URL is updated.
1029
		 * Determines if the site is part of a multisite network.
1030
		 *
1031
		 * @since 3.4.0
1032
		 *
1033
		 * @param string jetpack_is_multi_site.
1034
		 * @param bool is_multisite() Is the site part of a mutlisite network.
1035
		 */
1036
		do_action( 'add_option_jetpack_is_multi_site', 'jetpack_is_multi_site', (string) (bool) is_multisite() );
1037
	}
1038
	/**
1039
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1040
	 *
1041
	 */
1042
	function update_jetpack_network_settings() {
1043
		// Only sync this info for the main network site.
1044
		do_action( 'add_option_jetpack_network_name', 'jetpack_network_name', Jetpack::network_name() );
1045
		do_action( 'add_option_jetpack_network_allow_new_registrations', 'jetpack_network_allow_new_registrations', Jetpack::network_allow_new_registrations() );
1046
		do_action( 'add_option_jetpack_network_add_new_users', 'jetpack_network_add_new_users', Jetpack::network_add_new_users() );
1047
		do_action( 'add_option_jetpack_network_site_upload_space', 'jetpack_network_site_upload_space', Jetpack::network_site_upload_space() );
1048
		do_action( 'add_option_jetpack_network_upload_file_types', 'jetpack_network_upload_file_types', Jetpack::network_upload_file_types() );
1049
		do_action( 'add_option_jetpack_network_enable_administration_menus', 'jetpack_network_enable_administration_menus', Jetpack::network_enable_administration_menus() );
1050
1051
	}
1052
1053
	/**
1054
	 * Get back if the current site is single user site.
1055
	 *
1056
	 * @return bool
1057
	 */
1058
	public static function is_single_user_site() {
1059
1060
		$user_query = new WP_User_Query( array(
1061
			'blog_id' => get_current_blog_id(),
1062
			'fields'  => 'ID',
1063
			'number' => 2
1064
		) );
1065
		return 1 === (int) $user_query->get_total();
1066
	}
1067
1068
	/**
1069
	 * Returns true if the site has file write access false otherwise.
1070
	 * @return string ( '1' | '0' )
1071
	 **/
1072 View Code Duplication
	public static function file_system_write_access() {
1073
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1074
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1075
		}
1076
1077
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1078
1079
		$filesystem_method = get_filesystem_method();
1080
		if ( $filesystem_method === 'direct' ) {
1081
			return 1;
1082
		}
1083
1084
		ob_start();
1085
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1086
		ob_end_clean();
1087
		if ( $filesystem_credentials_are_stored ) {
1088
			return 1;
1089
		}
1090
		return 0;
1091
	}
1092
1093
	/**
1094
	 * Finds out if a site is using a version control system.
1095
	 * @return string ( '1' | '0' )
1096
	 **/
1097 View Code Duplication
	public static function is_version_controlled() {
1098
1099
		if ( !class_exists( 'WP_Automatic_Updater' ) ) {
1100
			require_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
1101
		}
1102
		$updater = new WP_Automatic_Updater();
1103
		$is_version_controlled = strval( $updater->is_vcs_checkout( $context = ABSPATH ) );
1104
		// transients should not be empty
1105
		if ( empty( $is_version_controlled ) ) {
1106
			$is_version_controlled = '0';
1107
		}
1108
		return $is_version_controlled;
1109
	}
1110
1111
	/**
1112
	 * Determines whether the current theme supports featured images or not.
1113
	 * @return string ( '1' | '0' )
1114
	 */
1115
	public static function featured_images_enabled() {
1116
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1117
	}
1118
1119
	/*
1120
	 * Sync back wp_version
1121
	 */
1122
	public static function get_wp_version() {
1123
		global $wp_version;
1124
		return $wp_version;
1125
	}
1126
1127
	/**
1128
	 * Keeps wp_version in sync with .com when WordPress core updates
1129
	 **/
1130
	public static function update_get_wp_version( $update, $meta_data ) {
1131
		if ( 'update' === $meta_data['action'] && 'core' === $meta_data['type'] ) {
1132
			/** This action is documented in wp-includes/option.php */
1133
			/**
1134
			 * This triggers the sync for the jetpack version
1135
			 * See Jetpack_Sync options method for more info.
1136
			 */
1137
			do_action( 'add_option_jetpack_wp_version', 'jetpack_wp_version', (string) Jetpack::get_wp_version() );
1138
		}
1139
	}
1140
1141
	/**
1142
	 * jetpack_updates is saved in the following schema:
1143
	 *
1144
	 * array (
1145
	 *      'plugins'                       => (int) Number of plugin updates available.
1146
	 *      'themes'                        => (int) Number of theme updates available.
1147
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1148
	 *      'translations'                  => (int) Number of translation updates available.
1149
	 *      'total'                         => (int) Total of all available updates.
1150
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1151
	 * )
1152
	 * @return array
1153
	 */
1154
	public static function get_updates() {
1155
		$update_data = wp_get_update_data();
1156
1157
		// Stores the individual update counts as well as the total count.
1158
		if ( isset( $update_data['counts'] ) ) {
1159
			$updates = $update_data['counts'];
1160
		}
1161
1162
		// If we need to update WordPress core, let's find the latest version number.
1163 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1164
			$cur = get_preferred_from_update_core();
1165
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1166
				$updates['wp_update_version'] = $cur->current;
1167
			}
1168
		}
1169
		return isset( $updates ) ? $updates : array();
1170
	}
1171
1172
	public static function get_update_details() {
1173
		$update_details = array(
1174
			'update_core' => get_site_transient( 'update_core' ),
1175
			'update_plugins' => get_site_transient( 'update_plugins' ),
1176
			'update_themes' => get_site_transient( 'update_themes' ),
1177
		);
1178
		return $update_details;
1179
	}
1180
1181
	public static function refresh_update_data() {
1182
		if ( current_user_can( 'update_core' ) && current_user_can( 'update_plugins' ) && current_user_can( 'update_themes' ) ) {
1183
			/**
1184
			 * Fires whenever the amount of updates needed for a site changes.
1185
			 * Syncs an array that includes the number of theme, plugin, and core updates available, as well as the latest core version available.
1186
			 *
1187
			 * @since 3.7.0
1188
			 *
1189
			 * @param string jetpack_updates
1190
			 * @param array Update counts calculated by Jetpack::get_updates
1191
			 */
1192
			do_action( 'add_option_jetpack_updates', 'jetpack_updates', Jetpack::get_updates() );
1193
		}
1194
		/**
1195
		 * Fires whenever the amount of updates needed for a site changes.
1196
		 * Syncs an array of core, theme, and plugin data, and which of each is out of date
1197
		 *
1198
		 * @since 3.7.0
1199
		 *
1200
		 * @param string jetpack_update_details
1201
		 * @param array Update details calculated by Jetpack::get_update_details
1202
		 */
1203
		do_action( 'add_option_jetpack_update_details', 'jetpack_update_details', Jetpack::get_update_details() );
1204
	}
1205
1206
	public static function refresh_theme_data() {
1207
		/**
1208
		 * Fires whenever a theme change is made.
1209
		 *
1210
		 * @since 3.8.1
1211
		 *
1212
		 * @param string featured_images_enabled
1213
		 * @param boolean Whether featured images are enabled or not
1214
		 */
1215
		do_action( 'add_option_jetpack_featured_images_enabled', 'jetpack_featured_images_enabled', Jetpack::featured_images_enabled() );
1216
	}
1217
1218
	/**
1219
	 * Is Jetpack active?
1220
	 */
1221
	public static function is_active() {
1222
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1223
	}
1224
1225
	/**
1226
	 * Is Jetpack in development (offline) mode?
1227
	 */
1228
	public static function is_development_mode() {
1229
		$development_mode = false;
1230
1231
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1232
			$development_mode = JETPACK_DEV_DEBUG;
1233
		}
1234
1235
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1236
			$development_mode = true;
1237
		}
1238
		/**
1239
		 * Filters Jetpack's development mode.
1240
		 *
1241
		 * @see http://jetpack.com/support/development-mode/
1242
		 *
1243
		 * @since 2.2.1
1244
		 *
1245
		 * @param bool $development_mode Is Jetpack's development mode active.
1246
		 */
1247
		return apply_filters( 'jetpack_development_mode', $development_mode );
1248
	}
1249
1250
	/**
1251
	* Get Jetpack development mode notice text and notice class.
1252
	*
1253
	* Mirrors the checks made in Jetpack::is_development_mode
1254
	*
1255
	*/
1256
	public static function show_development_mode_notice() {
1257
		if ( Jetpack::is_development_mode() ) {
1258
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1259
				$notice = sprintf(
1260
					/* translators: %s is a URL */
1261
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1262
					'http://jetpack.com/support/development-mode/'
1263
				);
1264
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1265
				$notice = sprintf(
1266
					/* translators: %s is a URL */
1267
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1268
					'http://jetpack.com/support/development-mode/'
1269
				);
1270
			} else {
1271
				$notice = sprintf(
1272
					/* translators: %s is a URL */
1273
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1274
					'http://jetpack.com/support/development-mode/'
1275
				);
1276
			}
1277
1278
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1279
		}
1280
1281
		// Throw up a notice if using a development version and as for feedback.
1282
		if ( Jetpack::is_development_version() ) {
1283
			/* translators: %s is a URL */
1284
			$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/' );
1285
1286
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1287
		}
1288
		// Throw up a notice if using staging mode
1289
		if ( Jetpack::is_staging_site() ) {
1290
			/* translators: %s is a URL */
1291
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1292
1293
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1294
		}
1295
	}
1296
1297
	/**
1298
	 * Whether Jetpack's version maps to a public release, or a development version.
1299
	 */
1300
	public static function is_development_version() {
1301
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1302
	}
1303
1304
	/**
1305
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1306
	 */
1307
	public static function is_user_connected( $user_id = false ) {
1308
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1309
		if ( ! $user_id ) {
1310
			return false;
1311
		}
1312
		return (bool) Jetpack_Data::get_access_token( $user_id );
1313
	}
1314
1315
	/**
1316
	 * Get the wpcom user data of the current|specified connected user.
1317
	 */
1318 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1319
		if ( ! $user_id ) {
1320
			$user_id = get_current_user_id();
1321
		}
1322
		Jetpack::load_xml_rpc_client();
1323
		$xml = new Jetpack_IXR_Client( array(
1324
			'user_id' => $user_id,
1325
		) );
1326
		$xml->query( 'wpcom.getUser' );
1327
		if ( ! $xml->isError() ) {
1328
			return $xml->getResponse();
1329
		}
1330
		return false;
1331
	}
1332
1333
	/**
1334
	 * Get the wpcom email of the current|specified connected user.
1335
	 */
1336 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1337
		if ( ! $user_id ) {
1338
			$user_id = get_current_user_id();
1339
		}
1340
		Jetpack::load_xml_rpc_client();
1341
		$xml = new Jetpack_IXR_Client( array(
1342
			'user_id' => $user_id,
1343
		) );
1344
		$xml->query( 'wpcom.getUserEmail' );
1345
		if ( ! $xml->isError() ) {
1346
			return $xml->getResponse();
1347
		}
1348
		return false;
1349
	}
1350
1351
	/**
1352
	 * Get the wpcom email of the master user.
1353
	 */
1354
	public static function get_master_user_email() {
1355
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1356
		if ( $master_user_id ) {
1357
			return self::get_connected_user_email( $master_user_id );
1358
		}
1359
		return '';
1360
	}
1361
1362
	function current_user_is_connection_owner() {
1363
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1364
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1365
	}
1366
1367
	/**
1368
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1369
	 */
1370
	function extra_oembed_providers() {
1371
		// Cloudup: https://dev.cloudup.com/#oembed
1372
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1373
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1374
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1375
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1376
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1377
	}
1378
1379
	/**
1380
	 * Synchronize connected user role changes
1381
	 */
1382
	function user_role_change( $user_id ) {
1383
		if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
1384
			$current_user_id = get_current_user_id();
1385
			wp_set_current_user( $user_id );
1386
			$role = $this->translate_current_user_to_role();
1387
			$signed_role = $this->sign_role( $role );
1388
			wp_set_current_user( $current_user_id );
1389
1390
			$master_token   = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1391
			$master_user_id = absint( $master_token->external_user_id );
1392
1393
			if ( ! $master_user_id )
1394
				return; // this shouldn't happen
1395
1396
			Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
1397
			//@todo retry on failure
1398
1399
			//try to choose a new master if we're demoting the current one
1400 View Code Duplication
			if ( $user_id == $master_user_id && 'administrator' != $role ) {
1401
				$query = new WP_User_Query(
1402
					array(
1403
						'fields'  => array( 'id' ),
1404
						'role'    => 'administrator',
1405
						'orderby' => 'id',
1406
						'exclude' => array( $master_user_id ),
1407
					)
1408
				);
1409
				$new_master = false;
1410
				foreach ( $query->results as $result ) {
1411
					$uid = absint( $result->id );
1412
					if ( $uid && Jetpack::is_user_connected( $uid ) ) {
1413
						$new_master = $uid;
1414
						break;
1415
					}
1416
				}
1417
1418
				if ( $new_master ) {
1419
					Jetpack_Options::update_option( 'master_user', $new_master );
1420
				}
1421
				// else disconnect..?
1422
			}
1423
		}
1424
	}
1425
1426
	/**
1427
	 * Loads the currently active modules.
1428
	 */
1429
	public static function load_modules() {
1430
		if ( ! self::is_active() && !self::is_development_mode() ) {
1431
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1432
				return;
1433
			}
1434
		}
1435
1436
		$version = Jetpack_Options::get_option( 'version' );
1437 View Code Duplication
		if ( ! $version ) {
1438
			$version = $old_version = JETPACK__VERSION . ':' . time();
1439
			/** This action is documented in class.jetpack.php */
1440
			do_action( 'updating_jetpack_version', $version, false );
1441
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1442
		}
1443
		list( $version ) = explode( ':', $version );
1444
1445
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1446
1447
		$modules_data = array();
1448
1449
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1450
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1451
			$updated_modules = array();
1452
			foreach ( $modules as $module ) {
1453
				$modules_data[ $module ] = Jetpack::get_module( $module );
1454
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1455
					continue;
1456
				}
1457
1458
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1459
					continue;
1460
				}
1461
1462
				$updated_modules[] = $module;
1463
			}
1464
1465
			$modules = array_diff( $modules, $updated_modules );
1466
		}
1467
1468
		$is_development_mode = Jetpack::is_development_mode();
1469
1470
		foreach ( $modules as $index => $module ) {
1471
			// If we're in dev mode, disable modules requiring a connection
1472
			if ( $is_development_mode ) {
1473
				// Prime the pump if we need to
1474
				if ( empty( $modules_data[ $module ] ) ) {
1475
					$modules_data[ $module ] = Jetpack::get_module( $module );
1476
				}
1477
				// If the module requires a connection, but we're in local mode, don't include it.
1478
				if ( $modules_data[ $module ]['requires_connection'] ) {
1479
					continue;
1480
				}
1481
			}
1482
1483
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1484
				continue;
1485
			}
1486
1487
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1488
				unset( $modules[ $index ] );
1489
				Jetpack_Options::update_option( 'active_modules', array_values( $modules ) );
1490
				continue;
1491
			}
1492
1493
			/**
1494
			 * Fires when a specific module is loaded.
1495
			 * The dynamic part of the hook, $module, is the module slug.
1496
			 *
1497
			 * @since 1.1.0
1498
			 */
1499
			do_action( 'jetpack_module_loaded_' . $module );
1500
		}
1501
1502
		/**
1503
		 * Fires when all the modules are loaded.
1504
		 *
1505
		 * @since 1.1.0
1506
		 */
1507
		do_action( 'jetpack_modules_loaded' );
1508
1509
		// 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.
1510
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1511
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1512
	}
1513
1514
	/**
1515
	 * Check if Jetpack's REST API compat file should be included
1516
	 * @action plugins_loaded
1517
	 * @return null
1518
	 */
1519
	public function check_rest_api_compat() {
1520
		/**
1521
		 * Filters the list of REST API compat files to be included.
1522
		 *
1523
		 * @since 2.2.5
1524
		 *
1525
		 * @param array $args Array of REST API compat files to include.
1526
		 */
1527
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1528
1529
		if ( function_exists( 'bbpress' ) )
1530
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1531
1532
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1533
			require_once $_jetpack_rest_api_compat_include;
1534
	}
1535
1536
	/**
1537
	 * Gets all plugins currently active in values, regardless of whether they're
1538
	 * traditionally activated or network activated.
1539
	 *
1540
	 * @todo Store the result in core's object cache maybe?
1541
	 */
1542
	public static function get_active_plugins() {
1543
		$active_plugins = (array) get_option( 'active_plugins', array() );
1544
1545
		if ( is_multisite() ) {
1546
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1547
			// whereas active_plugins stores them in the values.
1548
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1549
			if ( $network_plugins ) {
1550
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1551
			}
1552
		}
1553
1554
		sort( $active_plugins );
1555
1556
		return array_unique( $active_plugins );
1557
	}
1558
1559
	/**
1560
	 * Gets and parses additional plugin data to send with the heartbeat data
1561
	 *
1562
	 * @since 3.8.1
1563
	 *
1564
	 * @return array Array of plugin data
1565
	 */
1566
	public static function get_parsed_plugin_data() {
1567
		if ( ! function_exists( 'get_plugins' ) ) {
1568
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1569
		}
1570
		$all_plugins    = get_plugins();
1571
		$active_plugins = Jetpack::get_active_plugins();
1572
1573
		$plugins = array();
1574
		foreach ( $all_plugins as $path => $plugin_data ) {
1575
			$plugins[ $path ] = array(
1576
					'is_active' => in_array( $path, $active_plugins ),
1577
					'file'      => $path,
1578
					'name'      => $plugin_data['Name'],
1579
					'version'   => $plugin_data['Version'],
1580
					'author'    => $plugin_data['Author'],
1581
			);
1582
		}
1583
1584
		return $plugins;
1585
	}
1586
1587
	/**
1588
	 * Gets and parses theme data to send with the heartbeat data
1589
	 *
1590
	 * @since 3.8.1
1591
	 *
1592
	 * @return array Array of theme data
1593
	 */
1594
	public static function get_parsed_theme_data() {
1595
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1596
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1597
1598
		$themes = array();
1599
		foreach ( $all_themes as $slug => $theme_data ) {
1600
			$theme_headers = array();
1601
			foreach ( $header_keys as $header_key ) {
1602
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1603
			}
1604
1605
			$themes[ $slug ] = array(
1606
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1607
					'slug' => $slug,
1608
					'theme_root' => $theme_data->get_theme_root_uri(),
1609
					'parent' => $theme_data->parent(),
1610
					'headers' => $theme_headers
1611
			);
1612
		}
1613
1614
		return $themes;
1615
	}
1616
1617
	/**
1618
	 * Checks whether a specific plugin is active.
1619
	 *
1620
	 * We don't want to store these in a static variable, in case
1621
	 * there are switch_to_blog() calls involved.
1622
	 */
1623
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1624
		return in_array( $plugin, self::get_active_plugins() );
1625
	}
1626
1627
	/**
1628
	 * Check if Jetpack's Open Graph tags should be used.
1629
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1630
	 *
1631
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1632
	 * @action plugins_loaded
1633
	 * @return null
1634
	 */
1635
	public function check_open_graph() {
1636
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1637
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1638
		}
1639
1640
		$active_plugins = self::get_active_plugins();
1641
1642
		if ( ! empty( $active_plugins ) ) {
1643
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1644
				if ( in_array( $plugin, $active_plugins ) ) {
1645
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1646
					break;
1647
				}
1648
			}
1649
		}
1650
1651
		/**
1652
		 * Allow the addition of Open Graph Meta Tags to all pages.
1653
		 *
1654
		 * @since 2.0.3
1655
		 *
1656
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1657
		 */
1658
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1659
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1660
		}
1661
	}
1662
1663
	/**
1664
	 * Check if Jetpack's Twitter tags should be used.
1665
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1666
	 *
1667
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1668
	 * @action plugins_loaded
1669
	 * @return null
1670
	 */
1671
	public function check_twitter_tags() {
1672
1673
		$active_plugins = self::get_active_plugins();
1674
1675
		if ( ! empty( $active_plugins ) ) {
1676
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1677
				if ( in_array( $plugin, $active_plugins ) ) {
1678
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1679
					break;
1680
				}
1681
			}
1682
		}
1683
1684
		/**
1685
		 * Allow Twitter Card Meta tags to be disabled.
1686
		 *
1687
		 * @since 2.6.0
1688
		 *
1689
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1690
		 */
1691
		if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
1692
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1693
		}
1694
	}
1695
1696
1697
1698
1699
	/*
1700
	 *
1701
	 * Jetpack Security Reports
1702
	 *
1703
	 * Allowed types: login_form, backup, file_scanning, spam
1704
	 *
1705
	 * 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)
1706
	 *
1707
	 * 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)
1708
	 *
1709
	 *
1710
	 * Example code to submit a security report:
1711
	 *
1712
	 *  function akismet_submit_jetpack_security_report() {
1713
	 *  	Jetpack::submit_security_report( 'spam', __FILE__, $args = array( 'blocked' => 138284, status => 'ok' ) );
1714
	 *  }
1715
	 *  add_action( 'jetpack_security_report', 'akismet_submit_jetpack_security_report' );
1716
	 *
1717
	 */
1718
1719
1720
	/**
1721
	 * Calls for security report submissions.
1722
	 *
1723
	 * @return null
1724
	 */
1725
	public static function perform_security_reporting() {
1726
		$no_check_needed = get_site_transient( 'security_report_performed_recently' );
1727
1728
		if ( $no_check_needed ) {
1729
			return;
1730
		}
1731
1732
		/**
1733
		 * Fires before a security report is created.
1734
		 *
1735
		 * @since 3.4.0
1736
		 */
1737
		do_action( 'jetpack_security_report' );
1738
1739
		Jetpack_Options::update_option( 'security_report', self::$security_report );
1740
		set_site_transient( 'security_report_performed_recently', 1, 15 * MINUTE_IN_SECONDS );
1741
	}
1742
1743
	/**
1744
	 * Allows plugins to submit security reports.
1745
 	 *
1746
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1747
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1748
	 * @param array   $args         See definitions above
1749
	 */
1750
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1751
1752
		if( !doing_action( 'jetpack_security_report' ) ) {
1753
			return new WP_Error( 'not_collecting_report', 'Not currently collecting security reports.  Please use the jetpack_security_report hook.' );
1754
		}
1755
1756
		if( !is_string( $type ) || !is_string( $plugin_file ) ) {
1757
			return new WP_Error( 'invalid_security_report', 'Invalid Security Report' );
1758
		}
1759
1760
		if( !function_exists( 'get_plugin_data' ) ) {
1761
			include( ABSPATH . 'wp-admin/includes/plugin.php' );
1762
		}
1763
1764
		//Get rid of any non-allowed args
1765
		$args = array_intersect_key( $args, array_flip( array( 'blocked', 'last', 'next', 'status', 'message' ) ) );
1766
1767
		$plugin = get_plugin_data( $plugin_file );
1768
1769
		if ( !$plugin['Name'] ) {
1770
			return new WP_Error( 'security_report_missing_plugin_name', 'Invalid Plugin File Provided' );
1771
		}
1772
1773
		// Sanitize everything to make sure we're not syncing something wonky
1774
		$type = sanitize_key( $type );
1775
1776
		$args['plugin'] = $plugin;
1777
1778
		// Cast blocked, last and next as integers.
1779
		// Last and next should be in unix timestamp format
1780
		if ( isset( $args['blocked'] ) ) {
1781
			$args['blocked'] = (int) $args['blocked'];
1782
		}
1783
		if ( isset( $args['last'] ) ) {
1784
			$args['last'] = (int) $args['last'];
1785
		}
1786
		if ( isset( $args['next'] ) ) {
1787
			$args['next'] = (int) $args['next'];
1788
		}
1789
		if ( !in_array( $args['status'], array( 'ok', 'warning', 'error' ) ) ) {
1790
			$args['status'] = 'ok';
1791
		}
1792
		if ( isset( $args['message'] ) ) {
1793
1794
			if( $args['status'] == 'ok' ) {
1795
				unset( $args['message'] );
1796
			}
1797
1798
			$allowed_html = array(
1799
			    'a' => array(
1800
			        'href' => array(),
1801
			        'title' => array()
1802
			    ),
1803
			    'em' => array(),
1804
			    'strong' => array(),
1805
			);
1806
1807
			$args['message'] = wp_kses( $args['message'], $allowed_html );
1808
		}
1809
1810
		$plugin_name = $plugin[ 'Name' ];
1811
1812
		self::$security_report[ $type ][ $plugin_name ] = $args;
1813
	}
1814
1815
	/**
1816
	 * Collects a new report if needed, then returns it.
1817
	 */
1818
	public function get_security_report() {
1819
		self::perform_security_reporting();
1820
		return Jetpack_Options::get_option( 'security_report' );
1821
	}
1822
1823
1824
/* Jetpack Options API */
1825
1826
	public static function get_option_names( $type = 'compact' ) {
1827
		return Jetpack_Options::get_option_names( $type );
1828
	}
1829
1830
	/**
1831
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1832
 	 *
1833
	 * @param string $name    Option name
1834
	 * @param mixed  $default (optional)
1835
	 */
1836
	public static function get_option( $name, $default = false ) {
1837
		return Jetpack_Options::get_option( $name, $default );
1838
	}
1839
1840
	/**
1841
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1842
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1843
	* $name must be a registered option name.
1844
	*/
1845
	public static function create_nonce( $name ) {
1846
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1847
1848
		Jetpack_Options::update_option( $name, $secret );
1849
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1850
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1851
			return new Jetpack_Error( 'missing_secrets' );
1852
1853
		return array(
1854
			'secret_1' => $secret_1,
1855
			'secret_2' => $secret_2,
1856
			'eol'      => $eol,
1857
		);
1858
	}
1859
1860
	/**
1861
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1862
 	 *
1863
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1864
	 * @param string $name  Option name
1865
	 * @param mixed  $value Option value
1866
	 */
1867
	public static function update_option( $name, $value ) {
1868
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1869
		return Jetpack_Options::update_option( $name, $value );
1870
	}
1871
1872
	/**
1873
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1874
 	 *
1875
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1876
	 * @param array $array array( option name => option value, ... )
1877
	 */
1878
	public static function update_options( $array ) {
1879
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1880
		return Jetpack_Options::update_options( $array );
1881
	}
1882
1883
	/**
1884
	 * Deletes the given option.  May be passed multiple option names as an array.
1885
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1886
	 *
1887
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1888
	 * @param string|array $names
1889
	 */
1890
	public static function delete_option( $names ) {
1891
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1892
		return Jetpack_Options::delete_option( $names );
1893
	}
1894
1895
	/**
1896
	 * Enters a user token into the user_tokens option
1897
	 *
1898
	 * @param int $user_id
1899
	 * @param string $token
1900
	 * return bool
1901
	 */
1902
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1903
		// not designed for concurrent updates
1904
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1905
		if ( ! is_array( $user_tokens ) )
1906
			$user_tokens = array();
1907
		$user_tokens[$user_id] = $token;
1908
		if ( $is_master_user ) {
1909
			$master_user = $user_id;
1910
			$options     = compact( 'user_tokens', 'master_user' );
1911
		} else {
1912
			$options = compact( 'user_tokens' );
1913
		}
1914
		return Jetpack_Options::update_options( $options );
1915
	}
1916
1917
	/**
1918
	 * Returns an array of all PHP files in the specified absolute path.
1919
	 * Equivalent to glob( "$absolute_path/*.php" ).
1920
	 *
1921
	 * @param string $absolute_path The absolute path of the directory to search.
1922
	 * @return array Array of absolute paths to the PHP files.
1923
	 */
1924
	public static function glob_php( $absolute_path ) {
1925
		if ( function_exists( 'glob' ) ) {
1926
			return glob( "$absolute_path/*.php" );
1927
		}
1928
1929
		$absolute_path = untrailingslashit( $absolute_path );
1930
		$files = array();
1931
		if ( ! $dir = @opendir( $absolute_path ) ) {
1932
			return $files;
1933
		}
1934
1935
		while ( false !== $file = readdir( $dir ) ) {
1936
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1937
				continue;
1938
			}
1939
1940
			$file = "$absolute_path/$file";
1941
1942
			if ( ! is_file( $file ) ) {
1943
				continue;
1944
			}
1945
1946
			$files[] = $file;
1947
		}
1948
1949
		closedir( $dir );
1950
1951
		return $files;
1952
	}
1953
1954
	public static function activate_new_modules( $redirect = false ) {
1955
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1956
			return;
1957
		}
1958
1959
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1960 View Code Duplication
		if ( ! $jetpack_old_version ) {
1961
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1962
			/** This action is documented in class.jetpack.php */
1963
			do_action( 'updating_jetpack_version', $version, false );
1964
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1965
		}
1966
1967
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1968
1969
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1970
			return;
1971
		}
1972
1973
		$active_modules     = Jetpack::get_active_modules();
1974
		$reactivate_modules = array();
1975
		foreach ( $active_modules as $active_module ) {
1976
			$module = Jetpack::get_module( $active_module );
1977
			if ( ! isset( $module['changed'] ) ) {
1978
				continue;
1979
			}
1980
1981
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1982
				continue;
1983
			}
1984
1985
			$reactivate_modules[] = $active_module;
1986
			Jetpack::deactivate_module( $active_module );
1987
		}
1988
1989
		$new_version = JETPACK__VERSION . ':' . time();
1990
		/** This action is documented in class.jetpack.php */
1991
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1992
		Jetpack_Options::update_options(
1993
			array(
1994
				'version'     => $new_version,
1995
				'old_version' => $jetpack_old_version,
1996
			)
1997
		);
1998
1999
		Jetpack::state( 'message', 'modules_activated' );
2000
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
2001
2002
		if ( $redirect ) {
2003
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2004
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2005
				$page = $_GET['page'];
2006
			}
2007
2008
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2009
			exit;
2010
		}
2011
	}
2012
2013
	/**
2014
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2015
	 * Make sure to tuck away module "library" files in a sub-directory.
2016
	 */
2017
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2018
		static $modules = null;
2019
2020
		if ( ! isset( $modules ) ) {
2021
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2022
			// Use the cache if we're on the front-end and it's available...
2023
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2024
				$modules = $available_modules_option[ JETPACK__VERSION ];
2025
			} else {
2026
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2027
2028
				$modules = array();
2029
2030
				foreach ( $files as $file ) {
2031
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2032
						continue;
2033
					}
2034
2035
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2036
				}
2037
2038
				Jetpack_Options::update_option( 'available_modules', array(
2039
					JETPACK__VERSION => $modules,
2040
				) );
2041
			}
2042
		}
2043
2044
		/**
2045
		 * Filters the array of modules available to be activated.
2046
		 *
2047
		 * @since 2.4.0
2048
		 *
2049
		 * @param array $modules Array of available modules.
2050
		 * @param string $min_version Minimum version number required to use modules.
2051
		 * @param string $max_version Maximum version number required to use modules.
2052
		 */
2053
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2054
2055
		if ( ! $min_version && ! $max_version ) {
2056
			return array_keys( $mods );
2057
		}
2058
2059
		$r = array();
2060
		foreach ( $mods as $slug => $introduced ) {
2061
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2062
				continue;
2063
			}
2064
2065
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2066
				continue;
2067
			}
2068
2069
			$r[] = $slug;
2070
		}
2071
2072
		return $r;
2073
	}
2074
2075
	/**
2076
	 * Default modules loaded on activation.
2077
	 */
2078
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2079
		$return = array();
2080
2081
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2082
			$module_data = Jetpack::get_module( $module );
2083
2084
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2085
				case 'yes' :
2086
					$return[] = $module;
2087
					break;
2088
				case 'public' :
2089
					if ( Jetpack_Options::get_option( 'public' ) ) {
2090
						$return[] = $module;
2091
					}
2092
					break;
2093
				case 'no' :
2094
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

Loading history...
2095
					break;
2096
			}
2097
		}
2098
		/**
2099
		 * Filters the array of default modules.
2100
		 *
2101
		 * @since 2.5.0
2102
		 *
2103
		 * @param array $return Array of default modules.
2104
		 * @param string $min_version Minimum version number required to use modules.
2105
		 * @param string $max_version Maximum version number required to use modules.
2106
		 */
2107
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2108
	}
2109
2110
	/**
2111
	 * Checks activated modules during auto-activation to determine
2112
	 * if any of those modules are being deprecated.  If so, close
2113
	 * them out, and add any replacement modules.
2114
	 *
2115
	 * Runs at priority 99 by default.
2116
	 *
2117
	 * This is run late, so that it can still activate a module if
2118
	 * the new module is a replacement for another that the user
2119
	 * currently has active, even if something at the normal priority
2120
	 * would kibosh everything.
2121
	 *
2122
	 * @since 2.6
2123
	 * @uses jetpack_get_default_modules filter
2124
	 * @param array $modules
2125
	 * @return array
2126
	 */
2127
	function handle_deprecated_modules( $modules ) {
2128
		$deprecated_modules = array(
2129
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2130
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2131
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2132
		);
2133
2134
		// Don't activate SSO if they never completed activating WPCC.
2135
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2136
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2137
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2138
				$deprecated_modules['wpcc'] = null;
2139
			}
2140
		}
2141
2142
		foreach ( $deprecated_modules as $module => $replacement ) {
2143
			if ( Jetpack::is_module_active( $module ) ) {
2144
				self::deactivate_module( $module );
2145
				if ( $replacement ) {
2146
					$modules[] = $replacement;
2147
				}
2148
			}
2149
		}
2150
2151
		return array_unique( $modules );
2152
	}
2153
2154
	/**
2155
	 * Checks activated plugins during auto-activation to determine
2156
	 * if any of those plugins are in the list with a corresponding module
2157
	 * that is not compatible with the plugin. The module will not be allowed
2158
	 * to auto-activate.
2159
	 *
2160
	 * @since 2.6
2161
	 * @uses jetpack_get_default_modules filter
2162
	 * @param array $modules
2163
	 * @return array
2164
	 */
2165
	function filter_default_modules( $modules ) {
2166
2167
		$active_plugins = self::get_active_plugins();
2168
2169
		if ( ! empty( $active_plugins ) ) {
2170
2171
			// For each module we'd like to auto-activate...
2172
			foreach ( $modules as $key => $module ) {
2173
				// If there are potential conflicts for it...
2174
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2175
					// For each potential conflict...
2176
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2177
						// If that conflicting plugin is active...
2178
						if ( in_array( $plugin, $active_plugins ) ) {
2179
							// Remove that item from being auto-activated.
2180
							unset( $modules[ $key ] );
2181
						}
2182
					}
2183
				}
2184
			}
2185
		}
2186
2187
		return $modules;
2188
	}
2189
2190
	/**
2191
	 * Extract a module's slug from its full path.
2192
	 */
2193
	public static function get_module_slug( $file ) {
2194
		return str_replace( '.php', '', basename( $file ) );
2195
	}
2196
2197
	/**
2198
	 * Generate a module's path from its slug.
2199
	 */
2200
	public static function get_module_path( $slug ) {
2201
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2202
	}
2203
2204
	/**
2205
	 * Load module data from module file. Headers differ from WordPress
2206
	 * plugin headers to avoid them being identified as standalone
2207
	 * plugins on the WordPress plugins page.
2208
	 */
2209
	public static function get_module( $module ) {
2210
		$headers = array(
2211
			'name'                      => 'Module Name',
2212
			'description'               => 'Module Description',
2213
			'jumpstart_desc'            => 'Jumpstart Description',
2214
			'sort'                      => 'Sort Order',
2215
			'recommendation_order'      => 'Recommendation Order',
2216
			'introduced'                => 'First Introduced',
2217
			'changed'                   => 'Major Changes In',
2218
			'deactivate'                => 'Deactivate',
2219
			'free'                      => 'Free',
2220
			'requires_connection'       => 'Requires Connection',
2221
			'auto_activate'             => 'Auto Activate',
2222
			'module_tags'               => 'Module Tags',
2223
			'feature'                   => 'Feature',
2224
			'additional_search_queries' => 'Additional Search Queries',
2225
		);
2226
2227
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2228
2229
		$mod = Jetpack::get_file_data( $file, $headers );
2230
		if ( empty( $mod['name'] ) ) {
2231
			return false;
2232
		}
2233
2234
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2235
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2236
		$mod['deactivate']              = empty( $mod['deactivate'] );
2237
		$mod['free']                    = empty( $mod['free'] );
2238
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2239
2240
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2241
			$mod['auto_activate'] = 'No';
2242
		} else {
2243
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2244
		}
2245
2246
		if ( $mod['module_tags'] ) {
2247
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2248
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2249
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2250
		} else {
2251
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2252
		}
2253
2254
		if ( $mod['feature'] ) {
2255
			$mod['feature'] = explode( ',', $mod['feature'] );
2256
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2257
		} else {
2258
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2259
		}
2260
2261
		/**
2262
		 * Filters the feature array on a module.
2263
		 *
2264
		 * This filter allows you to control where each module is filtered: Recommended,
2265
		 * Jumpstart, and the default "Other" listing.
2266
		 *
2267
		 * @since 3.5.0
2268
		 *
2269
		 * @param array   $mod['feature'] The areas to feature this module:
2270
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2271
		 *     'Recommended' shows on the main Jetpack admin screen.
2272
		 *     'Other' should be the default if no other value is in the array.
2273
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2274
		 * @param array   $mod All the currently assembled module data.
2275
		 */
2276
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2277
2278
		/**
2279
		 * Filter the returned data about a module.
2280
		 *
2281
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2282
		 * so please be careful.
2283
		 *
2284
		 * @since 3.6.0
2285
		 *
2286
		 * @param array   $mod    The details of the requested module.
2287
		 * @param string  $module The slug of the module, e.g. sharedaddy
2288
		 * @param string  $file   The path to the module source file.
2289
		 */
2290
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2291
	}
2292
2293
	/**
2294
	 * Like core's get_file_data implementation, but caches the result.
2295
	 */
2296
	public static function get_file_data( $file, $headers ) {
2297
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2298
		$file_name = basename( $file );
2299
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2300
		$key              = md5( $file_name . serialize( $headers ) );
2301
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2302
2303
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2304
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2305
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2306
		}
2307
2308
		$data = get_file_data( $file, $headers );
2309
2310
		// Strip out any old Jetpack versions that are cluttering the option.
2311
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2312
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2313
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2314
2315
		return $data;
2316
	}
2317
2318
	/**
2319
	 * Return translated module tag.
2320
	 *
2321
	 * @param string $tag Tag as it appears in each module heading.
2322
	 *
2323
	 * @return mixed
2324
	 */
2325
	public static function translate_module_tag( $tag ) {
2326
		return jetpack_get_module_i18n_tag( $tag );
2327
	}
2328
2329
	/**
2330
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2331
	 *
2332
	 * @since 3.9.2
2333
	 *
2334
	 * @param array $modules
2335
	 *
2336
	 * @return string|void
2337
	 */
2338
	public static function get_translated_modules( $modules ) {
2339
		foreach ( $modules as $index => $module ) {
2340
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2341
			if ( isset( $module['name'] ) ) {
2342
				$modules[ $index ]['name'] = $i18n_module['name'];
2343
			}
2344
			if ( isset( $module['description'] ) ) {
2345
				$modules[ $index ]['description'] = $i18n_module['description'];
2346
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2347
			}
2348
		}
2349
		return $modules;
2350
	}
2351
2352
	/**
2353
	 * Get a list of activated modules as an array of module slugs.
2354
	 */
2355
	public static function get_active_modules() {
2356
		$active = Jetpack_Options::get_option( 'active_modules' );
2357
		if ( ! is_array( $active ) )
2358
			$active = array();
2359
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2360
			$active[] = 'vaultpress';
2361
		} else {
2362
			$active = array_diff( $active, array( 'vaultpress' ) );
2363
		}
2364
2365
		//If protect is active on the main site of a multisite, it should be active on all sites.
2366
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2367
			$active[] = 'protect';
2368
		}
2369
2370
		return array_unique( $active );
2371
	}
2372
2373
	/**
2374
	 * Check whether or not a Jetpack module is active.
2375
	 *
2376
	 * @param string $module The slug of a Jetpack module.
2377
	 * @return bool
2378
	 *
2379
	 * @static
2380
	 */
2381
	public static function is_module_active( $module ) {
2382
		return in_array( $module, self::get_active_modules() );
2383
	}
2384
2385
	public static function is_module( $module ) {
2386
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2387
	}
2388
2389
	/**
2390
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2391
	 *
2392
	 * @param bool $catch True to start catching, False to stop.
2393
	 *
2394
	 * @static
2395
	 */
2396
	public static function catch_errors( $catch ) {
2397
		static $display_errors, $error_reporting;
2398
2399
		if ( $catch ) {
2400
			$display_errors  = @ini_set( 'display_errors', 1 );
2401
			$error_reporting = @error_reporting( E_ALL );
2402
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2403
		} else {
2404
			@ini_set( 'display_errors', $display_errors );
2405
			@error_reporting( $error_reporting );
2406
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2407
		}
2408
	}
2409
2410
	/**
2411
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2412
	 */
2413
	public static function catch_errors_on_shutdown() {
2414
		Jetpack::state( 'php_errors', ob_get_clean() );
2415
	}
2416
2417
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2418
		$jetpack = Jetpack::init();
2419
2420
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2421
		$modules = array_merge( $other_modules, $modules );
2422
2423
		// Look for standalone plugins and disable if active.
2424
2425
		$to_deactivate = array();
2426
		foreach ( $modules as $module ) {
2427
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2428
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2429
			}
2430
		}
2431
2432
		$deactivated = array();
2433
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2434
			list( $probable_file, $probable_title ) = $deactivate_me;
2435
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2436
				$deactivated[] = $module;
2437
			}
2438
		}
2439
2440
		if ( $deactivated && $redirect ) {
2441
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2442
2443
			$url = add_query_arg(
2444
				array(
2445
					'action'   => 'activate_default_modules',
2446
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2447
				),
2448
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2449
			);
2450
			wp_safe_redirect( $url );
2451
			exit;
2452
		}
2453
2454
		/**
2455
		 * Fires before default modules are activated.
2456
		 *
2457
		 * @since 1.9.0
2458
		 *
2459
		 * @param string $min_version Minimum version number required to use modules.
2460
		 * @param string $max_version Maximum version number required to use modules.
2461
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2462
		 */
2463
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2464
2465
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2466
		Jetpack::restate();
2467
		Jetpack::catch_errors( true );
2468
2469
		$active = Jetpack::get_active_modules();
2470
2471
		foreach ( $modules as $module ) {
2472
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2473
				$active[] = $module;
2474
				Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2475
				continue;
2476
			}
2477
2478
			if ( in_array( $module, $active ) ) {
2479
				$module_info = Jetpack::get_module( $module );
2480
				if ( ! $module_info['deactivate'] ) {
2481
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2482 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2483
						$active_state = explode( ',', $active_state );
2484
					} else {
2485
						$active_state = array();
2486
					}
2487
					$active_state[] = $module;
2488
					Jetpack::state( $state, implode( ',', $active_state ) );
2489
				}
2490
				continue;
2491
			}
2492
2493
			$file = Jetpack::get_module_path( $module );
2494
			if ( ! file_exists( $file ) ) {
2495
				continue;
2496
			}
2497
2498
			// we'll override this later if the plugin can be included without fatal error
2499
			if ( $redirect ) {
2500
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2501
			}
2502
			Jetpack::state( 'error', 'module_activation_failed' );
2503
			Jetpack::state( 'module', $module );
2504
			ob_start();
2505
			require $file;
2506
			/**
2507
			 * Fires when a specific module is activated.
2508
			 *
2509
			 * @since 1.9.0
2510
			 *
2511
			 * @param string $module Module slug.
2512
			 */
2513
			do_action( 'jetpack_activate_module', $module );
2514
			$active[] = $module;
2515
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2516 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2517
				$active_state = explode( ',', $active_state );
2518
			} else {
2519
				$active_state = array();
2520
			}
2521
			$active_state[] = $module;
2522
			Jetpack::state( $state, implode( ',', $active_state ) );
2523
			Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2524
			ob_end_clean();
2525
		}
2526
		Jetpack::state( 'error', false );
2527
		Jetpack::state( 'module', false );
2528
		Jetpack::catch_errors( false );
2529
		/**
2530
		 * Fires when default modules are activated.
2531
		 *
2532
		 * @since 1.9.0
2533
		 *
2534
		 * @param string $min_version Minimum version number required to use modules.
2535
		 * @param string $max_version Maximum version number required to use modules.
2536
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2537
		 */
2538
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2539
	}
2540
2541
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2542
		/**
2543
		 * Fires before a module is activated.
2544
		 *
2545
		 * @since 2.6.0
2546
		 *
2547
		 * @param string $module Module slug.
2548
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2549
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2550
		 */
2551
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2552
2553
		$jetpack = Jetpack::init();
2554
2555
		if ( ! strlen( $module ) )
2556
			return false;
2557
2558
		if ( ! Jetpack::is_module( $module ) )
2559
			return false;
2560
2561
		// If it's already active, then don't do it again
2562
		$active = Jetpack::get_active_modules();
2563
		foreach ( $active as $act ) {
2564
			if ( $act == $module )
2565
				return true;
2566
		}
2567
2568
		$module_data = Jetpack::get_module( $module );
2569
2570
		if ( ! Jetpack::is_active() ) {
2571
			if ( !Jetpack::is_development_mode() )
2572
				return false;
2573
2574
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2575
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2576
				return false;
2577
		}
2578
2579
		// Check and see if the old plugin is active
2580
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2581
			// Deactivate the old plugin
2582
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2583
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2584
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2585
				Jetpack::state( 'deactivated_plugins', $module );
2586
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2587
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2588
			}
2589
		}
2590
2591
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2592
		Jetpack::state( 'module', $module );
2593
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2594
2595
		Jetpack::catch_errors( true );
2596
		ob_start();
2597
		require Jetpack::get_module_path( $module );
2598
		/** This action is documented in class.jetpack.php */
2599
		do_action( 'jetpack_activate_module', $module );
2600
		$active[] = $module;
2601
		Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
2602
		Jetpack::state( 'error', false ); // the override
2603
		Jetpack::state( 'message', 'module_activated' );
2604
		Jetpack::state( 'module', $module );
2605
		ob_end_clean();
2606
		Jetpack::catch_errors( false );
2607
2608
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2609 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2610
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2611
2612
			//Jump start is being dismissed send data to MC Stats
2613
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2614
2615
			$jetpack->do_stats( 'server_side' );
2616
		}
2617
2618
		if ( $redirect ) {
2619
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2620
		}
2621
		if ( $exit ) {
2622
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate_module() contains an exit expression.

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

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

Loading history...
2623
		}
2624
		return true;
2625
	}
2626
2627
	function activate_module_actions( $module ) {
2628
		/**
2629
		 * Fires when a module is activated.
2630
		 * The dynamic part of the filter, $module, is the module slug.
2631
		 *
2632
		 * @since 1.9.0
2633
		 *
2634
		 * @param string $module Module slug.
2635
		 */
2636
		do_action( "jetpack_activate_module_$module", $module );
2637
	}
2638
2639
	public static function deactivate_module( $module ) {
2640
		/**
2641
		 * Fires when a module is deactivated.
2642
		 *
2643
		 * @since 1.9.0
2644
		 *
2645
		 * @param string $module Module slug.
2646
		 */
2647
		do_action( 'jetpack_pre_deactivate_module', $module );
2648
2649
		$jetpack = Jetpack::init();
2650
2651
		$active = Jetpack::get_active_modules();
2652
		$new    = array_filter( array_diff( $active, (array) $module ) );
2653
2654
		/**
2655
		 * Fires when a module is deactivated.
2656
		 * The dynamic part of the filter, $module, is the module slug.
2657
		 *
2658
		 * @since 1.9.0
2659
		 *
2660
		 * @param string $module Module slug.
2661
		 */
2662
		do_action( "jetpack_deactivate_module_$module", $module );
2663
2664
		// A flag for Jump Start so it's not shown again.
2665 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2666
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2667
2668
			//Jump start is being dismissed send data to MC Stats
2669
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2670
2671
			$jetpack->do_stats( 'server_side' );
2672
		}
2673
2674
		return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
2675
	}
2676
2677
	public static function enable_module_configurable( $module ) {
2678
		$module = Jetpack::get_module_slug( $module );
2679
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2680
	}
2681
2682
	public static function module_configuration_url( $module ) {
2683
		$module = Jetpack::get_module_slug( $module );
2684
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2685
	}
2686
2687
	public static function module_configuration_load( $module, $method ) {
2688
		$module = Jetpack::get_module_slug( $module );
2689
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2690
	}
2691
2692
	public static function module_configuration_head( $module, $method ) {
2693
		$module = Jetpack::get_module_slug( $module );
2694
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2695
	}
2696
2697
	public static function module_configuration_screen( $module, $method ) {
2698
		$module = Jetpack::get_module_slug( $module );
2699
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2700
	}
2701
2702
	public static function module_configuration_activation_screen( $module, $method ) {
2703
		$module = Jetpack::get_module_slug( $module );
2704
		add_action( 'display_activate_module_setting_' . $module, $method );
2705
	}
2706
2707
/* Installation */
2708
2709
	public static function bail_on_activation( $message, $deactivate = true ) {
2710
?>
2711
<!doctype html>
2712
<html>
2713
<head>
2714
<meta charset="<?php bloginfo( 'charset' ); ?>">
2715
<style>
2716
* {
2717
	text-align: center;
2718
	margin: 0;
2719
	padding: 0;
2720
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2721
}
2722
p {
2723
	margin-top: 1em;
2724
	font-size: 18px;
2725
}
2726
</style>
2727
<body>
2728
<p><?php echo esc_html( $message ); ?></p>
2729
</body>
2730
</html>
2731
<?php
2732
		if ( $deactivate ) {
2733
			$plugins = get_option( 'active_plugins' );
2734
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2735
			$update  = false;
2736
			foreach ( $plugins as $i => $plugin ) {
2737
				if ( $plugin === $jetpack ) {
2738
					$plugins[$i] = false;
2739
					$update = true;
2740
				}
2741
			}
2742
2743
			if ( $update ) {
2744
				update_option( 'active_plugins', array_filter( $plugins ) );
2745
			}
2746
		}
2747
		exit;
2748
	}
2749
2750
	/**
2751
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2752
	 * @static
2753
	 */
2754
	public static function plugin_activation( $network_wide ) {
2755
		Jetpack_Options::update_option( 'activated', 1 );
2756
2757
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2758
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2759
		}
2760
2761
		if ( $network_wide )
2762
			Jetpack::state( 'network_nag', true );
2763
2764
		Jetpack::plugin_initialize();
2765
	}
2766
	/**
2767
	 * Runs before bumping version numbers up to a new version
2768
	 * @param  (string) $version    Version:timestamp
2769
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2770
	 * @return null              [description]
2771
	 */
2772
	public static function do_version_bump( $version, $old_version ) {
2773
2774
		if ( ! $old_version ) { // For new sites
2775
			// Setting up jetpack manage
2776
			Jetpack::activate_manage();
2777
		}
2778
	}
2779
2780
	/**
2781
	 * Sets the internal version number and activation state.
2782
	 * @static
2783
	 */
2784
	public static function plugin_initialize() {
2785
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2786
			Jetpack_Options::update_option( 'activated', 2 );
2787
		}
2788
2789 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2790
			$version = $old_version = JETPACK__VERSION . ':' . time();
2791
			/** This action is documented in class.jetpack.php */
2792
			do_action( 'updating_jetpack_version', $version, false );
2793
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2794
		}
2795
2796
		Jetpack::load_modules();
2797
2798
		Jetpack_Options::delete_option( 'do_activate' );
2799
	}
2800
2801
	/**
2802
	 * Removes all connection options
2803
	 * @static
2804
	 */
2805
	public static function plugin_deactivation( ) {
2806
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2807
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2808
			Jetpack_Network::init()->deactivate();
2809
		} else {
2810
			Jetpack::disconnect( false );
2811
			//Jetpack_Heartbeat::init()->deactivate();
2812
		}
2813
	}
2814
2815
	/**
2816
	 * Disconnects from the Jetpack servers.
2817
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2818
	 * @static
2819
	 */
2820
	public static function disconnect( $update_activated_state = true ) {
2821
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2822
		Jetpack::clean_nonces( true );
2823
2824
		Jetpack::load_xml_rpc_client();
2825
		$xml = new Jetpack_IXR_Client();
2826
		$xml->query( 'jetpack.deregister' );
2827
2828
		Jetpack_Options::delete_option(
2829
			array(
2830
				'register',
2831
				'blog_token',
2832
				'user_token',
2833
				'user_tokens',
2834
				'master_user',
2835
				'time_diff',
2836
				'fallback_no_verify_ssl_certs',
2837
			)
2838
		);
2839
2840
		if ( $update_activated_state ) {
2841
			Jetpack_Options::update_option( 'activated', 4 );
2842
		}
2843
2844
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
2845
		// Check then record unique disconnection if site has never been disconnected previously
2846
		if ( -1 == $jetpack_unique_connection['disconnected'] ) {
2847
			$jetpack_unique_connection['disconnected'] = 1;
2848
		}
2849
		else {
2850
			if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2851
				//track unique disconnect
2852
				$jetpack = Jetpack::init();
2853
2854
				$jetpack->stat( 'connections', 'unique-disconnect' );
2855
				$jetpack->do_stats( 'server_side' );
2856
			}
2857
			// increment number of times disconnected
2858
			$jetpack_unique_connection['disconnected'] += 1;
2859
		}
2860
2861
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2862
2863
		// Disable the Heartbeat cron
2864
		Jetpack_Heartbeat::init()->deactivate();
2865
	}
2866
2867
	/**
2868
	 * Unlinks the current user from the linked WordPress.com user
2869
	 */
2870
	public static function unlink_user( $user_id = null ) {
2871
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2872
			return false;
2873
2874
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2875
2876
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2877
			return false;
2878
2879
		if ( ! isset( $tokens[ $user_id ] ) )
2880
			return false;
2881
2882
		Jetpack::load_xml_rpc_client();
2883
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2884
		$xml->query( 'jetpack.unlink_user', $user_id );
2885
2886
		unset( $tokens[ $user_id ] );
2887
2888
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2889
2890
		/**
2891
		 * Fires after the current user has been unlinked from WordPress.com.
2892
		 *
2893
		 * @since 4.1.0
2894
		 *
2895
		 * @param int $user_id The current user's ID.
2896
		 */
2897
		do_action( 'jetpack_unlinked_user', $user_id );
2898
2899
		return true;
2900
	}
2901
2902
	/**
2903
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2904
	 */
2905
	public static function try_registration() {
2906
		// Let's get some testing in beta versions and such.
2907
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2908
			// Before attempting to connect, let's make sure that the domains are viable.
2909
			$domains_to_check = array_unique( array(
2910
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2911
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2912
			) );
2913
			foreach ( $domains_to_check as $domain ) {
2914
				$result = Jetpack_Data::is_usable_domain( $domain );
2915
				if ( is_wp_error( $result ) ) {
2916
					return $result;
2917
				}
2918
			}
2919
		}
2920
2921
		$result = Jetpack::register();
2922
2923
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2924
		if ( ! $result || is_wp_error( $result ) ) {
2925
			return $result;
2926
		} else {
2927
			return true;
2928
		}
2929
	}
2930
2931
	/**
2932
	 * Tracking an internal event log. Try not to put too much chaff in here.
2933
	 *
2934
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2935
	 */
2936
	public static function log( $code, $data = null ) {
2937
		// only grab the latest 200 entries
2938
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2939
2940
		// Append our event to the log
2941
		$log_entry = array(
2942
			'time'    => time(),
2943
			'user_id' => get_current_user_id(),
2944
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2945
			'code'    => $code,
2946
		);
2947
		// Don't bother storing it unless we've got some.
2948
		if ( ! is_null( $data ) ) {
2949
			$log_entry['data'] = $data;
2950
		}
2951
		$log[] = $log_entry;
2952
2953
		// Try add_option first, to make sure it's not autoloaded.
2954
		// @todo: Add an add_option method to Jetpack_Options
2955
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2956
			Jetpack_Options::update_option( 'log', $log );
2957
		}
2958
2959
		/**
2960
		 * Fires when Jetpack logs an internal event.
2961
		 *
2962
		 * @since 3.0.0
2963
		 *
2964
		 * @param array $log_entry {
2965
		 *	Array of details about the log entry.
2966
		 *
2967
		 *	@param string time Time of the event.
2968
		 *	@param int user_id ID of the user who trigerred the event.
2969
		 *	@param int blog_id Jetpack Blog ID.
2970
		 *	@param string code Unique name for the event.
2971
		 *	@param string data Data about the event.
2972
		 * }
2973
		 */
2974
		do_action( 'jetpack_log_entry', $log_entry );
2975
	}
2976
2977
	/**
2978
	 * Get the internal event log.
2979
	 *
2980
	 * @param $event (string) - only return the specific log events
2981
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2982
	 *
2983
	 * @return array of log events || WP_Error for invalid params
2984
	 */
2985
	public static function get_log( $event = false, $num = false ) {
2986
		if ( $event && ! is_string( $event ) ) {
2987
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2988
		}
2989
2990
		if ( $num && ! is_numeric( $num ) ) {
2991
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2992
		}
2993
2994
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2995
2996
		// If nothing set - act as it did before, otherwise let's start customizing the output
2997
		if ( ! $num && ! $event ) {
2998
			return $entire_log;
2999
		} else {
3000
			$entire_log = array_reverse( $entire_log );
3001
		}
3002
3003
		$custom_log_output = array();
3004
3005
		if ( $event ) {
3006
			foreach ( $entire_log as $log_event ) {
3007
				if ( $event == $log_event[ 'code' ] ) {
3008
					$custom_log_output[] = $log_event;
3009
				}
3010
			}
3011
		} else {
3012
			$custom_log_output = $entire_log;
3013
		}
3014
3015
		if ( $num ) {
3016
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3017
		}
3018
3019
		return $custom_log_output;
3020
	}
3021
3022
	/**
3023
	 * Log modification of important settings.
3024
	 */
3025
	public static function log_settings_change( $option, $old_value, $value ) {
0 ignored issues
show
The parameter $old_value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
3026
		switch( $option ) {
3027
			case 'jetpack_sync_non_public_post_stati':
3028
				self::log( $option, $value );
3029
				break;
3030
		}
3031
	}
3032
3033
	/**
3034
	 * Return stat data for WPCOM sync
3035
	 */
3036
	function get_stat_data() {
3037
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
3038
		$additional_data = $this->get_additional_stat_data();
3039
3040
		return json_encode( array_merge( $heartbeat_data, $additional_data ) );
3041
	}
3042
3043
	/**
3044
	 * Get additional stat data to sync to WPCOM
3045
	 */
3046
	function get_additional_stat_data( $prefix = '' ) {
3047
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3048
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3049
		$return["{$prefix}users"]          = count_users();
3050
		$return["{$prefix}site-count"]     = 0;
3051
		if ( function_exists( 'get_blog_count' ) ) {
3052
			$return["{$prefix}site-count"] = get_blog_count();
3053
		}
3054
		return $return;
3055
	}
3056
3057
	/* Admin Pages */
3058
3059
	function admin_init() {
3060
		// If the plugin is not connected, display a connect message.
3061
		if (
3062
			// the plugin was auto-activated and needs its candy
3063
			Jetpack_Options::get_option( 'do_activate' )
3064
		||
3065
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3066
			! Jetpack_Options::get_option( 'activated' )
3067
		) {
3068
			Jetpack::plugin_initialize();
3069
		}
3070
3071
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3072
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
3073
				// Show connect notice on dashboard and plugins pages
3074
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
3075
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
3076
			}
3077
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3078
			// Upgrade: 1.1 -> 1.1.1
3079
			// Check and see if host can verify the Jetpack servers' SSL certificate
3080
			$args = array();
3081
			Jetpack_Client::_wp_remote_request(
3082
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3083
				$args,
3084
				true
3085
			);
3086
		} else {
3087
			// Show the notice on the Dashboard only for now
3088
3089
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3090
3091
			// Identity crisis notices
3092
			add_action( 'jetpack_notices', array( $this, 'alert_identity_crisis' ) );
3093
		}
3094
3095
		// If the plugin has just been disconnected from WP.com, show the survey notice
3096
		if ( isset( $_GET['disconnected'] ) && 'true' === $_GET['disconnected'] ) {
3097
			add_action( 'jetpack_notices', array( $this, 'disconnect_survey_notice' ) );
3098
		}
3099
3100
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3101
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3102
		}
3103
3104
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3105
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3106
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3107
3108
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3109
			// Artificially throw errors in certain whitelisted cases during plugin activation
3110
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3111
3112
			// Kick off synchronization of user role when it changes
3113
			add_action( 'set_user_role', array( $this, 'user_role_change' ) );
3114
		}
3115
3116
		// Jetpack Manage Activation Screen from .com
3117
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3118
	}
3119
3120
	function admin_body_class( $admin_body_class = '' ) {
3121
		$classes = explode( ' ', trim( $admin_body_class ) );
3122
3123
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3124
3125
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3126
		return " $admin_body_class ";
3127
	}
3128
3129
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3130
		return $admin_body_class . ' jetpack-pagestyles ';
3131
	}
3132
3133
	function prepare_connect_notice() {
3134
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3135
3136
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
3137
3138
		if ( Jetpack::state( 'network_nag' ) )
3139
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
3140
	}
3141
	/**
3142
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3143
	 *
3144
	 * @return null
3145
	 */
3146
	function prepare_manage_jetpack_notice() {
3147
3148
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3149
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3150
	}
3151
3152
	function manage_activate_screen() {
3153
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3154
	}
3155
	/**
3156
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3157
	 * This function artificially throws errors for such cases (whitelisted).
3158
	 *
3159
	 * @param string $plugin The activated plugin.
3160
	 */
3161
	function throw_error_on_activate_plugin( $plugin ) {
3162
		$active_modules = Jetpack::get_active_modules();
3163
3164
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3165
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3166
			$throw = false;
3167
3168
			// Try and make sure it really was the stats plugin
3169
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3170
				if ( 'stats.php' == basename( $plugin ) ) {
3171
					$throw = true;
3172
				}
3173
			} else {
3174
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3175
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3176
					$throw = true;
3177
				}
3178
			}
3179
3180
			if ( $throw ) {
3181
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3182
			}
3183
		}
3184
	}
3185
3186
	function intercept_plugin_error_scrape_init() {
3187
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3188
	}
3189
3190
	function intercept_plugin_error_scrape( $action, $result ) {
3191
		if ( ! $result ) {
3192
			return;
3193
		}
3194
3195
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3196
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3197
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3198
			}
3199
		}
3200
	}
3201
3202
	function add_remote_request_handlers() {
3203
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3204
	}
3205
3206
	function remote_request_handlers() {
3207
		switch ( current_filter() ) {
3208
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3209
			$response = $this->upload_handler();
3210
			break;
3211
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

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

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

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

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