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