Completed
Push — add/notice-if-sync-large-sync-... ( 4cc037 )
by
unknown
15:07 queued 05:11
created

class.jetpack.php (7 issues)

Upgrade to new PHP Analysis Engine

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

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