Completed
Push — fix/videopress-always-active-o... ( 653bbf...8c0f4c )
by
unknown
34:46 queued 27:38
created

class.jetpack.php (13 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

Loading history...
2488
		}
2489
		return true;
2490
	}
2491
2492
	function activate_module_actions( $module ) {
2493
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2494
	}
2495
2496
	public static function deactivate_module( $module ) {
2497
		/**
2498
		 * Fires when a module is deactivated.
2499
		 *
2500
		 * @since 1.9.0
2501
		 *
2502
		 * @param string $module Module slug.
2503
		 */
2504
		do_action( 'jetpack_pre_deactivate_module', $module );
2505
2506
		$jetpack = Jetpack::init();
2507
2508
		$active = Jetpack::get_active_modules();
2509
		$new    = array_filter( array_diff( $active, (array) $module ) );
2510
2511
		// A flag for Jump Start so it's not shown again.
2512 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2513
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2514
2515
			//Jump start is being dismissed send data to MC Stats
2516
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2517
2518
			$jetpack->do_stats( 'server_side' );
2519
		}
2520
2521
		return self::update_active_modules( $new );
2522
	}
2523
2524
	public static function enable_module_configurable( $module ) {
2525
		$module = Jetpack::get_module_slug( $module );
2526
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2527
	}
2528
2529
	public static function module_configuration_url( $module ) {
2530
		$module = Jetpack::get_module_slug( $module );
2531
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2532
	}
2533
2534
	public static function module_configuration_load( $module, $method ) {
2535
		$module = Jetpack::get_module_slug( $module );
2536
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2537
	}
2538
2539
	public static function module_configuration_head( $module, $method ) {
2540
		$module = Jetpack::get_module_slug( $module );
2541
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2542
	}
2543
2544
	public static function module_configuration_screen( $module, $method ) {
2545
		$module = Jetpack::get_module_slug( $module );
2546
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2547
	}
2548
2549
	public static function module_configuration_activation_screen( $module, $method ) {
2550
		$module = Jetpack::get_module_slug( $module );
2551
		add_action( 'display_activate_module_setting_' . $module, $method );
2552
	}
2553
2554
/* Installation */
2555
2556
	public static function bail_on_activation( $message, $deactivate = true ) {
2557
?>
2558
<!doctype html>
2559
<html>
2560
<head>
2561
<meta charset="<?php bloginfo( 'charset' ); ?>">
2562
<style>
2563
* {
2564
	text-align: center;
2565
	margin: 0;
2566
	padding: 0;
2567
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2568
}
2569
p {
2570
	margin-top: 1em;
2571
	font-size: 18px;
2572
}
2573
</style>
2574
<body>
2575
<p><?php echo esc_html( $message ); ?></p>
2576
</body>
2577
</html>
2578
<?php
2579
		if ( $deactivate ) {
2580
			$plugins = get_option( 'active_plugins' );
2581
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2582
			$update  = false;
2583
			foreach ( $plugins as $i => $plugin ) {
2584
				if ( $plugin === $jetpack ) {
2585
					$plugins[$i] = false;
2586
					$update = true;
2587
				}
2588
			}
2589
2590
			if ( $update ) {
2591
				update_option( 'active_plugins', array_filter( $plugins ) );
2592
			}
2593
		}
2594
		exit;
2595
	}
2596
2597
	/**
2598
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2599
	 * @static
2600
	 */
2601
	public static function plugin_activation( $network_wide ) {
2602
		Jetpack_Options::update_option( 'activated', 1 );
2603
2604
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2605
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2606
		}
2607
2608
		if ( $network_wide )
2609
			Jetpack::state( 'network_nag', true );
2610
2611
		Jetpack::plugin_initialize();
2612
	}
2613
	/**
2614
	 * Runs before bumping version numbers up to a new version
2615
	 * @param  (string) $version    Version:timestamp
2616
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2617
	 * @return null              [description]
2618
	 */
2619
	public static function do_version_bump( $version, $old_version ) {
2620
2621
		if ( ! $old_version ) { // For new sites
2622
			// Setting up jetpack manage
2623
			Jetpack::activate_manage();
2624
		}
2625
	}
2626
2627
	/**
2628
	 * Sets the internal version number and activation state.
2629
	 * @static
2630
	 */
2631
	public static function plugin_initialize() {
2632
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2633
			Jetpack_Options::update_option( 'activated', 2 );
2634
		}
2635
2636 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2637
			$version = $old_version = JETPACK__VERSION . ':' . time();
2638
			/** This action is documented in class.jetpack.php */
2639
			do_action( 'updating_jetpack_version', $version, false );
2640
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2641
		}
2642
2643
		Jetpack::load_modules();
2644
2645
		Jetpack_Options::delete_option( 'do_activate' );
2646
	}
2647
2648
	/**
2649
	 * Removes all connection options
2650
	 * @static
2651
	 */
2652
	public static function plugin_deactivation( ) {
2653
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2654
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2655
			Jetpack_Network::init()->deactivate();
2656
		} else {
2657
			Jetpack::disconnect( false );
2658
			//Jetpack_Heartbeat::init()->deactivate();
2659
		}
2660
	}
2661
2662
	/**
2663
	 * Disconnects from the Jetpack servers.
2664
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2665
	 * @static
2666
	 */
2667
	public static function disconnect( $update_activated_state = true ) {
2668
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2669
		Jetpack::clean_nonces( true );
2670
2671
		// If the site is in an IDC because sync is not allowed,
2672
		// let's make sure to not disconnect the production site.
2673
		if ( ! self::validate_sync_error_idc_option() ) {
2674
			Jetpack::load_xml_rpc_client();
2675
			$xml = new Jetpack_IXR_Client();
2676
			$xml->query( 'jetpack.deregister' );
2677
		}
2678
2679
		Jetpack_Options::delete_option(
2680
			array(
2681
				'register',
2682
				'blog_token',
2683
				'user_token',
2684
				'user_tokens',
2685
				'master_user',
2686
				'time_diff',
2687
				'fallback_no_verify_ssl_certs',
2688
			)
2689
		);
2690
2691
		Jetpack_IDC::clear_all_idc_options();
2692
2693
		if ( $update_activated_state ) {
2694
			Jetpack_Options::update_option( 'activated', 4 );
2695
		}
2696
2697
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2698
			// Check then record unique disconnection if site has never been disconnected previously
2699
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2700
				$jetpack_unique_connection['disconnected'] = 1;
2701
			} else {
2702
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2703
					//track unique disconnect
2704
					$jetpack = Jetpack::init();
2705
2706
					$jetpack->stat( 'connections', 'unique-disconnect' );
2707
					$jetpack->do_stats( 'server_side' );
2708
				}
2709
				// increment number of times disconnected
2710
				$jetpack_unique_connection['disconnected'] += 1;
2711
			}
2712
2713
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2714
		}
2715
2716
		// Delete all the sync related data. Since it could be taking up space.
2717
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2718
		Jetpack_Sync_Sender::get_instance()->uninstall();
2719
2720
		// Disable the Heartbeat cron
2721
		Jetpack_Heartbeat::init()->deactivate();
2722
	}
2723
2724
	/**
2725
	 * Unlinks the current user from the linked WordPress.com user
2726
	 */
2727
	public static function unlink_user( $user_id = null ) {
2728
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2729
			return false;
2730
2731
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2732
2733
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2734
			return false;
2735
2736
		if ( ! isset( $tokens[ $user_id ] ) )
2737
			return false;
2738
2739
		Jetpack::load_xml_rpc_client();
2740
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2741
		$xml->query( 'jetpack.unlink_user', $user_id );
2742
2743
		unset( $tokens[ $user_id ] );
2744
2745
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2746
2747
		/**
2748
		 * Fires after the current user has been unlinked from WordPress.com.
2749
		 *
2750
		 * @since 4.1.0
2751
		 *
2752
		 * @param int $user_id The current user's ID.
2753
		 */
2754
		do_action( 'jetpack_unlinked_user', $user_id );
2755
2756
		return true;
2757
	}
2758
2759
	/**
2760
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2761
	 */
2762
	public static function try_registration() {
2763
		// Let's get some testing in beta versions and such.
2764
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2765
			// Before attempting to connect, let's make sure that the domains are viable.
2766
			$domains_to_check = array_unique( array(
2767
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2768
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2769
			) );
2770
			foreach ( $domains_to_check as $domain ) {
2771
				$result = Jetpack_Data::is_usable_domain( $domain );
2772
				if ( is_wp_error( $result ) ) {
2773
					return $result;
2774
				}
2775
			}
2776
		}
2777
2778
		$result = Jetpack::register();
2779
2780
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2781
		if ( ! $result || is_wp_error( $result ) ) {
2782
			return $result;
2783
		} else {
2784
			return true;
2785
		}
2786
	}
2787
2788
	/**
2789
	 * Tracking an internal event log. Try not to put too much chaff in here.
2790
	 *
2791
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2792
	 */
2793
	public static function log( $code, $data = null ) {
2794
		// only grab the latest 200 entries
2795
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2796
2797
		// Append our event to the log
2798
		$log_entry = array(
2799
			'time'    => time(),
2800
			'user_id' => get_current_user_id(),
2801
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2802
			'code'    => $code,
2803
		);
2804
		// Don't bother storing it unless we've got some.
2805
		if ( ! is_null( $data ) ) {
2806
			$log_entry['data'] = $data;
2807
		}
2808
		$log[] = $log_entry;
2809
2810
		// Try add_option first, to make sure it's not autoloaded.
2811
		// @todo: Add an add_option method to Jetpack_Options
2812
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2813
			Jetpack_Options::update_option( 'log', $log );
2814
		}
2815
2816
		/**
2817
		 * Fires when Jetpack logs an internal event.
2818
		 *
2819
		 * @since 3.0.0
2820
		 *
2821
		 * @param array $log_entry {
2822
		 *	Array of details about the log entry.
2823
		 *
2824
		 *	@param string time Time of the event.
2825
		 *	@param int user_id ID of the user who trigerred the event.
2826
		 *	@param int blog_id Jetpack Blog ID.
2827
		 *	@param string code Unique name for the event.
2828
		 *	@param string data Data about the event.
2829
		 * }
2830
		 */
2831
		do_action( 'jetpack_log_entry', $log_entry );
2832
	}
2833
2834
	/**
2835
	 * Get the internal event log.
2836
	 *
2837
	 * @param $event (string) - only return the specific log events
2838
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2839
	 *
2840
	 * @return array of log events || WP_Error for invalid params
2841
	 */
2842
	public static function get_log( $event = false, $num = false ) {
2843
		if ( $event && ! is_string( $event ) ) {
2844
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2845
		}
2846
2847
		if ( $num && ! is_numeric( $num ) ) {
2848
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2849
		}
2850
2851
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2852
2853
		// If nothing set - act as it did before, otherwise let's start customizing the output
2854
		if ( ! $num && ! $event ) {
2855
			return $entire_log;
2856
		} else {
2857
			$entire_log = array_reverse( $entire_log );
2858
		}
2859
2860
		$custom_log_output = array();
2861
2862
		if ( $event ) {
2863
			foreach ( $entire_log as $log_event ) {
2864
				if ( $event == $log_event[ 'code' ] ) {
2865
					$custom_log_output[] = $log_event;
2866
				}
2867
			}
2868
		} else {
2869
			$custom_log_output = $entire_log;
2870
		}
2871
2872
		if ( $num ) {
2873
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2874
		}
2875
2876
		return $custom_log_output;
2877
	}
2878
2879
	/**
2880
	 * Log modification of important settings.
2881
	 */
2882
	public static function log_settings_change( $option, $old_value, $value ) {
2883
		switch( $option ) {
2884
			case 'jetpack_sync_non_public_post_stati':
2885
				self::log( $option, $value );
2886
				break;
2887
		}
2888
	}
2889
2890
	/**
2891
	 * Return stat data for WPCOM sync
2892
	 */
2893
	public static function get_stat_data( $encode = true, $extended = true ) {
2894
		$data = Jetpack_Heartbeat::generate_stats_array();
2895
2896
		if ( $extended ) {
2897
			$additional_data = self::get_additional_stat_data();
2898
			$data = array_merge( $data, $additional_data );
2899
		}
2900
2901
		if ( $encode ) {
2902
			return json_encode( $data );
2903
		}
2904
2905
		return $data;
2906
	}
2907
2908
	/**
2909
	 * Get additional stat data to sync to WPCOM
2910
	 */
2911
	public static function get_additional_stat_data( $prefix = '' ) {
2912
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

Loading history...
2913
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2914
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
2915
		$return["{$prefix}site-count"]     = 0;
2916
2917
		if ( function_exists( 'get_blog_count' ) ) {
2918
			$return["{$prefix}site-count"] = get_blog_count();
2919
		}
2920
		return $return;
2921
	}
2922
2923
	private static function get_site_user_count() {
2924
		global $wpdb;
2925
2926
		if ( function_exists( 'wp_is_large_network' ) ) {
2927
			if ( wp_is_large_network( 'users' ) ) {
2928
				return -1; // Not a real value but should tell us that we are dealing with a large network.
2929
			}
2930
		}
2931 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
2932
			// It wasn't there, so regenerate the data and save the transient
2933
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
2934
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
2935
		}
2936
		return $user_count;
2937
	}
2938
2939
	/* Admin Pages */
2940
2941
	function admin_init() {
2942
		// If the plugin is not connected, display a connect message.
2943
		if (
2944
			// the plugin was auto-activated and needs its candy
2945
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2946
		||
2947
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2948
			! Jetpack_Options::get_option( 'activated' )
2949
		) {
2950
			Jetpack::plugin_initialize();
2951
		}
2952
2953
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2954
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2955
				Jetpack_Connection_Banner::init();
2956
			}
2957
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2958
			// Upgrade: 1.1 -> 1.1.1
2959
			// Check and see if host can verify the Jetpack servers' SSL certificate
2960
			$args = array();
2961
			Jetpack_Client::_wp_remote_request(
2962
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2963
				$args,
2964
				true
2965
			);
2966
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
2967
			// Show the notice on the Dashboard only for now
2968
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2969
		}
2970
2971
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2972
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2973
		}
2974
2975
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2976
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2977
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2978
2979
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2980
			// Artificially throw errors in certain whitelisted cases during plugin activation
2981
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2982
		}
2983
2984
		// Jetpack Manage Activation Screen from .com
2985
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2986
2987
		// Add custom column in wp-admin/users.php to show whether user is linked.
2988
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2989
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2990
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2991
	}
2992
2993
	function admin_body_class( $admin_body_class = '' ) {
2994
		$classes = explode( ' ', trim( $admin_body_class ) );
2995
2996
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2997
2998
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2999
		return " $admin_body_class ";
3000
	}
3001
3002
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3003
		return $admin_body_class . ' jetpack-pagestyles ';
3004
	}
3005
3006
	/**
3007
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3008
	 *
3009
	 * @return null
3010
	 */
3011
	function prepare_manage_jetpack_notice() {
3012
3013
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3014
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3015
	}
3016
3017
	function manage_activate_screen() {
3018
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3019
	}
3020
	/**
3021
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3022
	 * This function artificially throws errors for such cases (whitelisted).
3023
	 *
3024
	 * @param string $plugin The activated plugin.
3025
	 */
3026
	function throw_error_on_activate_plugin( $plugin ) {
3027
		$active_modules = Jetpack::get_active_modules();
3028
3029
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3030
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3031
			$throw = false;
3032
3033
			// Try and make sure it really was the stats plugin
3034
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3035
				if ( 'stats.php' == basename( $plugin ) ) {
3036
					$throw = true;
3037
				}
3038
			} else {
3039
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3040
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3041
					$throw = true;
3042
				}
3043
			}
3044
3045
			if ( $throw ) {
3046
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3047
			}
3048
		}
3049
	}
3050
3051
	function intercept_plugin_error_scrape_init() {
3052
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3053
	}
3054
3055
	function intercept_plugin_error_scrape( $action, $result ) {
3056
		if ( ! $result ) {
3057
			return;
3058
		}
3059
3060
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3061
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3062
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3063
			}
3064
		}
3065
	}
3066
3067
	function add_remote_request_handlers() {
3068
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3069
	}
3070
3071
	function remote_request_handlers() {
3072
		switch ( current_filter() ) {
3073
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3074
			$response = $this->upload_handler();
3075
			break;
3076
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

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

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

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

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

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