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

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

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

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