Completed
Push — fix/videopress-always-active-o... ( 287475...1c7a58 )
by
unknown
09:03 queued 01:23
created

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

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

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

Loading history...
3599 View Code Duplication
			case 'deactivate' :
3600
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3601
					$error = 'cheatin';
3602
					break;
3603
				}
3604
3605
				$modules = stripslashes( $_GET['module'] );
3606
				check_admin_referer( "jetpack_deactivate-$modules" );
3607
				foreach ( explode( ',', $modules ) as $module ) {
3608
					Jetpack::log( 'deactivate', $module );
3609
					Jetpack::deactivate_module( $module );
3610
					Jetpack::state( 'message', 'module_deactivated' );
3611
				}
3612
				Jetpack::state( 'module', $modules );
3613
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3614
				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...
3615
			case 'unlink' :
3616
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3617
				check_admin_referer( 'jetpack-unlink' );
3618
				Jetpack::log( 'unlink' );
3619
				$this->unlink_user();
3620
				Jetpack::state( 'message', 'unlinked' );
3621
				if ( 'sub-unlink' == $redirect ) {
3622
					wp_safe_redirect( admin_url() );
3623
				} else {
3624
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3625
				}
3626
				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...
3627
			default:
3628
				/**
3629
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3630
				 *
3631
				 * @since 2.6.0
3632
				 *
3633
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3634
				 */
3635
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3636
			}
3637
		}
3638
3639
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3640
			self::activate_new_modules( true );
3641
		}
3642
3643
		$message_code = Jetpack::state( 'message' );
3644
		if ( Jetpack::state( 'optin-manage' ) ) {
3645
			$activated_manage = $message_code;
3646
			$message_code = 'jetpack-manage';
3647
		}
3648
3649
		switch ( $message_code ) {
3650
		case 'jetpack-manage':
3651
			$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>';
3652
			if ( $activated_manage ) {
3653
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3654
			}
3655
			break;
3656
3657
		}
3658
3659
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3660
3661
		if ( ! empty( $deactivated_plugins ) ) {
3662
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3663
			$deactivated_titles  = array();
3664
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3665
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3666
					continue;
3667
				}
3668
3669
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3670
			}
3671
3672
			if ( $deactivated_titles ) {
3673
				if ( $this->message ) {
3674
					$this->message .= "<br /><br />\n";
3675
				}
3676
3677
				$this->message .= wp_sprintf(
3678
					_n(
3679
						'Jetpack contains the most recent version of the old %l plugin.',
3680
						'Jetpack contains the most recent versions of the old %l plugins.',
3681
						count( $deactivated_titles ),
3682
						'jetpack'
3683
					),
3684
					$deactivated_titles
3685
				);
3686
3687
				$this->message .= "<br />\n";
3688
3689
				$this->message .= _n(
3690
					'The old version has been deactivated and can be removed from your site.',
3691
					'The old versions have been deactivated and can be removed from your site.',
3692
					count( $deactivated_titles ),
3693
					'jetpack'
3694
				);
3695
			}
3696
		}
3697
3698
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3699
3700
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3701
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3702
		}
3703
3704 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3705
			/**
3706
			 * Fires when a module configuration page is loaded.
3707
			 * The dynamic part of the hook is the configure parameter from the URL.
3708
			 *
3709
			 * @since 1.1.0
3710
			 */
3711
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3712
		}
3713
3714
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3715
	}
3716
3717
	function admin_notices() {
3718
3719
		if ( $this->error ) {
3720
?>
3721
<div id="message" class="jetpack-message jetpack-err">
3722
	<div class="squeezer">
3723
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3724
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3725
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3726
<?php	endif; ?>
3727
	</div>
3728
</div>
3729
<?php
3730
		}
3731
3732
		if ( $this->message ) {
3733
?>
3734
<div id="message" class="jetpack-message">
3735
	<div class="squeezer">
3736
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3737
	</div>
3738
</div>
3739
<?php
3740
		}
3741
3742
		if ( $this->privacy_checks ) :
3743
			$module_names = $module_slugs = array();
3744
3745
			$privacy_checks = explode( ',', $this->privacy_checks );
3746
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3747
			foreach ( $privacy_checks as $module_slug ) {
3748
				$module = Jetpack::get_module( $module_slug );
3749
				if ( ! $module ) {
3750
					continue;
3751
				}
3752
3753
				$module_slugs[] = $module_slug;
3754
				$module_names[] = "<strong>{$module['name']}</strong>";
3755
			}
3756
3757
			$module_slugs = join( ',', $module_slugs );
3758
?>
3759
<div id="message" class="jetpack-message jetpack-err">
3760
	<div class="squeezer">
3761
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3762
		<p><?php
3763
			echo wp_kses(
3764
				wptexturize(
3765
					wp_sprintf(
3766
						_nx(
3767
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3768
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3769
							count( $privacy_checks ),
3770
							'%l = list of Jetpack module/feature names',
3771
							'jetpack'
3772
						),
3773
						$module_names
3774
					)
3775
				),
3776
				array( 'strong' => true )
3777
			);
3778
3779
			echo "\n<br />\n";
3780
3781
			echo wp_kses(
3782
				sprintf(
3783
					_nx(
3784
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3785
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3786
						count( $privacy_checks ),
3787
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3788
						'jetpack'
3789
					),
3790
					wp_nonce_url(
3791
						Jetpack::admin_url(
3792
							array(
3793
								'page'   => 'jetpack',
3794
								'action' => 'deactivate',
3795
								'module' => urlencode( $module_slugs ),
3796
							)
3797
						),
3798
						"jetpack_deactivate-$module_slugs"
3799
					),
3800
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3801
				),
3802
				array( 'a' => array( 'href' => true, 'title' => true ) )
3803
			);
3804
		?></p>
3805
	</div>
3806
</div>
3807
<?php endif;
3808
	// only display the notice if the other stuff is not there
3809
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3810
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3811
			$this->opt_in_jetpack_manage_notice();
3812
		}
3813
	}
3814
3815
	/**
3816
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3817
	 */
3818
	function stat( $group, $detail ) {
3819
		if ( ! isset( $this->stats[ $group ] ) )
3820
			$this->stats[ $group ] = array();
3821
		$this->stats[ $group ][] = $detail;
3822
	}
3823
3824
	/**
3825
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3826
	 */
3827
	function do_stats( $method = '' ) {
3828
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3829
			foreach ( $this->stats as $group => $stats ) {
3830
				if ( is_array( $stats ) && count( $stats ) ) {
3831
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3832
					if ( 'server_side' === $method ) {
3833
						self::do_server_side_stat( $args );
3834
					} else {
3835
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3836
					}
3837
				}
3838
				unset( $this->stats[ $group ] );
3839
			}
3840
		}
3841
	}
3842
3843
	/**
3844
	 * Runs stats code for a one-off, server-side.
3845
	 *
3846
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3847
	 *
3848
	 * @return bool If it worked.
3849
	 */
3850
	static function do_server_side_stat( $args ) {
3851
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3852
		if ( is_wp_error( $response ) )
3853
			return false;
3854
3855
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3856
			return false;
3857
3858
		return true;
3859
	}
3860
3861
	/**
3862
	 * Builds the stats url.
3863
	 *
3864
	 * @param $args array|string The arguments to append to the URL.
3865
	 *
3866
	 * @return string The URL to be pinged.
3867
	 */
3868
	static function build_stats_url( $args ) {
3869
		$defaults = array(
3870
			'v'    => 'wpcom2',
3871
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3872
		);
3873
		$args     = wp_parse_args( $args, $defaults );
3874
		/**
3875
		 * Filter the URL used as the Stats tracking pixel.
3876
		 *
3877
		 * @since 2.3.2
3878
		 *
3879
		 * @param string $url Base URL used as the Stats tracking pixel.
3880
		 */
3881
		$base_url = apply_filters(
3882
			'jetpack_stats_base_url',
3883
			'https://pixel.wp.com/g.gif'
3884
		);
3885
		$url      = add_query_arg( $args, $base_url );
3886
		return $url;
3887
	}
3888
3889
	static function translate_current_user_to_role() {
3890
		foreach ( self::$capability_translations as $role => $cap ) {
3891
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3892
				return $role;
3893
			}
3894
		}
3895
3896
		return false;
3897
	}
3898
3899
	static function translate_role_to_cap( $role ) {
3900
		if ( ! isset( self::$capability_translations[$role] ) ) {
3901
			return false;
3902
		}
3903
3904
		return self::$capability_translations[$role];
3905
	}
3906
3907
	static function sign_role( $role ) {
3908
		if ( ! $user_id = (int) get_current_user_id() ) {
3909
			return false;
3910
		}
3911
3912
		$token = Jetpack_Data::get_access_token();
3913
		if ( ! $token || is_wp_error( $token ) ) {
3914
			return false;
3915
		}
3916
3917
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3918
	}
3919
3920
3921
	/**
3922
	 * Builds a URL to the Jetpack connection auth page
3923
	 *
3924
	 * @since 3.9.5
3925
	 *
3926
	 * @param bool $raw If true, URL will not be escaped.
3927
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3928
	 *                              If string, will be a custom redirect.
3929
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3930
	 *
3931
	 * @return string Connect URL
3932
	 */
3933
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
3934
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
3935
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3936
			if( is_network_admin() ) {
3937
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
3938
			}
3939
		} else {
3940
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3941
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3942
			}
3943
3944
			$role = self::translate_current_user_to_role();
3945
			$signed_role = self::sign_role( $role );
3946
3947
			$user = wp_get_current_user();
3948
3949
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3950
			$redirect = $redirect
3951
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3952
				: $jetpack_admin_page;
3953
3954
			if( isset( $_REQUEST['is_multisite'] ) ) {
3955
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3956
			}
3957
3958
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
3959
			@list( $secret ) = explode( ':', $secrets );
3960
3961
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3962
				? get_site_icon_url()
3963
				: false;
3964
3965
			/**
3966
			 * Filter the type of authorization.
3967
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
3968
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
3969
			 *
3970
			 * @since 4.3.3
3971
			 *
3972
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
3973
			 */
3974
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
3975
3976
			$args = urlencode_deep(
3977
				array(
3978
					'response_type' => 'code',
3979
					'client_id'     => Jetpack_Options::get_option( 'id' ),
3980
					'redirect_uri'  => add_query_arg(
3981
						array(
3982
							'action'   => 'authorize',
3983
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3984
							'redirect' => urlencode( $redirect ),
3985
						),
3986
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
3987
					),
3988
					'state'         => $user->ID,
3989
					'scope'         => $signed_role,
3990
					'user_email'    => $user->user_email,
3991
					'user_login'    => $user->user_login,
3992
					'is_active'     => Jetpack::is_active(),
3993
					'jp_version'    => JETPACK__VERSION,
3994
					'auth_type'     => $auth_type,
3995
					'secret'        => $secret,
3996
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
3997
					'blogname'      => get_option( 'blogname' ),
3998
					'site_url'      => site_url(),
3999
					'home_url'      => home_url(),
4000
					'site_icon'     => $site_icon,
4001
				)
4002
			);
4003
4004
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4005
		}
4006
4007
		if ( $from ) {
4008
			$url = add_query_arg( 'from', $from, $url );
4009
		}
4010
4011
		if ( isset( $_GET['calypso_env'] ) ) {
4012
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4013
		}
4014
4015
		return $raw ? $url : esc_url( $url );
4016
	}
4017
4018
	function build_reconnect_url( $raw = false ) {
4019
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4020
		return $raw ? $url : esc_url( $url );
4021
	}
4022
4023
	public static function admin_url( $args = null ) {
4024
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4025
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4026
		return $url;
4027
	}
4028
4029
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4030
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4031
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4032
	}
4033
4034
	function dismiss_jetpack_notice() {
4035
4036
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4037
			return;
4038
		}
4039
4040
		switch( $_GET['jetpack-notice'] ) {
4041
			case 'dismiss':
4042
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4043
4044
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4045
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4046
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4047
				}
4048
				break;
4049 View Code Duplication
			case 'jetpack-manage-opt-out':
4050
4051
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4052
					// Don't show the banner again
4053
4054
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4055
					// redirect back to the page that had the notice
4056
					if ( wp_get_referer() ) {
4057
						wp_safe_redirect( wp_get_referer() );
4058
					} else {
4059
						// Take me to Jetpack
4060
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4061
					}
4062
				}
4063
				break;
4064 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4065
4066
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4067
					// Don't show the banner again
4068
4069
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4070
					// redirect back to the page that had the notice
4071
					if ( wp_get_referer() ) {
4072
						wp_safe_redirect( wp_get_referer() );
4073
					} else {
4074
						// Take me to Jetpack
4075
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4076
					}
4077
				}
4078
				break;
4079
			case 'jetpack-manage-opt-in':
4080
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4081
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4082
4083
					$redirection_url = Jetpack::admin_url();
4084
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4085
4086
					// Don't redirect form the Jetpack Setting Page
4087
					$referer_parsed = parse_url ( wp_get_referer() );
4088
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4089
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4090
						// Take the user to Jetpack home except when on the setting page
4091
						$redirection_url = wp_get_referer();
4092
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4093
					}
4094
					// Also update the JSON API FULL MANAGEMENT Option
4095
					Jetpack::activate_module( 'manage', false, false );
4096
4097
					// Special Message when option in.
4098
					Jetpack::state( 'optin-manage', 'true' );
4099
					// Activate the Module if not activated already
4100
4101
					// Redirect properly
4102
					wp_safe_redirect( $redirection_url );
4103
4104
				}
4105
				break;
4106
		}
4107
	}
4108
4109
	function debugger_page() {
4110
		nocache_headers();
4111
		if ( ! current_user_can( 'manage_options' ) ) {
4112
			die( '-1' );
4113
		}
4114
		Jetpack_Debugger::jetpack_debug_display_handler();
4115
		exit;
4116
	}
4117
4118
	public static function admin_screen_configure_module( $module_id ) {
4119
4120
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4121
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4122
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4123
				/**
4124
				 * Fires to diplay a custom module activation screen.
4125
				 *
4126
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4127
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4128
				 *
4129
				 * @module manage
4130
				 *
4131
				 * @since 3.8.0
4132
				 *
4133
				 * @param int $module_id Module ID.
4134
				 */
4135
				do_action( 'display_activate_module_setting_' . $module_id );
4136
			} else {
4137
				self::display_activate_module_link( $module_id );
4138
			}
4139
4140
			return false;
4141
		} ?>
4142
4143
		<div id="jp-settings-screen" style="position: relative">
4144
			<h3>
4145
			<?php
4146
				$module = Jetpack::get_module( $module_id );
4147
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4148
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4149
			?>
4150
			</h3>
4151
			<?php
4152
				/**
4153
				 * Fires within the displayed message when a feature configuation is updated.
4154
				 *
4155
				 * @since 3.4.0
4156
				 *
4157
				 * @param int $module_id Module ID.
4158
				 */
4159
				do_action( 'jetpack_notices_update_settings', $module_id );
4160
				/**
4161
				 * Fires when a feature configuation screen is loaded.
4162
				 * The dynamic part of the hook, $module_id, is the module ID.
4163
				 *
4164
				 * @since 1.1.0
4165
				 */
4166
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4167
			?>
4168
		</div><?php
4169
	}
4170
4171
	/**
4172
	 * Display link to activate the module to see the settings screen.
4173
	 * @param  string $module_id
4174
	 * @return null
4175
	 */
4176
	public static function display_activate_module_link( $module_id ) {
4177
4178
		$info =  Jetpack::get_module( $module_id );
4179
		$extra = '';
4180
		$activate_url = wp_nonce_url(
4181
				Jetpack::admin_url(
4182
					array(
4183
						'page'   => 'jetpack',
4184
						'action' => 'activate',
4185
						'module' => $module_id,
4186
					)
4187
				),
4188
				"jetpack_activate-$module_id"
4189
			);
4190
4191
		?>
4192
4193
		<div class="wrap configure-module">
4194
			<div id="jp-settings-screen">
4195
				<?php
4196
				if ( $module_id == 'json-api' ) {
4197
4198
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4199
4200
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4201
4202
					$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' );
4203
4204
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4205
				} ?>
4206
4207
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4208
				<div class="narrow">
4209
					<p><?php echo  $info['description']; ?></p>
4210
					<?php if( $extra ) { ?>
4211
					<p><?php echo esc_html( $extra ); ?></p>
4212
					<?php } ?>
4213
					<p>
4214
						<?php
4215
						if( wp_get_referer() ) {
4216
							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() );
4217
						} else {
4218
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4219
						} ?>
4220
					</p>
4221
				</div>
4222
4223
			</div>
4224
		</div>
4225
4226
		<?php
4227
	}
4228
4229
	public static function sort_modules( $a, $b ) {
4230
		if ( $a['sort'] == $b['sort'] )
4231
			return 0;
4232
4233
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4234
	}
4235
4236
	function ajax_recheck_ssl() {
4237
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4238
		$result = Jetpack::permit_ssl( true );
4239
		wp_send_json( array(
4240
			'enabled' => $result,
4241
			'message' => get_transient( 'jetpack_https_test_message' )
4242
		) );
4243
	}
4244
4245
/* Client API */
4246
4247
	/**
4248
	 * Returns the requested Jetpack API URL
4249
	 *
4250
	 * @return string
4251
	 */
4252
	public static function api_url( $relative_url ) {
4253
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4254
	}
4255
4256
	/**
4257
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4258
	 */
4259
	public static function fix_url_for_bad_hosts( $url ) {
4260
		if ( 0 !== strpos( $url, 'https://' ) ) {
4261
			return $url;
4262
		}
4263
4264
		switch ( JETPACK_CLIENT__HTTPS ) {
4265
			case 'ALWAYS' :
4266
				return $url;
4267
			case 'NEVER' :
4268
				return set_url_scheme( $url, 'http' );
4269
			// default : case 'AUTO' :
4270
		}
4271
4272
		// we now return the unmodified SSL URL by default, as a security precaution
4273
		return $url;
4274
	}
4275
4276
	/**
4277
	 * Checks to see if the URL is using SSL to connect with Jetpack
4278
	 *
4279
	 * @since 2.3.3
4280
	 * @return boolean
4281
	 */
4282
	public static function permit_ssl( $force_recheck = false ) {
4283
		// Do some fancy tests to see if ssl is being supported
4284
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4285
			$message = '';
4286
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4287
				$ssl = 0;
4288
			} else {
4289
				switch ( JETPACK_CLIENT__HTTPS ) {
4290
					case 'NEVER':
4291
						$ssl = 0;
4292
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4293
						break;
4294
					case 'ALWAYS':
4295
					case 'AUTO':
4296
					default:
4297
						$ssl = 1;
4298
						break;
4299
				}
4300
4301
				// If it's not 'NEVER', test to see
4302
				if ( $ssl ) {
4303
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4304
						$ssl = 0;
4305
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4306
					} else {
4307
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4308
						if ( is_wp_error( $response ) ) {
4309
							$ssl = 0;
4310
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4311
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4312
							$ssl = 0;
4313
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4314
						}
4315
					}
4316
				}
4317
			}
4318
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4319
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4320
		}
4321
4322
		return (bool) $ssl;
4323
	}
4324
4325
	/*
4326
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4327
	 */
4328
	public function alert_auto_ssl_fail() {
4329
		if ( ! current_user_can( 'manage_options' ) )
4330
			return;
4331
4332
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4333
		?>
4334
4335
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4336
			<div class="jp-banner__content">
4337
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4338
				<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>
4339
				<p>
4340
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4341
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4342
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4343
				</p>
4344
				<p>
4345
					<?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' ),
4346
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4347
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4348
				</p>
4349
			</div>
4350
		</div>
4351
		<style>
4352
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4353
		</style>
4354
		<script type="text/javascript">
4355
			jQuery( document ).ready( function( $ ) {
4356
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4357
					var $this = $( this );
4358
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4359
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4360
					e.preventDefault();
4361
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4362
					$.post( ajaxurl, data )
4363
					  .done( function( response ) {
4364
					  	if ( response.enabled ) {
4365
					  		$( '#jetpack-ssl-warning' ).hide();
4366
					  	} else {
4367
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4368
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4369
					  	}
4370
					  }.bind( $this ) );
4371
				} );
4372
			} );
4373
		</script>
4374
4375
		<?php
4376
	}
4377
4378
	/**
4379
	 * Returns the Jetpack XML-RPC API
4380
	 *
4381
	 * @return string
4382
	 */
4383
	public static function xmlrpc_api_url() {
4384
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4385
		return untrailingslashit( $base ) . '/xmlrpc.php';
4386
	}
4387
4388
	/**
4389
	 * Creates two secret tokens and the end of life timestamp for them.
4390
	 *
4391
	 * Note these tokens are unique per call, NOT static per site for connecting.
4392
	 *
4393
	 * @since 2.6
4394
	 * @return array
4395
	 */
4396
	public function generate_secrets( $action, $exp = 600 ) {
4397
	    $secret = wp_generate_password( 32, false ) // secret_1
4398
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4399
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4400
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4401
		Jetpack_Options::update_option( $action, $secret );
4402
	    return Jetpack_Options::get_option( $action );
4403
	}
4404
4405
	/**
4406
	 * Builds the timeout limit for queries talking with the wpcom servers.
4407
	 *
4408
	 * Based on local php max_execution_time in php.ini
4409
	 *
4410
	 * @since 2.6
4411
	 * @return int
4412
	 **/
4413
	public function get_remote_query_timeout_limit() {
4414
	    $timeout = (int) ini_get( 'max_execution_time' );
4415
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4416
		$timeout = 30;
4417
	    return intval( $timeout / 2 );
4418
	}
4419
4420
4421
	/**
4422
	 * Takes the response from the Jetpack register new site endpoint and
4423
	 * verifies it worked properly.
4424
	 *
4425
	 * @since 2.6
4426
	 * @return true or Jetpack_Error
4427
	 **/
4428
	public function validate_remote_register_response( $response ) {
4429
	    	if ( is_wp_error( $response ) ) {
4430
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4431
		}
4432
4433
		$code   = wp_remote_retrieve_response_code( $response );
4434
		$entity = wp_remote_retrieve_body( $response );
4435
		if ( $entity )
4436
			$json = json_decode( $entity );
4437
		else
4438
			$json = false;
4439
4440
		$code_type = intval( $code / 100 );
4441
		if ( 5 == $code_type ) {
4442
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4443
		} elseif ( 408 == $code ) {
4444
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4445
		} elseif ( ! empty( $json->error ) ) {
4446
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4447
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4448
		} elseif ( 200 != $code ) {
4449
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4450
		}
4451
4452
		// Jetpack ID error block
4453
		if ( empty( $json->jetpack_id ) ) {
4454
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4455
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4456
			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 );
4457
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4458
			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 );
4459
		}
4460
4461
	    return true;
4462
	}
4463
	/**
4464
	 * @return bool|WP_Error
4465
	 */
4466
	public static function register() {
4467
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4468
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4469
4470
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
4471 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4472
			return new Jetpack_Error( 'missing_secrets' );
4473
		}
4474
4475
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4476
4477
		$gmt_offset = get_option( 'gmt_offset' );
4478
		if ( ! $gmt_offset ) {
4479
			$gmt_offset = 0;
4480
		}
4481
4482
		$stats_options = get_option( 'stats_options' );
4483
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4484
4485
		$args = array(
4486
			'method'  => 'POST',
4487
			'body'    => array(
4488
				'siteurl'         => site_url(),
4489
				'home'            => home_url(),
4490
				'gmt_offset'      => $gmt_offset,
4491
				'timezone_string' => (string) get_option( 'timezone_string' ),
4492
				'site_name'       => (string) get_option( 'blogname' ),
4493
				'secret_1'        => $secret_1,
4494
				'secret_2'        => $secret_2,
4495
				'site_lang'       => get_locale(),
4496
				'timeout'         => $timeout,
4497
				'stats_id'        => $stats_id,
4498
				'state'           => get_current_user_id(),
4499
			),
4500
			'headers' => array(
4501
				'Accept' => 'application/json',
4502
			),
4503
			'timeout' => $timeout,
4504
		);
4505
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4506
4507
4508
		// Make sure the response is valid and does not contain any Jetpack errors
4509
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
4510
		if( is_wp_error( $valid_response ) || !$valid_response ) {
4511
		    return $valid_response;
4512
		}
4513
4514
		// Grab the response values to work with
4515
		$code   = wp_remote_retrieve_response_code( $response );
4516
		$entity = wp_remote_retrieve_body( $response );
4517
4518
		if ( $entity )
4519
			$json = json_decode( $entity );
4520
		else
4521
			$json = false;
4522
4523 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4524
			return new Jetpack_Error( 'jetpack_secret', '', $code );
4525
4526
		if ( isset( $json->jetpack_public ) ) {
4527
			$jetpack_public = (int) $json->jetpack_public;
4528
		} else {
4529
			$jetpack_public = false;
4530
		}
4531
4532
		Jetpack_Options::update_options(
4533
			array(
4534
				'id'         => (int)    $json->jetpack_id,
4535
				'blog_token' => (string) $json->jetpack_secret,
4536
				'public'     => $jetpack_public,
4537
			)
4538
		);
4539
4540
		/**
4541
		 * Fires when a site is registered on WordPress.com.
4542
		 *
4543
		 * @since 3.7.0
4544
		 *
4545
		 * @param int $json->jetpack_id Jetpack Blog ID.
4546
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4547
		 * @param int|bool $jetpack_public Is the site public.
4548
		 */
4549
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
4550
4551
		// Initialize Jump Start for the first and only time.
4552
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4553
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4554
4555
			$jetpack = Jetpack::init();
4556
4557
			$jetpack->stat( 'jumpstart', 'unique-views' );
4558
			$jetpack->do_stats( 'server_side' );
4559
		};
4560
4561
		return true;
4562
	}
4563
4564
	/**
4565
	 * If the db version is showing something other that what we've got now, bump it to current.
4566
	 *
4567
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4568
	 */
4569
	public static function maybe_set_version_option() {
4570
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4571
		if ( JETPACK__VERSION != $version ) {
4572
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4573
4574
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4575
				/** This action is documented in class.jetpack.php */
4576
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4577
			}
4578
4579
			return true;
4580
		}
4581
		return false;
4582
	}
4583
4584
/* Client Server API */
4585
4586
	/**
4587
	 * Loads the Jetpack XML-RPC client
4588
	 */
4589
	public static function load_xml_rpc_client() {
4590
		require_once ABSPATH . WPINC . '/class-IXR.php';
4591
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4592
	}
4593
4594
	function verify_xml_rpc_signature() {
4595
		if ( $this->xmlrpc_verification ) {
4596
			return $this->xmlrpc_verification;
4597
		}
4598
4599
		// It's not for us
4600
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4601
			return false;
4602
		}
4603
4604
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
4605
		if (
4606
			empty( $token_key )
4607
		||
4608
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4609
		) {
4610
			return false;
4611
		}
4612
4613
		if ( '0' === $user_id ) {
4614
			$token_type = 'blog';
4615
			$user_id = 0;
4616
		} else {
4617
			$token_type = 'user';
4618
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4619
				return false;
4620
			}
4621
			$user_id = (int) $user_id;
4622
4623
			$user = new WP_User( $user_id );
4624
			if ( ! $user || ! $user->exists() ) {
4625
				return false;
4626
			}
4627
		}
4628
4629
		$token = Jetpack_Data::get_access_token( $user_id );
4630
		if ( ! $token ) {
4631
			return false;
4632
		}
4633
4634
		$token_check = "$token_key.";
4635
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4636
			return false;
4637
		}
4638
4639
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4640
4641
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4642
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4643
			$post_data   = $_POST;
4644
			$file_hashes = array();
4645
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4646
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4647
					continue;
4648
				}
4649
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4650
				$file_hashes[$post_data_key] = $post_data_value;
4651
			}
4652
4653
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4654
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4655
				$post_data[$post_data_key] = $post_data_value;
4656
			}
4657
4658
			ksort( $post_data );
4659
4660
			$body = http_build_query( stripslashes_deep( $post_data ) );
4661
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4662
			$body = file_get_contents( 'php://input' );
4663
		} else {
4664
			$body = null;
4665
		}
4666
		$signature = $jetpack_signature->sign_current_request(
4667
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4668
		);
4669
4670
		if ( ! $signature ) {
4671
			return false;
4672
		} else if ( is_wp_error( $signature ) ) {
4673
			return $signature;
4674
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4675
			return false;
4676
		}
4677
4678
		$timestamp = (int) $_GET['timestamp'];
4679
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4680
4681
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4682
			return false;
4683
		}
4684
4685
		$this->xmlrpc_verification = array(
4686
			'type'    => $token_type,
4687
			'user_id' => $token->external_user_id,
4688
		);
4689
4690
		return $this->xmlrpc_verification;
4691
	}
4692
4693
	/**
4694
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4695
	 */
4696
	function authenticate_jetpack( $user, $username, $password ) {
4697
		if ( is_a( $user, 'WP_User' ) ) {
4698
			return $user;
4699
		}
4700
4701
		$token_details = $this->verify_xml_rpc_signature();
4702
4703
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4704
			return $user;
4705
		}
4706
4707
		if ( 'user' !== $token_details['type'] ) {
4708
			return $user;
4709
		}
4710
4711
		if ( ! $token_details['user_id'] ) {
4712
			return $user;
4713
		}
4714
4715
		nocache_headers();
4716
4717
		return new WP_User( $token_details['user_id'] );
4718
	}
4719
4720
	function add_nonce( $timestamp, $nonce ) {
4721
		global $wpdb;
4722
		static $nonces_used_this_request = array();
4723
4724
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4725
			return $nonces_used_this_request["$timestamp:$nonce"];
4726
		}
4727
4728
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4729
		$timestamp = (int) $timestamp;
4730
		$nonce     = esc_sql( $nonce );
4731
4732
		// Raw query so we can avoid races: add_option will also update
4733
		$show_errors = $wpdb->show_errors( false );
4734
4735
		$old_nonce = $wpdb->get_row(
4736
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4737
		);
4738
4739
		if ( is_null( $old_nonce ) ) {
4740
			$return = $wpdb->query(
4741
				$wpdb->prepare(
4742
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4743
					"jetpack_nonce_{$timestamp}_{$nonce}",
4744
					time(),
4745
					'no'
4746
				)
4747
			);
4748
		} else {
4749
			$return = false;
4750
		}
4751
4752
		$wpdb->show_errors( $show_errors );
4753
4754
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4755
4756
		return $return;
4757
	}
4758
4759
	/**
4760
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4761
	 * Capture it here so we can verify the signature later.
4762
	 */
4763
	function xmlrpc_methods( $methods ) {
4764
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4765
		return $methods;
4766
	}
4767
4768
	function public_xmlrpc_methods( $methods ) {
4769
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4770
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4771
		}
4772
		return $methods;
4773
	}
4774
4775
	function jetpack_getOptions( $args ) {
4776
		global $wp_xmlrpc_server;
4777
4778
		$wp_xmlrpc_server->escape( $args );
4779
4780
		$username	= $args[1];
4781
		$password	= $args[2];
4782
4783
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4784
			return $wp_xmlrpc_server->error;
4785
		}
4786
4787
		$options = array();
4788
		$user_data = $this->get_connected_user_data();
4789
		if ( is_array( $user_data ) ) {
4790
			$options['jetpack_user_id'] = array(
4791
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4792
				'readonly'      => true,
4793
				'value'         => $user_data['ID'],
4794
			);
4795
			$options['jetpack_user_login'] = array(
4796
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4797
				'readonly'      => true,
4798
				'value'         => $user_data['login'],
4799
			);
4800
			$options['jetpack_user_email'] = array(
4801
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4802
				'readonly'      => true,
4803
				'value'         => $user_data['email'],
4804
			);
4805
			$options['jetpack_user_site_count'] = array(
4806
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4807
				'readonly'      => true,
4808
				'value'         => $user_data['site_count'],
4809
			);
4810
		}
4811
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4812
		$args = stripslashes_deep( $args );
4813
		return $wp_xmlrpc_server->wp_getOptions( $args );
4814
	}
4815
4816
	function xmlrpc_options( $options ) {
4817
		$jetpack_client_id = false;
4818
		if ( self::is_active() ) {
4819
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4820
		}
4821
		$options['jetpack_version'] = array(
4822
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4823
				'readonly'      => true,
4824
				'value'         => JETPACK__VERSION,
4825
		);
4826
4827
		$options['jetpack_client_id'] = array(
4828
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4829
				'readonly'      => true,
4830
				'value'         => $jetpack_client_id,
4831
		);
4832
		return $options;
4833
	}
4834
4835
	public static function clean_nonces( $all = false ) {
4836
		global $wpdb;
4837
4838
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4839
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4840
4841
		if ( true !== $all ) {
4842
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4843
			$sql_args[] = time() - 3600;
4844
		}
4845
4846
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4847
4848
		$sql = $wpdb->prepare( $sql, $sql_args );
4849
4850
		for ( $i = 0; $i < 1000; $i++ ) {
4851
			if ( ! $wpdb->query( $sql ) ) {
4852
				break;
4853
			}
4854
		}
4855
	}
4856
4857
	/**
4858
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4859
	 * SET: state( $key, $value );
4860
	 * GET: $value = state( $key );
4861
	 *
4862
	 * @param string $key
4863
	 * @param string $value
4864
	 * @param bool $restate private
4865
	 */
4866
	public static function state( $key = null, $value = null, $restate = false ) {
4867
		static $state = array();
4868
		static $path, $domain;
4869
		if ( ! isset( $path ) ) {
4870
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4871
			$admin_url = Jetpack::admin_url();
4872
			$bits      = parse_url( $admin_url );
4873
4874
			if ( is_array( $bits ) ) {
4875
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4876
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4877
			} else {
4878
				$path = $domain = null;
4879
			}
4880
		}
4881
4882
		// Extract state from cookies and delete cookies
4883
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4884
			$yum = $_COOKIE[ 'jetpackState' ];
4885
			unset( $_COOKIE[ 'jetpackState' ] );
4886
			foreach ( $yum as $k => $v ) {
4887
				if ( strlen( $v ) )
4888
					$state[ $k ] = $v;
4889
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4890
			}
4891
		}
4892
4893
		if ( $restate ) {
4894
			foreach ( $state as $k => $v ) {
4895
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4896
			}
4897
			return;
4898
		}
4899
4900
		// Get a state variable
4901
		if ( isset( $key ) && ! isset( $value ) ) {
4902
			if ( array_key_exists( $key, $state ) )
4903
				return $state[ $key ];
4904
			return null;
4905
		}
4906
4907
		// Set a state variable
4908
		if ( isset ( $key ) && isset( $value ) ) {
4909
			if( is_array( $value ) && isset( $value[0] ) ) {
4910
				$value = $value[0];
4911
			}
4912
			$state[ $key ] = $value;
4913
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4914
		}
4915
	}
4916
4917
	public static function restate() {
4918
		Jetpack::state( null, null, true );
4919
	}
4920
4921
	public static function check_privacy( $file ) {
4922
		static $is_site_publicly_accessible = null;
4923
4924
		if ( is_null( $is_site_publicly_accessible ) ) {
4925
			$is_site_publicly_accessible = false;
4926
4927
			Jetpack::load_xml_rpc_client();
4928
			$rpc = new Jetpack_IXR_Client();
4929
4930
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4931
			if ( $success ) {
4932
				$response = $rpc->getResponse();
4933
				if ( $response ) {
4934
					$is_site_publicly_accessible = true;
4935
				}
4936
			}
4937
4938
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4939
		}
4940
4941
		if ( $is_site_publicly_accessible ) {
4942
			return;
4943
		}
4944
4945
		$module_slug = self::get_module_slug( $file );
4946
4947
		$privacy_checks = Jetpack::state( 'privacy_checks' );
4948
		if ( ! $privacy_checks ) {
4949
			$privacy_checks = $module_slug;
4950
		} else {
4951
			$privacy_checks .= ",$module_slug";
4952
		}
4953
4954
		Jetpack::state( 'privacy_checks', $privacy_checks );
4955
	}
4956
4957
	/**
4958
	 * Helper method for multicall XMLRPC.
4959
	 */
4960
	public static function xmlrpc_async_call() {
4961
		global $blog_id;
4962
		static $clients = array();
4963
4964
		$client_blog_id = is_multisite() ? $blog_id : 0;
4965
4966
		if ( ! isset( $clients[$client_blog_id] ) ) {
4967
			Jetpack::load_xml_rpc_client();
4968
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
4969
			if ( function_exists( 'ignore_user_abort' ) ) {
4970
				ignore_user_abort( true );
4971
			}
4972
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
4973
		}
4974
4975
		$args = func_get_args();
4976
4977
		if ( ! empty( $args[0] ) ) {
4978
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
4979
		} elseif ( is_multisite() ) {
4980
			foreach ( $clients as $client_blog_id => $client ) {
4981
				if ( ! $client_blog_id || empty( $client->calls ) ) {
4982
					continue;
4983
				}
4984
4985
				$switch_success = switch_to_blog( $client_blog_id, true );
4986
				if ( ! $switch_success ) {
4987
					continue;
4988
				}
4989
4990
				flush();
4991
				$client->query();
4992
4993
				restore_current_blog();
4994
			}
4995
		} else {
4996
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
4997
				flush();
4998
				$clients[0]->query();
4999
			}
5000
		}
5001
	}
5002
5003
	public static function staticize_subdomain( $url ) {
5004
5005
		// Extract hostname from URL
5006
		$host = parse_url( $url, PHP_URL_HOST );
5007
5008
		// Explode hostname on '.'
5009
		$exploded_host = explode( '.', $host );
5010
5011
		// Retrieve the name and TLD
5012
		if ( count( $exploded_host ) > 1 ) {
5013
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5014
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5015
			// Rebuild domain excluding subdomains
5016
			$domain = $name . '.' . $tld;
5017
		} else {
5018
			$domain = $host;
5019
		}
5020
		// Array of Automattic domains
5021
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5022
5023
		// Return $url if not an Automattic domain
5024
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5025
			return $url;
5026
		}
5027
5028
		if ( is_ssl() ) {
5029
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5030
		}
5031
5032
		srand( crc32( basename( $url ) ) );
5033
		$static_counter = rand( 0, 2 );
5034
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5035
5036
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5037
	}
5038
5039
/* JSON API Authorization */
5040
5041
	/**
5042
	 * Handles the login action for Authorizing the JSON API
5043
	 */
5044
	function login_form_json_api_authorization() {
5045
		$this->verify_json_api_authorization_request();
5046
5047
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5048
5049
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5050
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5051
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5052
	}
5053
5054
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5055
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5056
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5057
			return $url;
5058
		}
5059
5060
		$parsed_url = parse_url( $url );
5061
		$url = strtok( $url, '?' );
5062
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5063
		if ( ! empty( $parsed_url['query'] ) )
5064
			$url .= "&{$parsed_url['query']}";
5065
5066
		return $url;
5067
	}
5068
5069
	// Make sure the POSTed request is handled by the same action
5070
	function preserve_action_in_login_form_for_json_api_authorization() {
5071
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5072
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5073
	}
5074
5075
	// If someone logs in to approve API access, store the Access Code in usermeta
5076
	function store_json_api_authorization_token( $user_login, $user ) {
5077
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5078
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5079
		$token = wp_generate_password( 32, false );
5080
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5081
	}
5082
5083
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5084
	function allow_wpcom_public_api_domain( $domains ) {
5085
		$domains[] = 'public-api.wordpress.com';
5086
		return $domains;
5087
	}
5088
5089
	// Add the Access Code details to the public-api.wordpress.com redirect
5090
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5091
		return add_query_arg(
5092
			urlencode_deep(
5093
				array(
5094
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5095
					'jetpack-user-id' => (int) $user->ID,
5096
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5097
				)
5098
			),
5099
			$redirect_to
5100
		);
5101
	}
5102
5103
	// Verifies the request by checking the signature
5104
	function verify_json_api_authorization_request() {
5105
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5106
5107
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
5108
		if ( ! $token || empty( $token->secret ) ) {
5109
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5110
		}
5111
5112
		$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' );
5113
5114
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5115
5116
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
5117
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
5118
		} else {
5119
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5120
		}
5121
5122
		if ( ! $signature ) {
5123
			wp_die( $die_error );
5124
		} else if ( is_wp_error( $signature ) ) {
5125
			wp_die( $die_error );
5126
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5127
			if ( is_ssl() ) {
5128
				// 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
5129
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5130
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $_GET['signature'] ) ) {
5131
					wp_die( $die_error );
5132
				}
5133
			} else {
5134
				wp_die( $die_error );
5135
			}
5136
		}
5137
5138
		$timestamp = (int) $_GET['timestamp'];
5139
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5140
5141
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5142
			// De-nonce the nonce, at least for 5 minutes.
5143
			// 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)
5144
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5145
			if ( $old_nonce_time < time() - 300 ) {
5146
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5147
			}
5148
		}
5149
5150
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
5151
		$data_filters = array(
5152
			'state'        => 'opaque',
5153
			'client_id'    => 'int',
5154
			'client_title' => 'string',
5155
			'client_image' => 'url',
5156
		);
5157
5158
		foreach ( $data_filters as $key => $sanitation ) {
5159
			if ( ! isset( $data->$key ) ) {
5160
				wp_die( $die_error );
5161
			}
5162
5163
			switch ( $sanitation ) {
5164
			case 'int' :
5165
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5166
				break;
5167
			case 'opaque' :
5168
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5169
				break;
5170
			case 'string' :
5171
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5172
				break;
5173
			case 'url' :
5174
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5175
				break;
5176
			}
5177
		}
5178
5179
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5180
			wp_die( $die_error );
5181
		}
5182
	}
5183
5184
	function login_message_json_api_authorization( $message ) {
5185
		return '<p class="message">' . sprintf(
5186
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5187
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5188
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5189
	}
5190
5191
	/**
5192
	 * Get $content_width, but with a <s>twist</s> filter.
5193
	 */
5194
	public static function get_content_width() {
5195
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5196
		/**
5197
		 * Filter the Content Width value.
5198
		 *
5199
		 * @since 2.2.3
5200
		 *
5201
		 * @param string $content_width Content Width value.
5202
		 */
5203
		return apply_filters( 'jetpack_content_width', $content_width );
5204
	}
5205
5206
	/**
5207
	 * Centralize the function here until it gets added to core.
5208
	 *
5209
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5210
	 * @param int $size Size of the avatar image
5211
	 * @param string $default URL to a default image to use if no avatar is available
5212
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5213
	 *
5214
	 * @return array First element is the URL, second is the class.
5215
	 */
5216
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5217
		// Don't bother adding the __return_true filter if it's already there.
5218
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5219
5220
		if ( $force_display && ! $has_filter )
5221
			add_filter( 'pre_option_show_avatars', '__return_true' );
5222
5223
		$avatar = get_avatar( $id_or_email, $size, $default );
5224
5225
		if ( $force_display && ! $has_filter )
5226
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5227
5228
		// If no data, fail out.
5229
		if ( is_wp_error( $avatar ) || ! $avatar )
5230
			return array( null, null );
5231
5232
		// Pull out the URL.  If it's not there, fail out.
5233
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5234
			return array( null, null );
5235
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5236
5237
		// Pull out the class, but it's not a big deal if it's missing.
5238
		$class = '';
5239
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5240
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5241
5242
		return array( $url, $class );
5243
	}
5244
5245
	/**
5246
	 * Pings the WordPress.com Mirror Site for the specified options.
5247
	 *
5248
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5249
	 *
5250
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5251
	 */
5252
	public function get_cloud_site_options( $option_names ) {
5253
		$option_names = array_filter( (array) $option_names, 'is_string' );
5254
5255
		Jetpack::load_xml_rpc_client();
5256
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5257
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5258
		if ( $xml->isError() ) {
5259
			return array(
5260
				'error_code' => $xml->getErrorCode(),
5261
				'error_msg'  => $xml->getErrorMessage(),
5262
			);
5263
		}
5264
		$cloud_site_options = $xml->getResponse();
5265
5266
		return $cloud_site_options;
5267
	}
5268
5269
	/**
5270
	 * Checks if the site is currently in an identity crisis.
5271
	 *
5272
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5273
	 */
5274
	public static function check_identity_crisis() {
5275
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5276
			return false;
5277
		}
5278
5279
		return Jetpack_Options::get_option( 'sync_error_idc' );
5280
	}
5281
5282
	/**
5283
	 * Checks whether the home and siteurl specifically are whitelisted
5284
	 * Written so that we don't have re-check $key and $value params every time
5285
	 * we want to check if this site is whitelisted, for example in footer.php
5286
	 *
5287
	 * @since  3.8.0
5288
	 * @return bool True = already whitelisted False = not whitelisted
5289
	 */
5290
	public static function is_staging_site() {
5291
		$is_staging = false;
5292
5293
		$known_staging = array(
5294
			'urls' => array(
5295
				'#\.staging\.wpengine\.com$#i', // WP Engine
5296
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5297
				),
5298
			'constants' => array(
5299
				'IS_WPE_SNAPSHOT',      // WP Engine
5300
				'KINSTA_DEV_ENV',       // Kinsta.com
5301
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5302
				'JETPACK_STAGING_MODE', // Generic
5303
				)
5304
			);
5305
		/**
5306
		 * Filters the flags of known staging sites.
5307
		 *
5308
		 * @since 3.9.0
5309
		 *
5310
		 * @param array $known_staging {
5311
		 *     An array of arrays that each are used to check if the current site is staging.
5312
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5313
		 *     @type array $constants PHP constants of known staging/developement environments.
5314
		 *  }
5315
		 */
5316
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5317
5318
		if ( isset( $known_staging['urls'] ) ) {
5319
			foreach ( $known_staging['urls'] as $url ){
5320
				if ( preg_match( $url, site_url() ) ) {
5321
					$is_staging = true;
5322
					break;
5323
				}
5324
			}
5325
		}
5326
5327
		if ( isset( $known_staging['constants'] ) ) {
5328
			foreach ( $known_staging['constants'] as $constant ) {
5329
				if ( defined( $constant ) && constant( $constant ) ) {
5330
					$is_staging = true;
5331
				}
5332
			}
5333
		}
5334
5335
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5336
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5337
			$is_staging = true;
5338
		}
5339
5340
		/**
5341
		 * Filters is_staging_site check.
5342
		 *
5343
		 * @since 3.9.0
5344
		 *
5345
		 * @param bool $is_staging If the current site is a staging site.
5346
		 */
5347
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5348
	}
5349
5350
	/**
5351
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5352
	 *
5353
	 * @return bool
5354
	 */
5355
	public static function validate_sync_error_idc_option() {
5356
		$is_valid = false;
5357
5358
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5359
		if ( false === $idc_allowed ) {
5360
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5361
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5362
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5363
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5364
				$transient_duration = HOUR_IN_SECONDS;
5365
			} else {
5366
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5367
				$idc_allowed = '1';
5368
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5369
			}
5370
5371
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5372
		}
5373
5374
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5375
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5376
		$local_options = self::get_sync_error_idc_option();
5377
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5378
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5379
				$is_valid = true;
5380
			}
5381
		}
5382
5383
		/**
5384
		 * Filters whether the sync_error_idc option is valid.
5385
		 *
5386
		 * @since 4.4.0
5387
		 *
5388
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5389
		 */
5390
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5391
5392
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5393
			// Since the option exists, and did not validate, delete it
5394
			Jetpack_Options::delete_option( 'sync_error_idc' );
5395
		}
5396
5397
		return $is_valid;
5398
	}
5399
5400
	/**
5401
	 * Normalizes a url by doing three things:
5402
	 *  - Strips protocol
5403
	 *  - Strips www
5404
	 *  - Adds a trailing slash
5405
	 *
5406
	 * @since 4.4.0
5407
	 * @param string $url
5408
	 * @return WP_Error|string
5409
	 */
5410
	public static function normalize_url_protocol_agnostic( $url ) {
5411
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5412
		if ( ! $parsed_url ) {
5413
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5414
		}
5415
5416
		// Strip www and protocols
5417
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5418
		return $url;
5419
	}
5420
5421
	/**
5422
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5423
	 *
5424
	 * @since 4.4.0
5425
	 *
5426
	 * @param array $response
5427
	 * @return array Array of the local urls, wpcom urls, and error code
5428
	 */
5429
	public static function get_sync_error_idc_option( $response = array() ) {
5430
		$local_options = array(
5431
			'home' => get_home_url(),
5432
			'siteurl' => get_site_url(),
5433
		);
5434
5435
		$options = array_merge( $local_options, $response );
5436
5437
		$returned_values = array();
5438
		foreach( $options as $key => $option ) {
5439
			if ( 'error_code' === $key ) {
5440
				$returned_values[ $key ] = $option;
5441
				continue;
5442
			}
5443
5444
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5445
				continue;
5446
			}
5447
5448
			$returned_values[ $key ] = $normalized_url;
5449
		}
5450
5451
		return $returned_values;
5452
	}
5453
5454
	/**
5455
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5456
	 * If set to true, the site will be put into staging mode.
5457
	 *
5458
	 * @since 4.3.2
5459
	 * @return bool
5460
	 */
5461
	public static function sync_idc_optin() {
5462
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5463
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5464
		} else {
5465
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5466
		}
5467
5468
		/**
5469
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5470
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5471
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5472
		 *
5473
		 * @since 4.3.2
5474
		 *
5475
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5476
		 */
5477
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5478
	}
5479
5480
	/**
5481
	 * Maybe Use a .min.css stylesheet, maybe not.
5482
	 *
5483
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5484
	 */
5485
	public static function maybe_min_asset( $url, $path, $plugin ) {
5486
		// Short out on things trying to find actual paths.
5487
		if ( ! $path || empty( $plugin ) ) {
5488
			return $url;
5489
		}
5490
5491
		// Strip out the abspath.
5492
		$base = dirname( plugin_basename( $plugin ) );
5493
5494
		// Short out on non-Jetpack assets.
5495
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5496
			return $url;
5497
		}
5498
5499
		// File name parsing.
5500
		$file              = "{$base}/{$path}";
5501
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5502
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5503
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5504
		$extension         = array_shift( $file_name_parts_r );
5505
5506
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5507
			// Already pointing at the minified version.
5508
			if ( 'min' === $file_name_parts_r[0] ) {
5509
				return $url;
5510
			}
5511
5512
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5513
			if ( file_exists( $min_full_path ) ) {
5514
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5515
			}
5516
		}
5517
5518
		return $url;
5519
	}
5520
5521
	/**
5522
	 * Maybe inlines a stylesheet.
5523
	 *
5524
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5525
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5526
	 *
5527
	 * Attached to `style_loader_tag` filter.
5528
	 *
5529
	 * @param string $tag The tag that would link to the external asset.
5530
	 * @param string $handle The registered handle of the script in question.
5531
	 *
5532
	 * @return string
5533
	 */
5534
	public static function maybe_inline_style( $tag, $handle ) {
5535
		global $wp_styles;
5536
		$item = $wp_styles->registered[ $handle ];
5537
5538
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5539
			return $tag;
5540
		}
5541
5542
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5543
			$href = $matches[1];
5544
			// Strip off query string
5545
			if ( $pos = strpos( $href, '?' ) ) {
5546
				$href = substr( $href, 0, $pos );
5547
			}
5548
			// Strip off fragment
5549
			if ( $pos = strpos( $href, '#' ) ) {
5550
				$href = substr( $href, 0, $pos );
5551
			}
5552
		} else {
5553
			return $tag;
5554
		}
5555
5556
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5557
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5558
			return $tag;
5559
		}
5560
5561
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5562
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5563
			// And this isn't the pass that actually deals with the RTL version...
5564
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5565
				// Short out, as the RTL version will deal with it in a moment.
5566
				return $tag;
5567
			}
5568
		}
5569
5570
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5571
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5572
		if ( $css ) {
5573
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5574
			if ( empty( $item->extra['after'] ) ) {
5575
				wp_add_inline_style( $handle, $css );
5576
			} else {
5577
				array_unshift( $item->extra['after'], $css );
5578
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5579
			}
5580
		}
5581
5582
		return $tag;
5583
	}
5584
5585
	/**
5586
	 * Loads a view file from the views
5587
	 *
5588
	 * Data passed in with the $data parameter will be available in the
5589
	 * template file as $data['value']
5590
	 *
5591
	 * @param string $template - Template file to load
5592
	 * @param array $data - Any data to pass along to the template
5593
	 * @return boolean - If template file was found
5594
	 **/
5595
	public function load_view( $template, $data = array() ) {
5596
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5597
5598
		if( file_exists( $views_dir . $template ) ) {
5599
			require_once( $views_dir . $template );
5600
			return true;
5601
		}
5602
5603
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5604
		return false;
5605
	}
5606
5607
	/**
5608
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5609
	 */
5610
	public function deprecated_hooks() {
5611
		global $wp_filter;
5612
5613
		/*
5614
		 * Format:
5615
		 * deprecated_filter_name => replacement_name
5616
		 *
5617
		 * If there is no replacement, use null for replacement_name
5618
		 */
5619
		$deprecated_list = array(
5620
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5621
			'wpl_sharing_2014_1'                                     => null,
5622
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5623
			'jetpack_identity_crisis_options_to_check'               => null,
5624
			'update_option_jetpack_single_user_site'                 => null,
5625
			'audio_player_default_colors'                            => null,
5626
			'add_option_jetpack_featured_images_enabled'             => null,
5627
			'add_option_jetpack_update_details'                      => null,
5628
			'add_option_jetpack_updates'                             => null,
5629
			'add_option_jetpack_network_name'                        => null,
5630
			'add_option_jetpack_network_allow_new_registrations'     => null,
5631
			'add_option_jetpack_network_add_new_users'               => null,
5632
			'add_option_jetpack_network_site_upload_space'           => null,
5633
			'add_option_jetpack_network_upload_file_types'           => null,
5634
			'add_option_jetpack_network_enable_administration_menus' => null,
5635
			'add_option_jetpack_is_multi_site'                       => null,
5636
			'add_option_jetpack_is_main_network'                     => null,
5637
			'add_option_jetpack_main_network_site'                   => null,
5638
			'jetpack_sync_all_registered_options'                    => null,
5639
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5640
			'jetpack_is_post_mailable'                               => null,
5641
		);
5642
5643
		// This is a silly loop depth. Better way?
5644
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5645
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
5646
				foreach( $wp_filter[$hook] AS $func => $values ) {
5647
					foreach( $values AS $hooked ) {
5648
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
5649
					}
5650
				}
5651
			}
5652
		}
5653
	}
5654
5655
	/**
5656
	 * Converts any url in a stylesheet, to the correct absolute url.
5657
	 *
5658
	 * Considerations:
5659
	 *  - Normal, relative URLs     `feh.png`
5660
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5661
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5662
	 *  - Absolute URLs             `http://domain.com/feh.png`
5663
	 *  - Domain root relative URLs `/feh.png`
5664
	 *
5665
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5666
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5667
	 *
5668
	 * @return mixed|string
5669
	 */
5670
	public static function absolutize_css_urls( $css, $css_file_url ) {
5671
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5672
		$css_dir = dirname( $css_file_url );
5673
		$p       = parse_url( $css_dir );
5674
		$domain  = sprintf(
5675
					'%1$s//%2$s%3$s%4$s',
5676
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5677
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5678
					$p['host'],
5679
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5680
				);
5681
5682
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5683
			$find = $replace = array();
5684
			foreach ( $matches as $match ) {
5685
				$url = trim( $match['path'], "'\" \t" );
5686
5687
				// If this is a data url, we don't want to mess with it.
5688
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5689
					continue;
5690
				}
5691
5692
				// If this is an absolute or protocol-agnostic url,
5693
				// we don't want to mess with it.
5694
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5695
					continue;
5696
				}
5697
5698
				switch ( substr( $url, 0, 1 ) ) {
5699
					case '/':
5700
						$absolute = $domain . $url;
5701
						break;
5702
					default:
5703
						$absolute = $css_dir . '/' . $url;
5704
				}
5705
5706
				$find[]    = $match[0];
5707
				$replace[] = sprintf( 'url("%s")', $absolute );
5708
			}
5709
			$css = str_replace( $find, $replace, $css );
5710
		}
5711
5712
		return $css;
5713
	}
5714
5715
	/**
5716
	 * This methods removes all of the registered css files on the front end
5717
	 * from Jetpack in favor of using a single file. In effect "imploding"
5718
	 * all the files into one file.
5719
	 *
5720
	 * Pros:
5721
	 * - Uses only ONE css asset connection instead of 15
5722
	 * - Saves a minimum of 56k
5723
	 * - Reduces server load
5724
	 * - Reduces time to first painted byte
5725
	 *
5726
	 * Cons:
5727
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5728
	 *		should not cause any issues with themes.
5729
	 * - Plugins/themes dequeuing styles no longer do anything. See
5730
	 *		jetpack_implode_frontend_css filter for a workaround
5731
	 *
5732
	 * For some situations developers may wish to disable css imploding and
5733
	 * instead operate in legacy mode where each file loads seperately and
5734
	 * can be edited individually or dequeued. This can be accomplished with
5735
	 * the following line:
5736
	 *
5737
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5738
	 *
5739
	 * @since 3.2
5740
	 **/
5741
	public function implode_frontend_css( $travis_test = false ) {
5742
		$do_implode = true;
5743
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5744
			$do_implode = false;
5745
		}
5746
5747
		/**
5748
		 * Allow CSS to be concatenated into a single jetpack.css file.
5749
		 *
5750
		 * @since 3.2.0
5751
		 *
5752
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5753
		 */
5754
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5755
5756
		// Do not use the imploded file when default behaviour was altered through the filter
5757
		if ( ! $do_implode ) {
5758
			return;
5759
		}
5760
5761
		// We do not want to use the imploded file in dev mode, or if not connected
5762
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5763
			if ( ! $travis_test ) {
5764
				return;
5765
			}
5766
		}
5767
5768
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5769
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5770
			return;
5771
		}
5772
5773
		/*
5774
		 * Now we assume Jetpack is connected and able to serve the single
5775
		 * file.
5776
		 *
5777
		 * In the future there will be a check here to serve the file locally
5778
		 * or potentially from the Jetpack CDN
5779
		 *
5780
		 * For now:
5781
		 * - Enqueue a single imploded css file
5782
		 * - Zero out the style_loader_tag for the bundled ones
5783
		 * - Be happy, drink scotch
5784
		 */
5785
5786
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5787
5788
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5789
5790
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5791
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5792
	}
5793
5794
	function concat_remove_style_loader_tag( $tag, $handle ) {
5795
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5796
			$tag = '';
5797
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5798
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5799
			}
5800
		}
5801
5802
		return $tag;
5803
	}
5804
5805
	/*
5806
	 * Check the heartbeat data
5807
	 *
5808
	 * Organizes the heartbeat data by severity.  For example, if the site
5809
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5810
	 *
5811
	 * Data will be added to "caution" array, if it either:
5812
	 *  - Out of date Jetpack version
5813
	 *  - Out of date WP version
5814
	 *  - Out of date PHP version
5815
	 *
5816
	 * $return array $filtered_data
5817
	 */
5818
	public static function jetpack_check_heartbeat_data() {
5819
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5820
5821
		$good    = array();
5822
		$caution = array();
5823
		$bad     = array();
5824
5825
		foreach ( $raw_data as $stat => $value ) {
5826
5827
			// Check jetpack version
5828
			if ( 'version' == $stat ) {
5829
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5830
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5831
					continue;
5832
				}
5833
			}
5834
5835
			// Check WP version
5836
			if ( 'wp-version' == $stat ) {
5837
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5838
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5839
					continue;
5840
				}
5841
			}
5842
5843
			// Check PHP version
5844
			if ( 'php-version' == $stat ) {
5845
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5846
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5847
					continue;
5848
				}
5849
			}
5850
5851
			// Check ID crisis
5852
			if ( 'identitycrisis' == $stat ) {
5853
				if ( 'yes' == $value ) {
5854
					$bad[ $stat ] = $value;
5855
					continue;
5856
				}
5857
			}
5858
5859
			// The rest are good :)
5860
			$good[ $stat ] = $value;
5861
		}
5862
5863
		$filtered_data = array(
5864
			'good'    => $good,
5865
			'caution' => $caution,
5866
			'bad'     => $bad
5867
		);
5868
5869
		return $filtered_data;
5870
	}
5871
5872
5873
	/*
5874
	 * This method is used to organize all options that can be reset
5875
	 * without disconnecting Jetpack.
5876
	 *
5877
	 * It is used in class.jetpack-cli.php to reset options
5878
	 *
5879
	 * @return array of options to delete.
5880
	 */
5881
	public static function get_jetpack_options_for_reset() {
5882
		$jetpack_options            = Jetpack_Options::get_option_names();
5883
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
5884
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
5885
5886
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
5887
5888
		// A manual build of the wp options
5889
		$wp_options = array(
5890
			'sharing-options',
5891
			'disabled_likes',
5892
			'disabled_reblogs',
5893
			'jetpack_comments_likes_enabled',
5894
			'wp_mobile_excerpt',
5895
			'wp_mobile_featured_images',
5896
			'wp_mobile_app_promos',
5897
			'stats_options',
5898
			'stats_dashboard_widget',
5899
			'safecss_preview_rev',
5900
			'safecss_rev',
5901
			'safecss_revision_migrated',
5902
			'nova_menu_order',
5903
			'jetpack_portfolio',
5904
			'jetpack_portfolio_posts_per_page',
5905
			'jetpack_testimonial',
5906
			'jetpack_testimonial_posts_per_page',
5907
			'wp_mobile_custom_css',
5908
			'sharedaddy_disable_resources',
5909
			'sharing-options',
5910
			'sharing-services',
5911
			'site_icon_temp_data',
5912
			'featured-content',
5913
			'site_logo',
5914
			'jetpack_dismissed_notices',
5915
		);
5916
5917
		// Flag some Jetpack options as unsafe
5918
		$unsafe_options = array(
5919
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
5920
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
5921
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
5922
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
5923
5924
			// non_compact
5925
			'activated',
5926
5927
			// private
5928
			'register',
5929
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
5930
			'user_token',                  // (string) The User Token of this site. (deprecated)
5931
			'user_tokens'
5932
		);
5933
5934
		// Remove the unsafe Jetpack options
5935
		foreach ( $unsafe_options as $unsafe_option ) {
5936
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
5937
				unset( $all_jp_options[ $key ] );
5938
			}
5939
		}
5940
5941
		$options = array(
5942
			'jp_options' => $all_jp_options,
5943
			'wp_options' => $wp_options
5944
		);
5945
5946
		return $options;
5947
	}
5948
5949
	/**
5950
	 * Check if an option of a Jetpack module has been updated.
5951
	 *
5952
	 * If any module option has been updated before Jump Start has been dismissed,
5953
	 * update the 'jumpstart' option so we can hide Jump Start.
5954
	 *
5955
	 * @param string $option_name
5956
	 *
5957
	 * @return bool
5958
	 */
5959
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5960
		// Bail if Jump Start has already been dismissed
5961
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
5962
			return false;
5963
		}
5964
5965
		$jetpack = Jetpack::init();
5966
5967
		// Manual build of module options
5968
		$option_names = self::get_jetpack_options_for_reset();
5969
5970
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5971
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5972
5973
			//Jump start is being dismissed send data to MC Stats
5974
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5975
5976
			$jetpack->do_stats( 'server_side' );
5977
		}
5978
5979
	}
5980
5981
	/*
5982
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
5983
	 * so we can bring them directly to their site in calypso.
5984
	 *
5985
	 * @param string | url
5986
	 * @return string | url without the guff
5987
	 */
5988
	public static function build_raw_urls( $url ) {
5989
		$strip_http = '/.*?:\/\//i';
5990
		$url = preg_replace( $strip_http, '', $url  );
5991
		$url = str_replace( '/', '::', $url );
5992
		return $url;
5993
	}
5994
5995
	/**
5996
	 * Stores and prints out domains to prefetch for page speed optimization.
5997
	 *
5998
	 * @param mixed $new_urls
5999
	 */
6000
	public static function dns_prefetch( $new_urls = null ) {
6001
		static $prefetch_urls = array();
6002
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6003
			echo "\r\n";
6004
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6005
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6006
			}
6007
		} elseif ( ! empty( $new_urls ) ) {
6008
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6009
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6010
			}
6011
			foreach ( (array) $new_urls as $this_new_url ) {
6012
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6013
			}
6014
			$prefetch_urls = array_unique( $prefetch_urls );
6015
		}
6016
	}
6017
6018
	public function wp_dashboard_setup() {
6019
		if ( self::is_active() ) {
6020
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6021
			$widget_title = __( 'Site Stats', 'jetpack' );
6022
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6023
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6024
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6025
		}
6026
6027
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6028
			wp_add_dashboard_widget(
6029
				'jetpack_summary_widget',
6030
				$widget_title,
6031
				array( __CLASS__, 'dashboard_widget' )
6032
			);
6033
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6034
6035
			// If we're inactive and not in development mode, sort our box to the top.
6036
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6037
				global $wp_meta_boxes;
6038
6039
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6040
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6041
6042
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6043
			}
6044
		}
6045
	}
6046
6047
	/**
6048
	 * @param mixed $result Value for the user's option
6049
	 * @return mixed
6050
	 */
6051
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6052
		if ( ! is_array( $sorted ) ) {
6053
			return $sorted;
6054
		}
6055
6056
		foreach ( $sorted as $box_context => $ids ) {
6057
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6058
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6059
				continue;
6060
			}
6061
6062
			$ids_array = explode( ',', $ids );
6063
			$key = array_search( 'dashboard_stats', $ids_array );
6064
6065
			if ( false !== $key ) {
6066
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6067
				$ids_array[ $key ] = 'jetpack_summary_widget';
6068
				$sorted[ $box_context ] = implode( ',', $ids_array );
6069
				// We've found it, stop searching, and just return.
6070
				break;
6071
			}
6072
		}
6073
6074
		return $sorted;
6075
	}
6076
6077
	public static function dashboard_widget() {
6078
		/**
6079
		 * Fires when the dashboard is loaded.
6080
		 *
6081
		 * @since 3.4.0
6082
		 */
6083
		do_action( 'jetpack_dashboard_widget' );
6084
	}
6085
6086
	public static function dashboard_widget_footer() {
6087
		?>
6088
		<footer>
6089
6090
		<div class="protect">
6091
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6092
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6093
				<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>
6094
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6095
				<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' ); ?>">
6096
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6097
				</a>
6098
			<?php else : ?>
6099
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6100
			<?php endif; ?>
6101
		</div>
6102
6103
		<div class="akismet">
6104
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6105
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6106
				<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>
6107
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6108
				<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">
6109
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6110
				</a>
6111
			<?php else : ?>
6112
				<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>
6113
			<?php endif; ?>
6114
		</div>
6115
6116
		</footer>
6117
		<?php
6118
	}
6119
6120
	public function dashboard_widget_connect_to_wpcom() {
6121
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6122
			return;
6123
		}
6124
		?>
6125
		<div class="wpcom-connect">
6126
			<div class="jp-emblem">
6127
			<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">
6128
				<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"/>
6129
			</svg>
6130
			</div>
6131
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6132
			<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>
6133
6134
			<div class="actions">
6135
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6136
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6137
				</a>
6138
			</div>
6139
		</div>
6140
		<?php
6141
	}
6142
6143
	/**
6144
	 * Return string containing the Jetpack logo.
6145
	 *
6146
	 * @since 3.9.0
6147
	 *
6148
	 * @return string
6149
	 */
6150
	public static function get_jp_emblem() {
6151
		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>';
6152
	}
6153
6154
	/*
6155
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6156
	 */
6157
	function jetpack_icon_user_connected( $columns ) {
6158
		$columns['user_jetpack'] = '';
6159
		return $columns;
6160
	}
6161
6162
	/*
6163
	 * Show Jetpack icon if the user is linked.
6164
	 */
6165
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6166
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6167
			$emblem_html = sprintf(
6168
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6169
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6170
				Jetpack::get_jp_emblem()
6171
			);
6172
			return $emblem_html;
6173
		}
6174
6175
		return $val;
6176
	}
6177
6178
	/*
6179
	 * Style the Jetpack user column
6180
	 */
6181
	function jetpack_user_col_style() {
6182
		global $current_screen;
6183
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6184
			<style>
6185
				.fixed .column-user_jetpack {
6186
					width: 21px;
6187
				}
6188
				.jp-emblem-user-admin path {
6189
					fill: #8cc258;
6190
				}
6191
			</style>
6192
		<?php }
6193
	}
6194
}
6195