Completed
Push — enhance/js-i18n ( 86883a )
by
unknown
12:34
created

class.jetpack.php (6 issues)

Upgrade to new PHP Analysis Engine

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

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