Completed
Push — master-stable ( 2cb821...605f06 )
by Jeremy
184:40 queued 169:16
created

class.jetpack.php (5 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
		return ! preg_match( '/^\d+(\.\d+)+$/', JETPACK__VERSION );
1164
	}
1165
1166
	/**
1167
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1168
	 */
1169
	public static function is_user_connected( $user_id = false ) {
1170
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1171
		if ( ! $user_id ) {
1172
			return false;
1173
		}
1174
1175
		return (bool) Jetpack_Data::get_access_token( $user_id );
1176
	}
1177
1178
	/**
1179
	 * Get the wpcom user data of the current|specified connected user.
1180
	 */
1181
	public static function get_connected_user_data( $user_id = null ) {
1182
		if ( ! $user_id ) {
1183
			$user_id = get_current_user_id();
1184
		}
1185
1186
		$transient_key = "jetpack_connected_user_data_$user_id";
1187
1188
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1189
			return $cached_user_data;
1190
		}
1191
1192
		Jetpack::load_xml_rpc_client();
1193
		$xml = new Jetpack_IXR_Client( array(
1194
			'user_id' => $user_id,
1195
		) );
1196
		$xml->query( 'wpcom.getUser' );
1197
		if ( ! $xml->isError() ) {
1198
			$user_data = $xml->getResponse();
1199
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1200
			return $user_data;
1201
		}
1202
1203
		return false;
1204
	}
1205
1206
	/**
1207
	 * Get the wpcom email of the current|specified connected user.
1208
	 */
1209 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1210
		if ( ! $user_id ) {
1211
			$user_id = get_current_user_id();
1212
		}
1213
		Jetpack::load_xml_rpc_client();
1214
		$xml = new Jetpack_IXR_Client( array(
1215
			'user_id' => $user_id,
1216
		) );
1217
		$xml->query( 'wpcom.getUserEmail' );
1218
		if ( ! $xml->isError() ) {
1219
			return $xml->getResponse();
1220
		}
1221
		return false;
1222
	}
1223
1224
	/**
1225
	 * Get the wpcom email of the master user.
1226
	 */
1227
	public static function get_master_user_email() {
1228
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1229
		if ( $master_user_id ) {
1230
			return self::get_connected_user_email( $master_user_id );
1231
		}
1232
		return '';
1233
	}
1234
1235
	function current_user_is_connection_owner() {
1236
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1237
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1238
	}
1239
1240
	/**
1241
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1242
	 */
1243
	function extra_oembed_providers() {
1244
		// Cloudup: https://dev.cloudup.com/#oembed
1245
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1246
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1247
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1248
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1249
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1250
	}
1251
1252
	/**
1253
	 * Synchronize connected user role changes
1254
	 */
1255
	function user_role_change( $user_id ) {
1256
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1257
		Jetpack_Sync_Users::user_role_change( $user_id );
1258
	}
1259
1260
	/**
1261
	 * Loads the currently active modules.
1262
	 */
1263
	public static function load_modules() {
1264
		if ( ! self::is_active() && !self::is_development_mode() ) {
1265
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1266
				return;
1267
			}
1268
		}
1269
1270
		$version = Jetpack_Options::get_option( 'version' );
1271 View Code Duplication
		if ( ! $version ) {
1272
			$version = $old_version = JETPACK__VERSION . ':' . time();
1273
			/** This action is documented in class.jetpack.php */
1274
			do_action( 'updating_jetpack_version', $version, false );
1275
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1276
		}
1277
		list( $version ) = explode( ':', $version );
1278
1279
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1280
1281
		$modules_data = array();
1282
1283
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1284
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1285
			$updated_modules = array();
1286
			foreach ( $modules as $module ) {
1287
				$modules_data[ $module ] = Jetpack::get_module( $module );
1288
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1289
					continue;
1290
				}
1291
1292
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1293
					continue;
1294
				}
1295
1296
				$updated_modules[] = $module;
1297
			}
1298
1299
			$modules = array_diff( $modules, $updated_modules );
1300
		}
1301
1302
		$is_development_mode = Jetpack::is_development_mode();
1303
1304
		foreach ( $modules as $index => $module ) {
1305
			// If we're in dev mode, disable modules requiring a connection
1306
			if ( $is_development_mode ) {
1307
				// Prime the pump if we need to
1308
				if ( empty( $modules_data[ $module ] ) ) {
1309
					$modules_data[ $module ] = Jetpack::get_module( $module );
1310
				}
1311
				// If the module requires a connection, but we're in local mode, don't include it.
1312
				if ( $modules_data[ $module ]['requires_connection'] ) {
1313
					continue;
1314
				}
1315
			}
1316
1317
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1318
				continue;
1319
			}
1320
1321
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1322
				unset( $modules[ $index ] );
1323
				self::update_active_modules( array_values( $modules ) );
1324
				continue;
1325
			}
1326
1327
			/**
1328
			 * Fires when a specific module is loaded.
1329
			 * The dynamic part of the hook, $module, is the module slug.
1330
			 *
1331
			 * @since 1.1.0
1332
			 */
1333
			do_action( 'jetpack_module_loaded_' . $module );
1334
		}
1335
1336
		/**
1337
		 * Fires when all the modules are loaded.
1338
		 *
1339
		 * @since 1.1.0
1340
		 */
1341
		do_action( 'jetpack_modules_loaded' );
1342
1343
		// 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.
1344
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1345
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1346
	}
1347
1348
	/**
1349
	 * Check if Jetpack's REST API compat file should be included
1350
	 * @action plugins_loaded
1351
	 * @return null
1352
	 */
1353
	public function check_rest_api_compat() {
1354
		/**
1355
		 * Filters the list of REST API compat files to be included.
1356
		 *
1357
		 * @since 2.2.5
1358
		 *
1359
		 * @param array $args Array of REST API compat files to include.
1360
		 */
1361
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1362
1363
		if ( function_exists( 'bbpress' ) )
1364
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1365
1366
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1367
			require_once $_jetpack_rest_api_compat_include;
1368
	}
1369
1370
	/**
1371
	 * Gets all plugins currently active in values, regardless of whether they're
1372
	 * traditionally activated or network activated.
1373
	 *
1374
	 * @todo Store the result in core's object cache maybe?
1375
	 */
1376
	public static function get_active_plugins() {
1377
		$active_plugins = (array) get_option( 'active_plugins', array() );
1378
1379
		if ( is_multisite() ) {
1380
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1381
			// whereas active_plugins stores them in the values.
1382
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1383
			if ( $network_plugins ) {
1384
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1385
			}
1386
		}
1387
1388
		sort( $active_plugins );
1389
1390
		return array_unique( $active_plugins );
1391
	}
1392
1393
	/**
1394
	 * Gets and parses additional plugin data to send with the heartbeat data
1395
	 *
1396
	 * @since 3.8.1
1397
	 *
1398
	 * @return array Array of plugin data
1399
	 */
1400
	public static function get_parsed_plugin_data() {
1401
		if ( ! function_exists( 'get_plugins' ) ) {
1402
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1403
		}
1404
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1405
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1406
		$active_plugins = Jetpack::get_active_plugins();
1407
1408
		$plugins = array();
1409
		foreach ( $all_plugins as $path => $plugin_data ) {
1410
			$plugins[ $path ] = array(
1411
					'is_active' => in_array( $path, $active_plugins ),
1412
					'file'      => $path,
1413
					'name'      => $plugin_data['Name'],
1414
					'version'   => $plugin_data['Version'],
1415
					'author'    => $plugin_data['Author'],
1416
			);
1417
		}
1418
1419
		return $plugins;
1420
	}
1421
1422
	/**
1423
	 * Gets and parses theme data to send with the heartbeat data
1424
	 *
1425
	 * @since 3.8.1
1426
	 *
1427
	 * @return array Array of theme data
1428
	 */
1429
	public static function get_parsed_theme_data() {
1430
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1431
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1432
1433
		$themes = array();
1434
		foreach ( $all_themes as $slug => $theme_data ) {
1435
			$theme_headers = array();
1436
			foreach ( $header_keys as $header_key ) {
1437
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1438
			}
1439
1440
			$themes[ $slug ] = array(
1441
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1442
					'slug' => $slug,
1443
					'theme_root' => $theme_data->get_theme_root_uri(),
1444
					'parent' => $theme_data->parent(),
1445
					'headers' => $theme_headers
1446
			);
1447
		}
1448
1449
		return $themes;
1450
	}
1451
1452
	/**
1453
	 * Checks whether a specific plugin is active.
1454
	 *
1455
	 * We don't want to store these in a static variable, in case
1456
	 * there are switch_to_blog() calls involved.
1457
	 */
1458
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1459
		return in_array( $plugin, self::get_active_plugins() );
1460
	}
1461
1462
	/**
1463
	 * Check if Jetpack's Open Graph tags should be used.
1464
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1465
	 *
1466
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1467
	 * @action plugins_loaded
1468
	 * @return null
1469
	 */
1470
	public function check_open_graph() {
1471
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1472
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1473
		}
1474
1475
		$active_plugins = self::get_active_plugins();
1476
1477
		if ( ! empty( $active_plugins ) ) {
1478
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1479
				if ( in_array( $plugin, $active_plugins ) ) {
1480
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1481
					break;
1482
				}
1483
			}
1484
		}
1485
1486
		/**
1487
		 * Allow the addition of Open Graph Meta Tags to all pages.
1488
		 *
1489
		 * @since 2.0.3
1490
		 *
1491
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1492
		 */
1493
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1494
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1495
		}
1496
	}
1497
1498
	/**
1499
	 * Check if Jetpack's Twitter tags should be used.
1500
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1501
	 *
1502
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1503
	 * @action plugins_loaded
1504
	 * @return null
1505
	 */
1506
	public function check_twitter_tags() {
1507
1508
		$active_plugins = self::get_active_plugins();
1509
1510
		if ( ! empty( $active_plugins ) ) {
1511
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1512
				if ( in_array( $plugin, $active_plugins ) ) {
1513
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1514
					break;
1515
				}
1516
			}
1517
		}
1518
1519
		/**
1520
		 * Allow Twitter Card Meta tags to be disabled.
1521
		 *
1522
		 * @since 2.6.0
1523
		 *
1524
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1525
		 */
1526
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1527
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1528
		}
1529
	}
1530
1531
	/**
1532
	 * Allows plugins to submit security reports.
1533
 	 *
1534
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1535
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1536
	 * @param array   $args         See definitions above
1537
	 */
1538
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1539
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1540
	}
1541
1542
/* Jetpack Options API */
1543
1544
	public static function get_option_names( $type = 'compact' ) {
1545
		return Jetpack_Options::get_option_names( $type );
1546
	}
1547
1548
	/**
1549
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1550
 	 *
1551
	 * @param string $name    Option name
1552
	 * @param mixed  $default (optional)
1553
	 */
1554
	public static function get_option( $name, $default = false ) {
1555
		return Jetpack_Options::get_option( $name, $default );
1556
	}
1557
1558
	/**
1559
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1560
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1561
	* $name must be a registered option name.
1562
	*/
1563
	public static function create_nonce( $name ) {
1564
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1565
1566
		Jetpack_Options::update_option( $name, $secret );
1567
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1568
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1569
			return new Jetpack_Error( 'missing_secrets' );
1570
1571
		return array(
1572
			'secret_1' => $secret_1,
1573
			'secret_2' => $secret_2,
1574
			'eol'      => $eol,
1575
		);
1576
	}
1577
1578
	/**
1579
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1580
 	 *
1581
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1582
	 * @param string $name  Option name
1583
	 * @param mixed  $value Option value
1584
	 */
1585
	public static function update_option( $name, $value ) {
1586
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1587
		return Jetpack_Options::update_option( $name, $value );
1588
	}
1589
1590
	/**
1591
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1592
 	 *
1593
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1594
	 * @param array $array array( option name => option value, ... )
1595
	 */
1596
	public static function update_options( $array ) {
1597
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1598
		return Jetpack_Options::update_options( $array );
1599
	}
1600
1601
	/**
1602
	 * Deletes the given option.  May be passed multiple option names as an array.
1603
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1604
	 *
1605
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1606
	 * @param string|array $names
1607
	 */
1608
	public static function delete_option( $names ) {
1609
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1610
		return Jetpack_Options::delete_option( $names );
1611
	}
1612
1613
	/**
1614
	 * Enters a user token into the user_tokens option
1615
	 *
1616
	 * @param int $user_id
1617
	 * @param string $token
1618
	 * return bool
1619
	 */
1620
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1621
		// not designed for concurrent updates
1622
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1623
		if ( ! is_array( $user_tokens ) )
1624
			$user_tokens = array();
1625
		$user_tokens[$user_id] = $token;
1626
		if ( $is_master_user ) {
1627
			$master_user = $user_id;
1628
			$options     = compact( 'user_tokens', 'master_user' );
1629
		} else {
1630
			$options = compact( 'user_tokens' );
1631
		}
1632
		return Jetpack_Options::update_options( $options );
1633
	}
1634
1635
	/**
1636
	 * Returns an array of all PHP files in the specified absolute path.
1637
	 * Equivalent to glob( "$absolute_path/*.php" ).
1638
	 *
1639
	 * @param string $absolute_path The absolute path of the directory to search.
1640
	 * @return array Array of absolute paths to the PHP files.
1641
	 */
1642
	public static function glob_php( $absolute_path ) {
1643
		if ( function_exists( 'glob' ) ) {
1644
			return glob( "$absolute_path/*.php" );
1645
		}
1646
1647
		$absolute_path = untrailingslashit( $absolute_path );
1648
		$files = array();
1649
		if ( ! $dir = @opendir( $absolute_path ) ) {
1650
			return $files;
1651
		}
1652
1653
		while ( false !== $file = readdir( $dir ) ) {
1654
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1655
				continue;
1656
			}
1657
1658
			$file = "$absolute_path/$file";
1659
1660
			if ( ! is_file( $file ) ) {
1661
				continue;
1662
			}
1663
1664
			$files[] = $file;
1665
		}
1666
1667
		closedir( $dir );
1668
1669
		return $files;
1670
	}
1671
1672
	public static function activate_new_modules( $redirect = false ) {
1673
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1674
			return;
1675
		}
1676
1677
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1678 View Code Duplication
		if ( ! $jetpack_old_version ) {
1679
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1680
			/** This action is documented in class.jetpack.php */
1681
			do_action( 'updating_jetpack_version', $version, false );
1682
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1683
		}
1684
1685
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1686
1687
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1688
			return;
1689
		}
1690
1691
		$active_modules     = Jetpack::get_active_modules();
1692
		$reactivate_modules = array();
1693
		foreach ( $active_modules as $active_module ) {
1694
			$module = Jetpack::get_module( $active_module );
1695
			if ( ! isset( $module['changed'] ) ) {
1696
				continue;
1697
			}
1698
1699
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1700
				continue;
1701
			}
1702
1703
			$reactivate_modules[] = $active_module;
1704
			Jetpack::deactivate_module( $active_module );
1705
		}
1706
1707
		$new_version = JETPACK__VERSION . ':' . time();
1708
		/** This action is documented in class.jetpack.php */
1709
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1710
		Jetpack_Options::update_options(
1711
			array(
1712
				'version'     => $new_version,
1713
				'old_version' => $jetpack_old_version,
1714
			)
1715
		);
1716
1717
		Jetpack::state( 'message', 'modules_activated' );
1718
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
1719
1720
		if ( $redirect ) {
1721
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1722
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1723
				$page = $_GET['page'];
1724
			}
1725
1726
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1727
			exit;
1728
		}
1729
	}
1730
1731
	/**
1732
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1733
	 * Make sure to tuck away module "library" files in a sub-directory.
1734
	 */
1735
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1736
		static $modules = null;
1737
1738
		if ( ! isset( $modules ) ) {
1739
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1740
			// Use the cache if we're on the front-end and it's available...
1741
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1742
				$modules = $available_modules_option[ JETPACK__VERSION ];
1743
			} else {
1744
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1745
1746
				$modules = array();
1747
1748
				foreach ( $files as $file ) {
1749
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1750
						continue;
1751
					}
1752
1753
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1754
				}
1755
1756
				Jetpack_Options::update_option( 'available_modules', array(
1757
					JETPACK__VERSION => $modules,
1758
				) );
1759
			}
1760
		}
1761
1762
		/**
1763
		 * Filters the array of modules available to be activated.
1764
		 *
1765
		 * @since 2.4.0
1766
		 *
1767
		 * @param array $modules Array of available modules.
1768
		 * @param string $min_version Minimum version number required to use modules.
1769
		 * @param string $max_version Maximum version number required to use modules.
1770
		 */
1771
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1772
1773
		if ( ! $min_version && ! $max_version ) {
1774
			return array_keys( $mods );
1775
		}
1776
1777
		$r = array();
1778
		foreach ( $mods as $slug => $introduced ) {
1779
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1780
				continue;
1781
			}
1782
1783
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1784
				continue;
1785
			}
1786
1787
			$r[] = $slug;
1788
		}
1789
1790
		return $r;
1791
	}
1792
1793
	/**
1794
	 * Default modules loaded on activation.
1795
	 */
1796
	public static function get_default_modules( $min_version = false, $max_version = false ) {
1797
		$return = array();
1798
1799
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1800
			$module_data = Jetpack::get_module( $module );
1801
1802
			switch ( strtolower( $module_data['auto_activate'] ) ) {
1803
				case 'yes' :
1804
					$return[] = $module;
1805
					break;
1806
				case 'public' :
1807
					if ( Jetpack_Options::get_option( 'public' ) ) {
1808
						$return[] = $module;
1809
					}
1810
					break;
1811
				case 'no' :
1812
				default :
1813
					break;
1814
			}
1815
		}
1816
		/**
1817
		 * Filters the array of default modules.
1818
		 *
1819
		 * @since 2.5.0
1820
		 *
1821
		 * @param array $return Array of default modules.
1822
		 * @param string $min_version Minimum version number required to use modules.
1823
		 * @param string $max_version Maximum version number required to use modules.
1824
		 */
1825
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1826
	}
1827
1828
	/**
1829
	 * Checks activated modules during auto-activation to determine
1830
	 * if any of those modules are being deprecated.  If so, close
1831
	 * them out, and add any replacement modules.
1832
	 *
1833
	 * Runs at priority 99 by default.
1834
	 *
1835
	 * This is run late, so that it can still activate a module if
1836
	 * the new module is a replacement for another that the user
1837
	 * currently has active, even if something at the normal priority
1838
	 * would kibosh everything.
1839
	 *
1840
	 * @since 2.6
1841
	 * @uses jetpack_get_default_modules filter
1842
	 * @param array $modules
1843
	 * @return array
1844
	 */
1845
	function handle_deprecated_modules( $modules ) {
1846
		$deprecated_modules = array(
1847
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
1848
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1849
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
1850
		);
1851
1852
		// Don't activate SSO if they never completed activating WPCC.
1853
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
1854
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1855
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1856
				$deprecated_modules['wpcc'] = null;
1857
			}
1858
		}
1859
1860
		foreach ( $deprecated_modules as $module => $replacement ) {
1861
			if ( Jetpack::is_module_active( $module ) ) {
1862
				self::deactivate_module( $module );
1863
				if ( $replacement ) {
1864
					$modules[] = $replacement;
1865
				}
1866
			}
1867
		}
1868
1869
		return array_unique( $modules );
1870
	}
1871
1872
	/**
1873
	 * Checks activated plugins during auto-activation to determine
1874
	 * if any of those plugins are in the list with a corresponding module
1875
	 * that is not compatible with the plugin. The module will not be allowed
1876
	 * to auto-activate.
1877
	 *
1878
	 * @since 2.6
1879
	 * @uses jetpack_get_default_modules filter
1880
	 * @param array $modules
1881
	 * @return array
1882
	 */
1883
	function filter_default_modules( $modules ) {
1884
1885
		$active_plugins = self::get_active_plugins();
1886
1887
		if ( ! empty( $active_plugins ) ) {
1888
1889
			// For each module we'd like to auto-activate...
1890
			foreach ( $modules as $key => $module ) {
1891
				// If there are potential conflicts for it...
1892
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1893
					// For each potential conflict...
1894
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1895
						// If that conflicting plugin is active...
1896
						if ( in_array( $plugin, $active_plugins ) ) {
1897
							// Remove that item from being auto-activated.
1898
							unset( $modules[ $key ] );
1899
						}
1900
					}
1901
				}
1902
			}
1903
		}
1904
1905
		return $modules;
1906
	}
1907
1908
	/**
1909
	 * Extract a module's slug from its full path.
1910
	 */
1911
	public static function get_module_slug( $file ) {
1912
		return str_replace( '.php', '', basename( $file ) );
1913
	}
1914
1915
	/**
1916
	 * Generate a module's path from its slug.
1917
	 */
1918
	public static function get_module_path( $slug ) {
1919
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
1920
	}
1921
1922
	/**
1923
	 * Load module data from module file. Headers differ from WordPress
1924
	 * plugin headers to avoid them being identified as standalone
1925
	 * plugins on the WordPress plugins page.
1926
	 */
1927
	public static function get_module( $module ) {
1928
		$headers = array(
1929
			'name'                      => 'Module Name',
1930
			'description'               => 'Module Description',
1931
			'jumpstart_desc'            => 'Jumpstart Description',
1932
			'sort'                      => 'Sort Order',
1933
			'recommendation_order'      => 'Recommendation Order',
1934
			'introduced'                => 'First Introduced',
1935
			'changed'                   => 'Major Changes In',
1936
			'deactivate'                => 'Deactivate',
1937
			'free'                      => 'Free',
1938
			'requires_connection'       => 'Requires Connection',
1939
			'auto_activate'             => 'Auto Activate',
1940
			'module_tags'               => 'Module Tags',
1941
			'feature'                   => 'Feature',
1942
			'additional_search_queries' => 'Additional Search Queries',
1943
		);
1944
1945
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
1946
1947
		$mod = Jetpack::get_file_data( $file, $headers );
1948
		if ( empty( $mod['name'] ) ) {
1949
			return false;
1950
		}
1951
1952
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
1953
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
1954
		$mod['deactivate']              = empty( $mod['deactivate'] );
1955
		$mod['free']                    = empty( $mod['free'] );
1956
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
1957
1958
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
1959
			$mod['auto_activate'] = 'No';
1960
		} else {
1961
			$mod['auto_activate'] = (string) $mod['auto_activate'];
1962
		}
1963
1964
		if ( $mod['module_tags'] ) {
1965
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
1966
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
1967
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
1968
		} else {
1969
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
1970
		}
1971
1972
		if ( $mod['feature'] ) {
1973
			$mod['feature'] = explode( ',', $mod['feature'] );
1974
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
1975
		} else {
1976
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
1977
		}
1978
1979
		/**
1980
		 * Filters the feature array on a module.
1981
		 *
1982
		 * This filter allows you to control where each module is filtered: Recommended,
1983
		 * Jumpstart, and the default "Other" listing.
1984
		 *
1985
		 * @since 3.5.0
1986
		 *
1987
		 * @param array   $mod['feature'] The areas to feature this module:
1988
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
1989
		 *     'Recommended' shows on the main Jetpack admin screen.
1990
		 *     'Other' should be the default if no other value is in the array.
1991
		 * @param string  $module The slug of the module, e.g. sharedaddy.
1992
		 * @param array   $mod All the currently assembled module data.
1993
		 */
1994
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
1995
1996
		/**
1997
		 * Filter the returned data about a module.
1998
		 *
1999
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2000
		 * so please be careful.
2001
		 *
2002
		 * @since 3.6.0
2003
		 *
2004
		 * @param array   $mod    The details of the requested module.
2005
		 * @param string  $module The slug of the module, e.g. sharedaddy
2006
		 * @param string  $file   The path to the module source file.
2007
		 */
2008
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2009
	}
2010
2011
	/**
2012
	 * Like core's get_file_data implementation, but caches the result.
2013
	 */
2014
	public static function get_file_data( $file, $headers ) {
2015
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2016
		$file_name = basename( $file );
2017
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2018
		$key              = md5( $file_name . serialize( $headers ) );
2019
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2020
2021
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2022
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2023
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2024
		}
2025
2026
		$data = get_file_data( $file, $headers );
2027
2028
		// Strip out any old Jetpack versions that are cluttering the option.
2029
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2030
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2031
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2032
2033
		return $data;
2034
	}
2035
2036
	/**
2037
	 * Return translated module tag.
2038
	 *
2039
	 * @param string $tag Tag as it appears in each module heading.
2040
	 *
2041
	 * @return mixed
2042
	 */
2043
	public static function translate_module_tag( $tag ) {
2044
		return jetpack_get_module_i18n_tag( $tag );
2045
	}
2046
2047
	/**
2048
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2049
	 *
2050
	 * @since 3.9.2
2051
	 *
2052
	 * @param array $modules
2053
	 *
2054
	 * @return string|void
2055
	 */
2056
	public static function get_translated_modules( $modules ) {
2057
		foreach ( $modules as $index => $module ) {
2058
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2059
			if ( isset( $module['name'] ) ) {
2060
				$modules[ $index ]['name'] = $i18n_module['name'];
2061
			}
2062
			if ( isset( $module['description'] ) ) {
2063
				$modules[ $index ]['description'] = $i18n_module['description'];
2064
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2065
			}
2066
		}
2067
		return $modules;
2068
	}
2069
2070
	/**
2071
	 * Get a list of activated modules as an array of module slugs.
2072
	 */
2073
	public static function get_active_modules() {
2074
		$active = Jetpack_Options::get_option( 'active_modules' );
2075
		if ( ! is_array( $active ) )
2076
			$active = array();
2077
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2078
			$active[] = 'vaultpress';
2079
		} else {
2080
			$active = array_diff( $active, array( 'vaultpress' ) );
2081
		}
2082
2083
		//If protect is active on the main site of a multisite, it should be active on all sites.
2084
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2085
			$active[] = 'protect';
2086
		}
2087
2088
		return array_unique( $active );
2089
	}
2090
2091
	/**
2092
	 * Check whether or not a Jetpack module is active.
2093
	 *
2094
	 * @param string $module The slug of a Jetpack module.
2095
	 * @return bool
2096
	 *
2097
	 * @static
2098
	 */
2099
	public static function is_module_active( $module ) {
2100
		return in_array( $module, self::get_active_modules() );
2101
	}
2102
2103
	public static function is_module( $module ) {
2104
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2105
	}
2106
2107
	/**
2108
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2109
	 *
2110
	 * @param bool $catch True to start catching, False to stop.
2111
	 *
2112
	 * @static
2113
	 */
2114
	public static function catch_errors( $catch ) {
2115
		static $display_errors, $error_reporting;
2116
2117
		if ( $catch ) {
2118
			$display_errors  = @ini_set( 'display_errors', 1 );
2119
			$error_reporting = @error_reporting( E_ALL );
2120
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2121
		} else {
2122
			@ini_set( 'display_errors', $display_errors );
2123
			@error_reporting( $error_reporting );
2124
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2125
		}
2126
	}
2127
2128
	/**
2129
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2130
	 */
2131
	public static function catch_errors_on_shutdown() {
2132
		Jetpack::state( 'php_errors', ob_get_clean() );
2133
	}
2134
2135
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2136
		$jetpack = Jetpack::init();
2137
2138
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2139
		$modules = array_merge( $other_modules, $modules );
2140
2141
		// Look for standalone plugins and disable if active.
2142
2143
		$to_deactivate = array();
2144
		foreach ( $modules as $module ) {
2145
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2146
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2147
			}
2148
		}
2149
2150
		$deactivated = array();
2151
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2152
			list( $probable_file, $probable_title ) = $deactivate_me;
2153
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2154
				$deactivated[] = $module;
2155
			}
2156
		}
2157
2158
		if ( $deactivated && $redirect ) {
2159
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2160
2161
			$url = add_query_arg(
2162
				array(
2163
					'action'   => 'activate_default_modules',
2164
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2165
				),
2166
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2167
			);
2168
			wp_safe_redirect( $url );
2169
			exit;
2170
		}
2171
2172
		/**
2173
		 * Fires before default modules are activated.
2174
		 *
2175
		 * @since 1.9.0
2176
		 *
2177
		 * @param string $min_version Minimum version number required to use modules.
2178
		 * @param string $max_version Maximum version number required to use modules.
2179
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2180
		 */
2181
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2182
2183
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2184
		Jetpack::restate();
2185
		Jetpack::catch_errors( true );
2186
2187
		$active = Jetpack::get_active_modules();
2188
2189
		foreach ( $modules as $module ) {
2190
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2191
				$active[] = $module;
2192
				self::update_active_modules( $active );
2193
				continue;
2194
			}
2195
2196
			if ( in_array( $module, $active ) ) {
2197
				$module_info = Jetpack::get_module( $module );
2198
				if ( ! $module_info['deactivate'] ) {
2199
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2200 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2201
						$active_state = explode( ',', $active_state );
2202
					} else {
2203
						$active_state = array();
2204
					}
2205
					$active_state[] = $module;
2206
					Jetpack::state( $state, implode( ',', $active_state ) );
2207
				}
2208
				continue;
2209
			}
2210
2211
			$file = Jetpack::get_module_path( $module );
2212
			if ( ! file_exists( $file ) ) {
2213
				continue;
2214
			}
2215
2216
			// we'll override this later if the plugin can be included without fatal error
2217
			if ( $redirect ) {
2218
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2219
			}
2220
			Jetpack::state( 'error', 'module_activation_failed' );
2221
			Jetpack::state( 'module', $module );
2222
			ob_start();
2223
			require $file;
2224
2225
			$active[] = $module;
2226
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2227 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2228
				$active_state = explode( ',', $active_state );
2229
			} else {
2230
				$active_state = array();
2231
			}
2232
			$active_state[] = $module;
2233
			Jetpack::state( $state, implode( ',', $active_state ) );
2234
			Jetpack::update_active_modules( $active );
2235
2236
			ob_end_clean();
2237
		}
2238
		Jetpack::state( 'error', false );
2239
		Jetpack::state( 'module', false );
2240
		Jetpack::catch_errors( false );
2241
		/**
2242
		 * Fires when default modules are activated.
2243
		 *
2244
		 * @since 1.9.0
2245
		 *
2246
		 * @param string $min_version Minimum version number required to use modules.
2247
		 * @param string $max_version Maximum version number required to use modules.
2248
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2249
		 */
2250
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2251
	}
2252
2253
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2254
		/**
2255
		 * Fires before a module is activated.
2256
		 *
2257
		 * @since 2.6.0
2258
		 *
2259
		 * @param string $module Module slug.
2260
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2261
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2262
		 */
2263
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2264
2265
		$jetpack = Jetpack::init();
2266
2267
		if ( ! strlen( $module ) )
2268
			return false;
2269
2270
		if ( ! Jetpack::is_module( $module ) )
2271
			return false;
2272
2273
		// If it's already active, then don't do it again
2274
		$active = Jetpack::get_active_modules();
2275
		foreach ( $active as $act ) {
2276
			if ( $act == $module )
2277
				return true;
2278
		}
2279
2280
		$module_data = Jetpack::get_module( $module );
2281
2282
		if ( ! Jetpack::is_active() ) {
2283
			if ( !Jetpack::is_development_mode() )
2284
				return false;
2285
2286
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2287
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2288
				return false;
2289
		}
2290
2291
		// Check and see if the old plugin is active
2292
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2293
			// Deactivate the old plugin
2294
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2295
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2296
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2297
				Jetpack::state( 'deactivated_plugins', $module );
2298
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2299
				exit;
2300
			}
2301
		}
2302
2303
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2304
		Jetpack::state( 'module', $module );
2305
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2306
2307
		Jetpack::catch_errors( true );
2308
		ob_start();
2309
		require Jetpack::get_module_path( $module );
2310
		/** This action is documented in class.jetpack.php */
2311
		do_action( 'jetpack_activate_module', $module );
2312
		$active[] = $module;
2313
		Jetpack::update_active_modules( $active );
2314
2315
		Jetpack::state( 'error', false ); // the override
2316
		ob_end_clean();
2317
		Jetpack::catch_errors( false );
2318
2319
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2320 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2321
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2322
2323
			//Jump start is being dismissed send data to MC Stats
2324
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2325
2326
			$jetpack->do_stats( 'server_side' );
2327
		}
2328
2329
		if ( $redirect ) {
2330
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2331
		}
2332
		if ( $exit ) {
2333
			exit;
2334
		}
2335
		return true;
2336
	}
2337
2338
	function activate_module_actions( $module ) {
2339
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2340
	}
2341
2342
	public static function deactivate_module( $module ) {
2343
		/**
2344
		 * Fires when a module is deactivated.
2345
		 *
2346
		 * @since 1.9.0
2347
		 *
2348
		 * @param string $module Module slug.
2349
		 */
2350
		do_action( 'jetpack_pre_deactivate_module', $module );
2351
2352
		$jetpack = Jetpack::init();
2353
2354
		$active = Jetpack::get_active_modules();
2355
		$new    = array_filter( array_diff( $active, (array) $module ) );
2356
2357
		// A flag for Jump Start so it's not shown again.
2358 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2359
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2360
2361
			//Jump start is being dismissed send data to MC Stats
2362
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2363
2364
			$jetpack->do_stats( 'server_side' );
2365
		}
2366
2367
		return self::update_active_modules( $new );
2368
	}
2369
2370
	public static function enable_module_configurable( $module ) {
2371
		$module = Jetpack::get_module_slug( $module );
2372
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2373
	}
2374
2375
	public static function module_configuration_url( $module ) {
2376
		$module = Jetpack::get_module_slug( $module );
2377
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2378
	}
2379
2380
	public static function module_configuration_load( $module, $method ) {
2381
		$module = Jetpack::get_module_slug( $module );
2382
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2383
	}
2384
2385
	public static function module_configuration_head( $module, $method ) {
2386
		$module = Jetpack::get_module_slug( $module );
2387
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2388
	}
2389
2390
	public static function module_configuration_screen( $module, $method ) {
2391
		$module = Jetpack::get_module_slug( $module );
2392
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2393
	}
2394
2395
	public static function module_configuration_activation_screen( $module, $method ) {
2396
		$module = Jetpack::get_module_slug( $module );
2397
		add_action( 'display_activate_module_setting_' . $module, $method );
2398
	}
2399
2400
/* Installation */
2401
2402
	public static function bail_on_activation( $message, $deactivate = true ) {
2403
?>
2404
<!doctype html>
2405
<html>
2406
<head>
2407
<meta charset="<?php bloginfo( 'charset' ); ?>">
2408
<style>
2409
* {
2410
	text-align: center;
2411
	margin: 0;
2412
	padding: 0;
2413
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2414
}
2415
p {
2416
	margin-top: 1em;
2417
	font-size: 18px;
2418
}
2419
</style>
2420
<body>
2421
<p><?php echo esc_html( $message ); ?></p>
2422
</body>
2423
</html>
2424
<?php
2425
		if ( $deactivate ) {
2426
			$plugins = get_option( 'active_plugins' );
2427
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2428
			$update  = false;
2429
			foreach ( $plugins as $i => $plugin ) {
2430
				if ( $plugin === $jetpack ) {
2431
					$plugins[$i] = false;
2432
					$update = true;
2433
				}
2434
			}
2435
2436
			if ( $update ) {
2437
				update_option( 'active_plugins', array_filter( $plugins ) );
2438
			}
2439
		}
2440
		exit;
2441
	}
2442
2443
	/**
2444
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2445
	 * @static
2446
	 */
2447
	public static function plugin_activation( $network_wide ) {
2448
		Jetpack_Options::update_option( 'activated', 1 );
2449
2450
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2451
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2452
		}
2453
2454
		if ( $network_wide )
2455
			Jetpack::state( 'network_nag', true );
2456
2457
		Jetpack::plugin_initialize();
2458
	}
2459
	/**
2460
	 * Runs before bumping version numbers up to a new version
2461
	 * @param  (string) $version    Version:timestamp
2462
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2463
	 * @return null              [description]
2464
	 */
2465
	public static function do_version_bump( $version, $old_version ) {
2466
2467
		if ( ! $old_version ) { // For new sites
2468
			// Setting up jetpack manage
2469
			Jetpack::activate_manage();
2470
		}
2471
	}
2472
2473
	/**
2474
	 * Sets the internal version number and activation state.
2475
	 * @static
2476
	 */
2477
	public static function plugin_initialize() {
2478
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2479
			Jetpack_Options::update_option( 'activated', 2 );
2480
		}
2481
2482 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2483
			$version = $old_version = JETPACK__VERSION . ':' . time();
2484
			/** This action is documented in class.jetpack.php */
2485
			do_action( 'updating_jetpack_version', $version, false );
2486
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2487
		}
2488
2489
		Jetpack::load_modules();
2490
2491
		Jetpack_Options::delete_option( 'do_activate' );
2492
	}
2493
2494
	/**
2495
	 * Removes all connection options
2496
	 * @static
2497
	 */
2498
	public static function plugin_deactivation( ) {
2499
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2500
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2501
			Jetpack_Network::init()->deactivate();
2502
		} else {
2503
			Jetpack::disconnect( false );
2504
			//Jetpack_Heartbeat::init()->deactivate();
2505
		}
2506
	}
2507
2508
	/**
2509
	 * Disconnects from the Jetpack servers.
2510
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2511
	 * @static
2512
	 */
2513
	public static function disconnect( $update_activated_state = true ) {
2514
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2515
		Jetpack::clean_nonces( true );
2516
2517
		Jetpack::load_xml_rpc_client();
2518
		$xml = new Jetpack_IXR_Client();
2519
		$xml->query( 'jetpack.deregister' );
2520
2521
		Jetpack_Options::delete_option(
2522
			array(
2523
				'register',
2524
				'blog_token',
2525
				'user_token',
2526
				'user_tokens',
2527
				'master_user',
2528
				'time_diff',
2529
				'fallback_no_verify_ssl_certs',
2530
			)
2531
		);
2532
2533
		if ( $update_activated_state ) {
2534
			Jetpack_Options::update_option( 'activated', 4 );
2535
		}
2536
2537
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2538
			// Check then record unique disconnection if site has never been disconnected previously
2539
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2540
				$jetpack_unique_connection['disconnected'] = 1;
2541
			} else {
2542
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2543
					//track unique disconnect
2544
					$jetpack = Jetpack::init();
2545
2546
					$jetpack->stat( 'connections', 'unique-disconnect' );
2547
					$jetpack->do_stats( 'server_side' );
2548
				}
2549
				// increment number of times disconnected
2550
				$jetpack_unique_connection['disconnected'] += 1;
2551
			}
2552
2553
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2554
		}
2555
2556
		// Delete all the sync related data. Since it could be taking up space.
2557
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2558
		Jetpack_Sync_Sender::get_instance()->uninstall();
2559
2560
		// Disable the Heartbeat cron
2561
		Jetpack_Heartbeat::init()->deactivate();
2562
	}
2563
2564
	/**
2565
	 * Unlinks the current user from the linked WordPress.com user
2566
	 */
2567
	public static function unlink_user( $user_id = null ) {
2568
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2569
			return false;
2570
2571
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2572
2573
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2574
			return false;
2575
2576
		if ( ! isset( $tokens[ $user_id ] ) )
2577
			return false;
2578
2579
		Jetpack::load_xml_rpc_client();
2580
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2581
		$xml->query( 'jetpack.unlink_user', $user_id );
2582
2583
		unset( $tokens[ $user_id ] );
2584
2585
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2586
2587
		/**
2588
		 * Fires after the current user has been unlinked from WordPress.com.
2589
		 *
2590
		 * @since 4.1.0
2591
		 *
2592
		 * @param int $user_id The current user's ID.
2593
		 */
2594
		do_action( 'jetpack_unlinked_user', $user_id );
2595
2596
		return true;
2597
	}
2598
2599
	/**
2600
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2601
	 */
2602
	public static function try_registration() {
2603
		// Let's get some testing in beta versions and such.
2604
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2605
			// Before attempting to connect, let's make sure that the domains are viable.
2606
			$domains_to_check = array_unique( array(
2607
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2608
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2609
			) );
2610
			foreach ( $domains_to_check as $domain ) {
2611
				$result = Jetpack_Data::is_usable_domain( $domain );
2612
				if ( is_wp_error( $result ) ) {
2613
					return $result;
2614
				}
2615
			}
2616
		}
2617
2618
		$result = Jetpack::register();
2619
2620
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2621
		if ( ! $result || is_wp_error( $result ) ) {
2622
			return $result;
2623
		} else {
2624
			return true;
2625
		}
2626
	}
2627
2628
	/**
2629
	 * Tracking an internal event log. Try not to put too much chaff in here.
2630
	 *
2631
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2632
	 */
2633
	public static function log( $code, $data = null ) {
2634
		// only grab the latest 200 entries
2635
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2636
2637
		// Append our event to the log
2638
		$log_entry = array(
2639
			'time'    => time(),
2640
			'user_id' => get_current_user_id(),
2641
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2642
			'code'    => $code,
2643
		);
2644
		// Don't bother storing it unless we've got some.
2645
		if ( ! is_null( $data ) ) {
2646
			$log_entry['data'] = $data;
2647
		}
2648
		$log[] = $log_entry;
2649
2650
		// Try add_option first, to make sure it's not autoloaded.
2651
		// @todo: Add an add_option method to Jetpack_Options
2652
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2653
			Jetpack_Options::update_option( 'log', $log );
2654
		}
2655
2656
		/**
2657
		 * Fires when Jetpack logs an internal event.
2658
		 *
2659
		 * @since 3.0.0
2660
		 *
2661
		 * @param array $log_entry {
2662
		 *	Array of details about the log entry.
2663
		 *
2664
		 *	@param string time Time of the event.
2665
		 *	@param int user_id ID of the user who trigerred the event.
2666
		 *	@param int blog_id Jetpack Blog ID.
2667
		 *	@param string code Unique name for the event.
2668
		 *	@param string data Data about the event.
2669
		 * }
2670
		 */
2671
		do_action( 'jetpack_log_entry', $log_entry );
2672
	}
2673
2674
	/**
2675
	 * Get the internal event log.
2676
	 *
2677
	 * @param $event (string) - only return the specific log events
2678
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2679
	 *
2680
	 * @return array of log events || WP_Error for invalid params
2681
	 */
2682
	public static function get_log( $event = false, $num = false ) {
2683
		if ( $event && ! is_string( $event ) ) {
2684
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2685
		}
2686
2687
		if ( $num && ! is_numeric( $num ) ) {
2688
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2689
		}
2690
2691
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2692
2693
		// If nothing set - act as it did before, otherwise let's start customizing the output
2694
		if ( ! $num && ! $event ) {
2695
			return $entire_log;
2696
		} else {
2697
			$entire_log = array_reverse( $entire_log );
2698
		}
2699
2700
		$custom_log_output = array();
2701
2702
		if ( $event ) {
2703
			foreach ( $entire_log as $log_event ) {
2704
				if ( $event == $log_event[ 'code' ] ) {
2705
					$custom_log_output[] = $log_event;
2706
				}
2707
			}
2708
		} else {
2709
			$custom_log_output = $entire_log;
2710
		}
2711
2712
		if ( $num ) {
2713
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2714
		}
2715
2716
		return $custom_log_output;
2717
	}
2718
2719
	/**
2720
	 * Log modification of important settings.
2721
	 */
2722
	public static function log_settings_change( $option, $old_value, $value ) {
2723
		switch( $option ) {
2724
			case 'jetpack_sync_non_public_post_stati':
2725
				self::log( $option, $value );
2726
				break;
2727
		}
2728
	}
2729
2730
	/**
2731
	 * Return stat data for WPCOM sync
2732
	 */
2733
	public static function get_stat_data( $encode = true ) {
2734
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
2735
		$additional_data = self::get_additional_stat_data();
2736
2737
		$merged_data = array_merge( $heartbeat_data, $additional_data );
2738
2739
		if ( $encode ) {
2740
			return json_encode( $merged_data );
2741
		}
2742
2743
		return $merged_data;
2744
	}
2745
2746
	/**
2747
	 * Get additional stat data to sync to WPCOM
2748
	 */
2749
	public static function get_additional_stat_data( $prefix = '' ) {
2750
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
2751
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2752
		$return["{$prefix}users"]          = count_users();
2753
		$return["{$prefix}site-count"]     = 0;
2754
		if ( function_exists( 'get_blog_count' ) ) {
2755
			$return["{$prefix}site-count"] = get_blog_count();
2756
		}
2757
		return $return;
2758
	}
2759
2760
	/* Admin Pages */
2761
2762
	function admin_init() {
2763
		// If the plugin is not connected, display a connect message.
2764
		if (
2765
			// the plugin was auto-activated and needs its candy
2766
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2767
		||
2768
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2769
			! Jetpack_Options::get_option( 'activated' )
2770
		) {
2771
			Jetpack::plugin_initialize();
2772
		}
2773
2774
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2775
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2776
				// Show connect notice on dashboard and plugins pages
2777
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
2778
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
2779
			}
2780
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2781
			// Upgrade: 1.1 -> 1.1.1
2782
			// Check and see if host can verify the Jetpack servers' SSL certificate
2783
			$args = array();
2784
			Jetpack_Client::_wp_remote_request(
2785
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2786
				$args,
2787
				true
2788
			);
2789
		} else {
2790
			// Show the notice on the Dashboard only for now
2791
2792
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2793
		}
2794
2795
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2796
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2797
		}
2798
2799
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2800
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2801
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2802
2803
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2804
			// Artificially throw errors in certain whitelisted cases during plugin activation
2805
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2806
		}
2807
2808
		// Jetpack Manage Activation Screen from .com
2809
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2810
2811
		// Add custom column in wp-admin/users.php to show whether user is linked.
2812
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2813
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2814
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2815
	}
2816
2817
	function admin_body_class( $admin_body_class = '' ) {
2818
		$classes = explode( ' ', trim( $admin_body_class ) );
2819
2820
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2821
2822
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2823
		return " $admin_body_class ";
2824
	}
2825
2826
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2827
		return $admin_body_class . ' jetpack-pagestyles ';
2828
	}
2829
2830
	function prepare_connect_notice() {
2831
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2832
2833
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
2834
2835
		if ( Jetpack::state( 'network_nag' ) )
2836
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
2837
	}
2838
	/**
2839
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2840
	 *
2841
	 * @return null
2842
	 */
2843
	function prepare_manage_jetpack_notice() {
2844
2845
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2846
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2847
	}
2848
2849
	function manage_activate_screen() {
2850
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2851
	}
2852
	/**
2853
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2854
	 * This function artificially throws errors for such cases (whitelisted).
2855
	 *
2856
	 * @param string $plugin The activated plugin.
2857
	 */
2858
	function throw_error_on_activate_plugin( $plugin ) {
2859
		$active_modules = Jetpack::get_active_modules();
2860
2861
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2862
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2863
			$throw = false;
2864
2865
			// Try and make sure it really was the stats plugin
2866
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2867
				if ( 'stats.php' == basename( $plugin ) ) {
2868
					$throw = true;
2869
				}
2870
			} else {
2871
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2872
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2873
					$throw = true;
2874
				}
2875
			}
2876
2877
			if ( $throw ) {
2878
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2879
			}
2880
		}
2881
	}
2882
2883
	function intercept_plugin_error_scrape_init() {
2884
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2885
	}
2886
2887
	function intercept_plugin_error_scrape( $action, $result ) {
2888
		if ( ! $result ) {
2889
			return;
2890
		}
2891
2892
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2893
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2894
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2895
			}
2896
		}
2897
	}
2898
2899
	function add_remote_request_handlers() {
2900
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2901
	}
2902
2903
	function remote_request_handlers() {
2904
		switch ( current_filter() ) {
2905
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2906
			$response = $this->upload_handler();
2907
			break;
2908
		default :
2909
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2910
			break;
2911
		}
2912
2913
		if ( ! $response ) {
2914
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2915
		}
2916
2917
		if ( is_wp_error( $response ) ) {
2918
			$status_code       = $response->get_error_data();
2919
			$error             = $response->get_error_code();
2920
			$error_description = $response->get_error_message();
2921
2922
			if ( ! is_int( $status_code ) ) {
2923
				$status_code = 400;
2924
			}
2925
2926
			status_header( $status_code );
2927
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
2928
		}
2929
2930
		status_header( 200 );
2931
		if ( true === $response ) {
2932
			exit;
2933
		}
2934
2935
		die( json_encode( (object) $response ) );
2936
	}
2937
2938
	function upload_handler() {
2939
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
2940
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
2941
		}
2942
2943
		$user = wp_authenticate( '', '' );
2944
		if ( ! $user || is_wp_error( $user ) ) {
2945
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
2946
		}
2947
2948
		wp_set_current_user( $user->ID );
2949
2950
		if ( ! current_user_can( 'upload_files' ) ) {
2951
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
2952
		}
2953
2954
		if ( empty( $_FILES ) ) {
2955
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
2956
		}
2957
2958
		foreach ( array_keys( $_FILES ) as $files_key ) {
2959
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
2960
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
2961
			}
2962
		}
2963
2964
		$media_keys = array_keys( $_FILES['media'] );
2965
2966
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
2967
		if ( ! $token || is_wp_error( $token ) ) {
2968
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
2969
		}
2970
2971
		$uploaded_files = array();
2972
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
2973
		unset( $GLOBALS['post'] );
2974
		foreach ( $_FILES['media']['name'] as $index => $name ) {
2975
			$file = array();
2976
			foreach ( $media_keys as $media_key ) {
2977
				$file[$media_key] = $_FILES['media'][$media_key][$index];
2978
			}
2979
2980
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
2981
2982
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
2983
			if ( $hmac_provided !== $hmac_file ) {
2984
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
2985
				continue;
2986
			}
2987
2988
			$_FILES['.jetpack.upload.'] = $file;
2989
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
2990
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
2991
				$post_id = 0;
2992
			}
2993
			$attachment_id = media_handle_upload(
2994
				'.jetpack.upload.',
2995
				$post_id,
2996
				array(),
2997
				array(
2998
					'action' => 'jetpack_upload_file',
2999
				)
3000
			);
3001
3002
			if ( ! $attachment_id ) {
3003
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3004
			} elseif ( is_wp_error( $attachment_id ) ) {
3005
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3006
			} else {
3007
				$attachment = get_post( $attachment_id );
3008
				$uploaded_files[$index] = (object) array(
3009
					'id'   => (string) $attachment_id,
3010
					'file' => $attachment->post_title,
3011
					'url'  => wp_get_attachment_url( $attachment_id ),
3012
					'type' => $attachment->post_mime_type,
3013
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3014
				);
3015
			}
3016
		}
3017
		if ( ! is_null( $global_post ) ) {
3018
			$GLOBALS['post'] = $global_post;
3019
		}
3020
3021
		return $uploaded_files;
3022
	}
3023
3024
	/**
3025
	 * Add help to the Jetpack page
3026
	 *
3027
	 * @since Jetpack (1.2.3)
3028
	 * @return false if not the Jetpack page
3029
	 */
3030
	function admin_help() {
3031
		$current_screen = get_current_screen();
3032
3033
		// Overview
3034
		$current_screen->add_help_tab(
3035
			array(
3036
				'id'		=> 'home',
3037
				'title'		=> __( 'Home', 'jetpack' ),
3038
				'content'	=>
3039
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3040
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3041
					'<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>',
3042
			)
3043
		);
3044
3045
		// Screen Content
3046
		if ( current_user_can( 'manage_options' ) ) {
3047
			$current_screen->add_help_tab(
3048
				array(
3049
					'id'		=> 'settings',
3050
					'title'		=> __( 'Settings', 'jetpack' ),
3051
					'content'	=>
3052
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3053
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3054
						'<ol>' .
3055
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3056
							'<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>' .
3057
						'</ol>' .
3058
						'<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>'
3059
				)
3060
			);
3061
		}
3062
3063
		// Help Sidebar
3064
		$current_screen->set_help_sidebar(
3065
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3066
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3067
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3068
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3069
		);
3070
	}
3071
3072
	function admin_menu_css() {
3073
		wp_enqueue_style( 'jetpack-icons' );
3074
	}
3075
3076
	function admin_menu_order() {
3077
		return true;
3078
	}
3079
3080 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3081
		$jp_menu_order = array();
3082
3083
		foreach ( $menu_order as $index => $item ) {
3084
			if ( $item != 'jetpack' ) {
3085
				$jp_menu_order[] = $item;
3086
			}
3087
3088
			if ( $index == 0 ) {
3089
				$jp_menu_order[] = 'jetpack';
3090
			}
3091
		}
3092
3093
		return $jp_menu_order;
3094
	}
3095
3096
	function admin_head() {
3097 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3098
			/** This action is documented in class.jetpack-admin-page.php */
3099
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3100
	}
3101
3102 View Code Duplication
	function admin_banner_styles() {
3103
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3104
3105
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3106
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3107
		wp_style_add_data( 'jetpack', 'suffix', $min );
3108
	}
3109
3110
	function plugin_action_links( $actions ) {
3111
3112
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3113
3114
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3115
			return array_merge(
3116
				$jetpack_home,
3117
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3118
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3119
				$actions
3120
				);
3121
			}
3122
3123
		return array_merge( $jetpack_home, $actions );
3124
	}
3125
3126
	function admin_connect_notice() {
3127
		// Don't show the connect notice anywhere but the plugins.php after activating
3128
		$current = get_current_screen();
3129
		if ( 'plugins' !== $current->parent_base )
3130
			return;
3131
3132
		if ( ! current_user_can( 'jetpack_connect' ) )
3133
			return;
3134
3135
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3136
		?>
3137
		<div id="message" class="updated jp-banner">
3138
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3139
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3140
					<div class="jp-banner__description-container">
3141
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3142
						<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>
3143
						<p class="jp-banner__button-container">
3144
							<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>
3145
							<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>
3146
						</p>
3147
					</div>
3148
			<?php else : ?>
3149
				<div class="jp-banner__content">
3150
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3151
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3152
				</div>
3153
				<div class="jp-banner__action-container">
3154
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3155
				</div>
3156
			<?php endif; ?>
3157
		</div>
3158
3159
		<?php
3160
	}
3161
3162
	/**
3163
	 * This is the first banner
3164
	 * It should be visible only to user that can update the option
3165
	 * Are not connected
3166
	 *
3167
	 * @return null
3168
	 */
3169
	function admin_jetpack_manage_notice() {
3170
		$screen = get_current_screen();
3171
3172
		// Don't show the connect notice on the jetpack settings page.
3173
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3174
			return;
3175
3176
		// Only show it if don't have the managment option set.
3177
		// And not dismissed it already.
3178
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3179
			return;
3180
		}
3181
3182
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3183
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3184
		/**
3185
		 * I think it would be great to have different wordsing depending on where you are
3186
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3187
		 * etc..
3188
		 */
3189
3190
		?>
3191
		<div id="message" class="updated jp-banner">
3192
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3193
				<div class="jp-banner__description-container">
3194
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3195
					<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>
3196
					<p class="jp-banner__button-container">
3197
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3198
						<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>
3199
					</p>
3200
				</div>
3201
		</div>
3202
		<?php
3203
	}
3204
3205
	/**
3206
	 * Returns the url that the user clicks to remove the notice for the big banner
3207
	 * @return (string)
3208
	 */
3209
	function opt_out_jetpack_manage_url() {
3210
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3211
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3212
	}
3213
	/**
3214
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3215
	 * @return (string)
3216
	 */
3217
	function opt_in_jetpack_manage_url() {
3218
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3219
	}
3220
3221
	function opt_in_jetpack_manage_notice() {
3222
		?>
3223
		<div class="wrap">
3224
			<div id="message" class="jetpack-message is-opt-in">
3225
				<?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' ); ?>
3226
			</div>
3227
		</div>
3228
		<?php
3229
3230
	}
3231
	/**
3232
	 * Determines whether to show the notice of not true = display notice
3233
	 * @return (bool)
3234
	 */
3235
	function can_display_jetpack_manage_notice() {
3236
		// never display the notice to users that can't do anything about it anyways
3237
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3238
			return false;
3239
3240
		// don't display if we are in development more
3241
		if( Jetpack::is_development_mode() ) {
3242
			return false;
3243
		}
3244
		// don't display if the site is private
3245
		if(  ! Jetpack_Options::get_option( 'public' ) )
3246
			return false;
3247
3248
		/**
3249
		 * Should the Jetpack Remote Site Management notice be displayed.
3250
		 *
3251
		 * @since 3.3.0
3252
		 *
3253
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3254
		 */
3255
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3256
	}
3257
3258
	function network_connect_notice() {
3259
		?>
3260
		<div id="message" class="updated jetpack-message">
3261
			<div class="squeezer">
3262
				<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>
3263
			</div>
3264
		</div>
3265
		<?php
3266
	}
3267
3268
	/*
3269
	 * Registration flow:
3270
	 * 1 - ::admin_page_load() action=register
3271
	 * 2 - ::try_registration()
3272
	 * 3 - ::register()
3273
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3274
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3275
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3276
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3277
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3278
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3279
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3280
	 *       jetpack_id, jetpack_secret, jetpack_public
3281
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3282
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3283
	 * 5 - user logs in with WP.com account
3284
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3285
	 *		- Jetpack_Client_Server::authorize()
3286
	 *		- Jetpack_Client_Server::get_token()
3287
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3288
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3289
	 *			- which responds with access_token, token_type, scope
3290
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3291
	 *		- Jetpack::activate_default_modules()
3292
	 *     		- Deactivates deprecated plugins
3293
	 *     		- Activates all default modules
3294
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3295
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3296
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3297
	 *     Done!
3298
	 */
3299
3300
	/**
3301
	 * Handles the page load events for the Jetpack admin page
3302
	 */
3303
	function admin_page_load() {
3304
		$error = false;
3305
3306
		// Make sure we have the right body class to hook stylings for subpages off of.
3307
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3308
3309
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3310
			// Should only be used in intermediate redirects to preserve state across redirects
3311
			Jetpack::restate();
3312
		}
3313
3314
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3315
			// User clicked in the iframe to link their accounts
3316
			if ( ! Jetpack::is_user_connected() ) {
3317
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3318
				if ( isset( $_GET['notes_iframe'] ) )
3319
					$connect_url .= '&notes_iframe';
3320
				wp_redirect( $connect_url );
3321
				exit;
3322
			} else {
3323
				if ( ! isset( $_GET['calypso_env'] ) ) {
3324
					Jetpack::state( 'message', 'already_authorized' );
3325
					wp_safe_redirect( Jetpack::admin_url() );
3326
				} else {
3327
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3328
					$connect_url .= '&already_authorized=true';
3329
					wp_redirect( $connect_url );
3330
				}
3331
			}
3332
		}
3333
3334
3335
		if ( isset( $_GET['action'] ) ) {
3336
			switch ( $_GET['action'] ) {
3337
			case 'authorize':
3338
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3339
					Jetpack::state( 'message', 'already_authorized' );
3340
					wp_safe_redirect( Jetpack::admin_url() );
3341
					exit;
3342
				}
3343
				Jetpack::log( 'authorize' );
3344
				$client_server = new Jetpack_Client_Server;
3345
				$client_server->client_authorize();
3346
				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...
3347
			case 'register' :
3348
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3349
					$error = 'cheatin';
3350
					break;
3351
				}
3352
				check_admin_referer( 'jetpack-register' );
3353
				Jetpack::log( 'register' );
3354
				Jetpack::maybe_set_version_option();
3355
				$registered = Jetpack::try_registration();
3356
				if ( is_wp_error( $registered ) ) {
3357
					$error = $registered->get_error_code();
3358
					Jetpack::state( 'error', $error );
3359
					Jetpack::state( 'error', $registered->get_error_message() );
3360
					break;
3361
				}
3362
3363
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3364
3365
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3366
				exit;
3367
			case 'activate' :
3368
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3369
					$error = 'cheatin';
3370
					break;
3371
				}
3372
3373
				$module = stripslashes( $_GET['module'] );
3374
				check_admin_referer( "jetpack_activate-$module" );
3375
				Jetpack::log( 'activate', $module );
3376
				Jetpack::activate_module( $module );
3377
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3378
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3379
				exit;
3380
			case 'activate_default_modules' :
3381
				check_admin_referer( 'activate_default_modules' );
3382
				Jetpack::log( 'activate_default_modules' );
3383
				Jetpack::restate();
3384
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3385
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3386
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3387
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3388
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3389
				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...
3390
			case 'disconnect' :
3391
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3392
					$error = 'cheatin';
3393
					break;
3394
				}
3395
3396
				check_admin_referer( 'jetpack-disconnect' );
3397
				Jetpack::log( 'disconnect' );
3398
				Jetpack::disconnect();
3399
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3400
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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