Completed
Push — update/connection-banner-not-c... ( 4c46f6 )
by
unknown
08:27
created

class.jetpack.php (7 issues)

Upgrade to new PHP Analysis Engine

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

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