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

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

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

Loading history...
2314
			}
2315
		}
2316
2317
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2318
		Jetpack::state( 'module', $module );
2319
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2320
2321
		Jetpack::catch_errors( true );
2322
		ob_start();
2323
		require Jetpack::get_module_path( $module );
2324
		/** This action is documented in class.jetpack.php */
2325
		do_action( 'jetpack_activate_module', $module );
2326
		$active[] = $module;
2327
		Jetpack::update_active_modules( $active );
2328
2329
		Jetpack::state( 'error', false ); // the override
2330
		ob_end_clean();
2331
		Jetpack::catch_errors( false );
2332
2333
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2334 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2335
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2336
2337
			//Jump start is being dismissed send data to MC Stats
2338
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2339
2340
			$jetpack->do_stats( 'server_side' );
2341
		}
2342
2343
		if ( $redirect ) {
2344
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2345
		}
2346
		if ( $exit ) {
2347
			exit;
2348
		}
2349
		return true;
2350
	}
2351
2352
	function activate_module_actions( $module ) {
2353
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2354
	}
2355
2356
	public static function deactivate_module( $module ) {
2357
		/**
2358
		 * Fires when a module is deactivated.
2359
		 *
2360
		 * @since 1.9.0
2361
		 *
2362
		 * @param string $module Module slug.
2363
		 */
2364
		do_action( 'jetpack_pre_deactivate_module', $module );
2365
2366
		$jetpack = Jetpack::init();
2367
2368
		$active = Jetpack::get_active_modules();
2369
		$new    = array_filter( array_diff( $active, (array) $module ) );
2370
2371
		// A flag for Jump Start so it's not shown again.
2372 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2373
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2374
2375
			//Jump start is being dismissed send data to MC Stats
2376
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2377
2378
			$jetpack->do_stats( 'server_side' );
2379
		}
2380
2381
		return self::update_active_modules( $new );
2382
	}
2383
2384
	public static function enable_module_configurable( $module ) {
2385
		$module = Jetpack::get_module_slug( $module );
2386
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2387
	}
2388
2389
	public static function module_configuration_url( $module ) {
2390
		$module = Jetpack::get_module_slug( $module );
2391
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2392
	}
2393
2394
	public static function module_configuration_load( $module, $method ) {
2395
		$module = Jetpack::get_module_slug( $module );
2396
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2397
	}
2398
2399
	public static function module_configuration_head( $module, $method ) {
2400
		$module = Jetpack::get_module_slug( $module );
2401
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2402
	}
2403
2404
	public static function module_configuration_screen( $module, $method ) {
2405
		$module = Jetpack::get_module_slug( $module );
2406
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2407
	}
2408
2409
	public static function module_configuration_activation_screen( $module, $method ) {
2410
		$module = Jetpack::get_module_slug( $module );
2411
		add_action( 'display_activate_module_setting_' . $module, $method );
2412
	}
2413
2414
/* Installation */
2415
2416
	public static function bail_on_activation( $message, $deactivate = true ) {
2417
?>
2418
<!doctype html>
2419
<html>
2420
<head>
2421
<meta charset="<?php bloginfo( 'charset' ); ?>">
2422
<style>
2423
* {
2424
	text-align: center;
2425
	margin: 0;
2426
	padding: 0;
2427
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2428
}
2429
p {
2430
	margin-top: 1em;
2431
	font-size: 18px;
2432
}
2433
</style>
2434
<body>
2435
<p><?php echo esc_html( $message ); ?></p>
2436
</body>
2437
</html>
2438
<?php
2439
		if ( $deactivate ) {
2440
			$plugins = get_option( 'active_plugins' );
2441
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2442
			$update  = false;
2443
			foreach ( $plugins as $i => $plugin ) {
2444
				if ( $plugin === $jetpack ) {
2445
					$plugins[$i] = false;
2446
					$update = true;
2447
				}
2448
			}
2449
2450
			if ( $update ) {
2451
				update_option( 'active_plugins', array_filter( $plugins ) );
2452
			}
2453
		}
2454
		exit;
2455
	}
2456
2457
	/**
2458
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2459
	 * @static
2460
	 */
2461
	public static function plugin_activation( $network_wide ) {
2462
		Jetpack_Options::update_option( 'activated', 1 );
2463
2464
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2465
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2466
		}
2467
2468
		if ( $network_wide )
2469
			Jetpack::state( 'network_nag', true );
2470
2471
		Jetpack::plugin_initialize();
2472
	}
2473
	/**
2474
	 * Runs before bumping version numbers up to a new version
2475
	 * @param  (string) $version    Version:timestamp
2476
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2477
	 * @return null              [description]
2478
	 */
2479
	public static function do_version_bump( $version, $old_version ) {
2480
2481
		if ( ! $old_version ) { // For new sites
2482
			// Setting up jetpack manage
2483
			Jetpack::activate_manage();
2484
		}
2485
	}
2486
2487
	/**
2488
	 * Sets the internal version number and activation state.
2489
	 * @static
2490
	 */
2491
	public static function plugin_initialize() {
2492
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2493
			Jetpack_Options::update_option( 'activated', 2 );
2494
		}
2495
2496 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2497
			$version = $old_version = JETPACK__VERSION . ':' . time();
2498
			/** This action is documented in class.jetpack.php */
2499
			do_action( 'updating_jetpack_version', $version, false );
2500
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2501
		}
2502
2503
		Jetpack::load_modules();
2504
2505
		Jetpack_Options::delete_option( 'do_activate' );
2506
	}
2507
2508
	/**
2509
	 * Removes all connection options
2510
	 * @static
2511
	 */
2512
	public static function plugin_deactivation( ) {
2513
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2514
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2515
			Jetpack_Network::init()->deactivate();
2516
		} else {
2517
			Jetpack::disconnect( false );
2518
			//Jetpack_Heartbeat::init()->deactivate();
2519
		}
2520
	}
2521
2522
	/**
2523
	 * Disconnects from the Jetpack servers.
2524
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2525
	 * @static
2526
	 */
2527
	public static function disconnect( $update_activated_state = true ) {
2528
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2529
		Jetpack::clean_nonces( true );
2530
2531
		Jetpack::load_xml_rpc_client();
2532
		$xml = new Jetpack_IXR_Client();
2533
		$xml->query( 'jetpack.deregister' );
2534
2535
		Jetpack_Options::delete_option(
2536
			array(
2537
				'register',
2538
				'blog_token',
2539
				'user_token',
2540
				'user_tokens',
2541
				'master_user',
2542
				'time_diff',
2543
				'fallback_no_verify_ssl_certs',
2544
			)
2545
		);
2546
2547
		if ( $update_activated_state ) {
2548
			Jetpack_Options::update_option( 'activated', 4 );
2549
		}
2550
2551
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2552
			// Check then record unique disconnection if site has never been disconnected previously
2553
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2554
				$jetpack_unique_connection['disconnected'] = 1;
2555
			} else {
2556
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2557
					//track unique disconnect
2558
					$jetpack = Jetpack::init();
2559
2560
					$jetpack->stat( 'connections', 'unique-disconnect' );
2561
					$jetpack->do_stats( 'server_side' );
2562
				}
2563
				// increment number of times disconnected
2564
				$jetpack_unique_connection['disconnected'] += 1;
2565
			}
2566
2567
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2568
		}
2569
2570
		// Delete all the sync related data. Since it could be taking up space.
2571
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2572
		Jetpack_Sync_Sender::get_instance()->uninstall();
2573
2574
		// Disable the Heartbeat cron
2575
		Jetpack_Heartbeat::init()->deactivate();
2576
	}
2577
2578
	/**
2579
	 * Unlinks the current user from the linked WordPress.com user
2580
	 */
2581
	public static function unlink_user( $user_id = null ) {
2582
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2583
			return false;
2584
2585
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2586
2587
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2588
			return false;
2589
2590
		if ( ! isset( $tokens[ $user_id ] ) )
2591
			return false;
2592
2593
		Jetpack::load_xml_rpc_client();
2594
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2595
		$xml->query( 'jetpack.unlink_user', $user_id );
2596
2597
		unset( $tokens[ $user_id ] );
2598
2599
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2600
2601
		/**
2602
		 * Fires after the current user has been unlinked from WordPress.com.
2603
		 *
2604
		 * @since 4.1.0
2605
		 *
2606
		 * @param int $user_id The current user's ID.
2607
		 */
2608
		do_action( 'jetpack_unlinked_user', $user_id );
2609
2610
		return true;
2611
	}
2612
2613
	/**
2614
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2615
	 */
2616
	public static function try_registration() {
2617
		// Let's get some testing in beta versions and such.
2618
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2619
			// Before attempting to connect, let's make sure that the domains are viable.
2620
			$domains_to_check = array_unique( array(
2621
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2622
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2623
			) );
2624
			foreach ( $domains_to_check as $domain ) {
2625
				$result = Jetpack_Data::is_usable_domain( $domain );
2626
				if ( is_wp_error( $result ) ) {
2627
					return $result;
2628
				}
2629
			}
2630
		}
2631
2632
		$result = Jetpack::register();
2633
2634
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2635
		if ( ! $result || is_wp_error( $result ) ) {
2636
			return $result;
2637
		} else {
2638
			return true;
2639
		}
2640
	}
2641
2642
	/**
2643
	 * Tracking an internal event log. Try not to put too much chaff in here.
2644
	 *
2645
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2646
	 */
2647
	public static function log( $code, $data = null ) {
2648
		// only grab the latest 200 entries
2649
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2650
2651
		// Append our event to the log
2652
		$log_entry = array(
2653
			'time'    => time(),
2654
			'user_id' => get_current_user_id(),
2655
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2656
			'code'    => $code,
2657
		);
2658
		// Don't bother storing it unless we've got some.
2659
		if ( ! is_null( $data ) ) {
2660
			$log_entry['data'] = $data;
2661
		}
2662
		$log[] = $log_entry;
2663
2664
		// Try add_option first, to make sure it's not autoloaded.
2665
		// @todo: Add an add_option method to Jetpack_Options
2666
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2667
			Jetpack_Options::update_option( 'log', $log );
2668
		}
2669
2670
		/**
2671
		 * Fires when Jetpack logs an internal event.
2672
		 *
2673
		 * @since 3.0.0
2674
		 *
2675
		 * @param array $log_entry {
2676
		 *	Array of details about the log entry.
2677
		 *
2678
		 *	@param string time Time of the event.
2679
		 *	@param int user_id ID of the user who trigerred the event.
2680
		 *	@param int blog_id Jetpack Blog ID.
2681
		 *	@param string code Unique name for the event.
2682
		 *	@param string data Data about the event.
2683
		 * }
2684
		 */
2685
		do_action( 'jetpack_log_entry', $log_entry );
2686
	}
2687
2688
	/**
2689
	 * Get the internal event log.
2690
	 *
2691
	 * @param $event (string) - only return the specific log events
2692
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2693
	 *
2694
	 * @return array of log events || WP_Error for invalid params
2695
	 */
2696
	public static function get_log( $event = false, $num = false ) {
2697
		if ( $event && ! is_string( $event ) ) {
2698
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2699
		}
2700
2701
		if ( $num && ! is_numeric( $num ) ) {
2702
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2703
		}
2704
2705
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2706
2707
		// If nothing set - act as it did before, otherwise let's start customizing the output
2708
		if ( ! $num && ! $event ) {
2709
			return $entire_log;
2710
		} else {
2711
			$entire_log = array_reverse( $entire_log );
2712
		}
2713
2714
		$custom_log_output = array();
2715
2716
		if ( $event ) {
2717
			foreach ( $entire_log as $log_event ) {
2718
				if ( $event == $log_event[ 'code' ] ) {
2719
					$custom_log_output[] = $log_event;
2720
				}
2721
			}
2722
		} else {
2723
			$custom_log_output = $entire_log;
2724
		}
2725
2726
		if ( $num ) {
2727
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2728
		}
2729
2730
		return $custom_log_output;
2731
	}
2732
2733
	/**
2734
	 * Log modification of important settings.
2735
	 */
2736
	public static function log_settings_change( $option, $old_value, $value ) {
2737
		switch( $option ) {
2738
			case 'jetpack_sync_non_public_post_stati':
2739
				self::log( $option, $value );
2740
				break;
2741
		}
2742
	}
2743
2744
	/**
2745
	 * Return stat data for WPCOM sync
2746
	 */
2747
	public static function get_stat_data( $encode = true ) {
2748
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
2749
		$additional_data = self::get_additional_stat_data();
2750
2751
		$merged_data = array_merge( $heartbeat_data, $additional_data );
2752
2753
		if ( $encode ) {
2754
			return json_encode( $merged_data );
2755
		}
2756
2757
		return $merged_data;
2758
	}
2759
2760
	/**
2761
	 * Get additional stat data to sync to WPCOM
2762
	 */
2763
	public static function get_additional_stat_data( $prefix = '' ) {
2764
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
2765
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2766
		$return["{$prefix}users"]          = count_users();
2767
		$return["{$prefix}site-count"]     = 0;
2768
		if ( function_exists( 'get_blog_count' ) ) {
2769
			$return["{$prefix}site-count"] = get_blog_count();
2770
		}
2771
		return $return;
2772
	}
2773
2774
	/* Admin Pages */
2775
2776
	function admin_init() {
2777
		// If the plugin is not connected, display a connect message.
2778
		if (
2779
			// the plugin was auto-activated and needs its candy
2780
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2781
		||
2782
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2783
			! Jetpack_Options::get_option( 'activated' )
2784
		) {
2785
			Jetpack::plugin_initialize();
2786
		}
2787
2788
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2789
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2790
				// Show connect notice on dashboard and plugins pages
2791
				add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
2792
				add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
2793
			}
2794
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2795
			// Upgrade: 1.1 -> 1.1.1
2796
			// Check and see if host can verify the Jetpack servers' SSL certificate
2797
			$args = array();
2798
			Jetpack_Client::_wp_remote_request(
2799
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2800
				$args,
2801
				true
2802
			);
2803
		} else {
2804
			// Show the notice on the Dashboard only for now
2805
2806
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2807
		}
2808
2809
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2810
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2811
		}
2812
2813
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2814
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2815
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2816
2817
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2818
			// Artificially throw errors in certain whitelisted cases during plugin activation
2819
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2820
		}
2821
2822
		// Jetpack Manage Activation Screen from .com
2823
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2824
2825
		// Add custom column in wp-admin/users.php to show whether user is linked.
2826
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2827
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2828
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2829
	}
2830
2831
	function admin_body_class( $admin_body_class = '' ) {
2832
		$classes = explode( ' ', trim( $admin_body_class ) );
2833
2834
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2835
2836
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2837
		return " $admin_body_class ";
2838
	}
2839
2840
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2841
		return $admin_body_class . ' jetpack-pagestyles ';
2842
	}
2843
2844
	function prepare_connect_notice() {
2845
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2846
2847
		add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
2848
2849
		if ( Jetpack::state( 'network_nag' ) )
2850
			add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
2851
	}
2852
	/**
2853
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2854
	 *
2855
	 * @return null
2856
	 */
2857
	function prepare_manage_jetpack_notice() {
2858
2859
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2860
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2861
	}
2862
2863
	function manage_activate_screen() {
2864
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2865
	}
2866
	/**
2867
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2868
	 * This function artificially throws errors for such cases (whitelisted).
2869
	 *
2870
	 * @param string $plugin The activated plugin.
2871
	 */
2872
	function throw_error_on_activate_plugin( $plugin ) {
2873
		$active_modules = Jetpack::get_active_modules();
2874
2875
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2876
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2877
			$throw = false;
2878
2879
			// Try and make sure it really was the stats plugin
2880
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2881
				if ( 'stats.php' == basename( $plugin ) ) {
2882
					$throw = true;
2883
				}
2884
			} else {
2885
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2886
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2887
					$throw = true;
2888
				}
2889
			}
2890
2891
			if ( $throw ) {
2892
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2893
			}
2894
		}
2895
	}
2896
2897
	function intercept_plugin_error_scrape_init() {
2898
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2899
	}
2900
2901
	function intercept_plugin_error_scrape( $action, $result ) {
2902
		if ( ! $result ) {
2903
			return;
2904
		}
2905
2906
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2907
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2908
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2909
			}
2910
		}
2911
	}
2912
2913
	function add_remote_request_handlers() {
2914
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2915
	}
2916
2917
	function remote_request_handlers() {
2918
		switch ( current_filter() ) {
2919
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2920
			$response = $this->upload_handler();
2921
			break;
2922
		default :
2923
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2924
			break;
2925
		}
2926
2927
		if ( ! $response ) {
2928
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2929
		}
2930
2931
		if ( is_wp_error( $response ) ) {
2932
			$status_code       = $response->get_error_data();
2933
			$error             = $response->get_error_code();
2934
			$error_description = $response->get_error_message();
2935
2936
			if ( ! is_int( $status_code ) ) {
2937
				$status_code = 400;
2938
			}
2939
2940
			status_header( $status_code );
2941
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
2942
		}
2943
2944
		status_header( 200 );
2945
		if ( true === $response ) {
2946
			exit;
2947
		}
2948
2949
		die( json_encode( (object) $response ) );
2950
	}
2951
2952
	function upload_handler() {
2953
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
2954
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
2955
		}
2956
2957
		$user = wp_authenticate( '', '' );
2958
		if ( ! $user || is_wp_error( $user ) ) {
2959
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
2960
		}
2961
2962
		wp_set_current_user( $user->ID );
2963
2964
		if ( ! current_user_can( 'upload_files' ) ) {
2965
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
2966
		}
2967
2968
		if ( empty( $_FILES ) ) {
2969
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
2970
		}
2971
2972
		foreach ( array_keys( $_FILES ) as $files_key ) {
2973
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
2974
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
2975
			}
2976
		}
2977
2978
		$media_keys = array_keys( $_FILES['media'] );
2979
2980
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
2981
		if ( ! $token || is_wp_error( $token ) ) {
2982
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
2983
		}
2984
2985
		$uploaded_files = array();
2986
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
2987
		unset( $GLOBALS['post'] );
2988
		foreach ( $_FILES['media']['name'] as $index => $name ) {
2989
			$file = array();
2990
			foreach ( $media_keys as $media_key ) {
2991
				$file[$media_key] = $_FILES['media'][$media_key][$index];
2992
			}
2993
2994
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
2995
2996
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
2997
			if ( $hmac_provided !== $hmac_file ) {
2998
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
2999
				continue;
3000
			}
3001
3002
			$_FILES['.jetpack.upload.'] = $file;
3003
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3004
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3005
				$post_id = 0;
3006
			}
3007
			$attachment_id = media_handle_upload(
3008
				'.jetpack.upload.',
3009
				$post_id,
3010
				array(),
3011
				array(
3012
					'action' => 'jetpack_upload_file',
3013
				)
3014
			);
3015
3016
			if ( ! $attachment_id ) {
3017
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3018
			} elseif ( is_wp_error( $attachment_id ) ) {
3019
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3020
			} else {
3021
				$attachment = get_post( $attachment_id );
3022
				$uploaded_files[$index] = (object) array(
3023
					'id'   => (string) $attachment_id,
3024
					'file' => $attachment->post_title,
3025
					'url'  => wp_get_attachment_url( $attachment_id ),
3026
					'type' => $attachment->post_mime_type,
3027
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3028
				);
3029
			}
3030
		}
3031
		if ( ! is_null( $global_post ) ) {
3032
			$GLOBALS['post'] = $global_post;
3033
		}
3034
3035
		return $uploaded_files;
3036
	}
3037
3038
	/**
3039
	 * Add help to the Jetpack page
3040
	 *
3041
	 * @since Jetpack (1.2.3)
3042
	 * @return false if not the Jetpack page
3043
	 */
3044
	function admin_help() {
3045
		$current_screen = get_current_screen();
3046
3047
		// Overview
3048
		$current_screen->add_help_tab(
3049
			array(
3050
				'id'		=> 'home',
3051
				'title'		=> __( 'Home', 'jetpack' ),
3052
				'content'	=>
3053
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3054
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3055
					'<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>',
3056
			)
3057
		);
3058
3059
		// Screen Content
3060
		if ( current_user_can( 'manage_options' ) ) {
3061
			$current_screen->add_help_tab(
3062
				array(
3063
					'id'		=> 'settings',
3064
					'title'		=> __( 'Settings', 'jetpack' ),
3065
					'content'	=>
3066
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3067
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3068
						'<ol>' .
3069
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3070
							'<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>' .
3071
						'</ol>' .
3072
						'<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>'
3073
				)
3074
			);
3075
		}
3076
3077
		// Help Sidebar
3078
		$current_screen->set_help_sidebar(
3079
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3080
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3081
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3082
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3083
		);
3084
	}
3085
3086
	function admin_menu_css() {
3087
		wp_enqueue_style( 'jetpack-icons' );
3088
	}
3089
3090
	function admin_menu_order() {
3091
		return true;
3092
	}
3093
3094 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3095
		$jp_menu_order = array();
3096
3097
		foreach ( $menu_order as $index => $item ) {
3098
			if ( $item != 'jetpack' ) {
3099
				$jp_menu_order[] = $item;
3100
			}
3101
3102
			if ( $index == 0 ) {
3103
				$jp_menu_order[] = 'jetpack';
3104
			}
3105
		}
3106
3107
		return $jp_menu_order;
3108
	}
3109
3110
	function admin_head() {
3111 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3112
			/** This action is documented in class.jetpack-admin-page.php */
3113
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3114
	}
3115
3116 View Code Duplication
	function admin_banner_styles() {
3117
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3118
3119
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3120
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3121
		wp_style_add_data( 'jetpack', 'suffix', $min );
3122
	}
3123
3124
	function plugin_action_links( $actions ) {
3125
3126
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3127
3128
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3129
			return array_merge(
3130
				$jetpack_home,
3131
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
3132
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3133
				$actions
3134
				);
3135
			}
3136
3137
		return array_merge( $jetpack_home, $actions );
3138
	}
3139
3140
	function admin_connect_notice() {
3141
		// Don't show the connect notice anywhere but the plugins.php after activating
3142
		$current = get_current_screen();
3143
		if ( 'plugins' !== $current->parent_base )
3144
			return;
3145
3146
		if ( ! current_user_can( 'jetpack_connect' ) )
3147
			return;
3148
3149
		$dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
3150
		?>
3151
		<div id="message" class="updated jp-banner">
3152
			<a href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3153
			<?php if ( in_array( Jetpack_Options::get_option( 'activated' ) , array( 1, 2, 3 ) ) ) : ?>
3154
					<div class="jp-banner__description-container">
3155
						<h2 class="jp-banner__header"><?php _e( 'Your Jetpack is almost ready!', 'jetpack' ); ?></h2>
3156
						<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>
3157
						<p class="jp-banner__button-container">
3158
							<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>
3159
							<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>
3160
						</p>
3161
					</div>
3162
			<?php else : ?>
3163
				<div class="jp-banner__content">
3164
					<h2><?php _e( 'Jetpack is installed!', 'jetpack' ) ?></h2>
3165
					<p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
3166
				</div>
3167
				<div class="jp-banner__action-container">
3168
					<a href="<?php echo Jetpack::admin_url() ?>" class="jp-banner__button" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a>
3169
				</div>
3170
			<?php endif; ?>
3171
		</div>
3172
3173
		<?php
3174
	}
3175
3176
	/**
3177
	 * This is the first banner
3178
	 * It should be visible only to user that can update the option
3179
	 * Are not connected
3180
	 *
3181
	 * @return null
3182
	 */
3183
	function admin_jetpack_manage_notice() {
3184
		$screen = get_current_screen();
3185
3186
		// Don't show the connect notice on the jetpack settings page.
3187
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3188
			return;
3189
3190
		// Only show it if don't have the managment option set.
3191
		// And not dismissed it already.
3192
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3193
			return;
3194
		}
3195
3196
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3197
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3198
		/**
3199
		 * I think it would be great to have different wordsing depending on where you are
3200
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3201
		 * etc..
3202
		 */
3203
3204
		?>
3205
		<div id="message" class="updated jp-banner">
3206
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3207
				<div class="jp-banner__description-container">
3208
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3209
					<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>
3210
					<p class="jp-banner__button-container">
3211
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3212
						<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>
3213
					</p>
3214
				</div>
3215
		</div>
3216
		<?php
3217
	}
3218
3219
	/**
3220
	 * Returns the url that the user clicks to remove the notice for the big banner
3221
	 * @return (string)
3222
	 */
3223
	function opt_out_jetpack_manage_url() {
3224
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3225
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3226
	}
3227
	/**
3228
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3229
	 * @return (string)
3230
	 */
3231
	function opt_in_jetpack_manage_url() {
3232
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3233
	}
3234
3235
	function opt_in_jetpack_manage_notice() {
3236
		?>
3237
		<div class="wrap">
3238
			<div id="message" class="jetpack-message is-opt-in">
3239
				<?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' ); ?>
3240
			</div>
3241
		</div>
3242
		<?php
3243
3244
	}
3245
	/**
3246
	 * Determines whether to show the notice of not true = display notice
3247
	 * @return (bool)
3248
	 */
3249
	function can_display_jetpack_manage_notice() {
3250
		// never display the notice to users that can't do anything about it anyways
3251
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3252
			return false;
3253
3254
		// don't display if we are in development more
3255
		if( Jetpack::is_development_mode() ) {
3256
			return false;
3257
		}
3258
		// don't display if the site is private
3259
		if(  ! Jetpack_Options::get_option( 'public' ) )
3260
			return false;
3261
3262
		/**
3263
		 * Should the Jetpack Remote Site Management notice be displayed.
3264
		 *
3265
		 * @since 3.3.0
3266
		 *
3267
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3268
		 */
3269
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3270
	}
3271
3272
	function network_connect_notice() {
3273
		?>
3274
		<div id="message" class="updated jetpack-message">
3275
			<div class="squeezer">
3276
				<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>
3277
			</div>
3278
		</div>
3279
		<?php
3280
	}
3281
3282
	/*
3283
	 * Registration flow:
3284
	 * 1 - ::admin_page_load() action=register
3285
	 * 2 - ::try_registration()
3286
	 * 3 - ::register()
3287
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3288
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3289
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3290
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3291
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3292
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3293
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3294
	 *       jetpack_id, jetpack_secret, jetpack_public
3295
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3296
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3297
	 * 5 - user logs in with WP.com account
3298
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3299
	 *		- Jetpack_Client_Server::authorize()
3300
	 *		- Jetpack_Client_Server::get_token()
3301
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3302
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3303
	 *			- which responds with access_token, token_type, scope
3304
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3305
	 *		- Jetpack::activate_default_modules()
3306
	 *     		- Deactivates deprecated plugins
3307
	 *     		- Activates all default modules
3308
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3309
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3310
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3311
	 *     Done!
3312
	 */
3313
3314
	/**
3315
	 * Handles the page load events for the Jetpack admin page
3316
	 */
3317
	function admin_page_load() {
3318
		$error = false;
3319
3320
		// Make sure we have the right body class to hook stylings for subpages off of.
3321
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3322
3323
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3324
			// Should only be used in intermediate redirects to preserve state across redirects
3325
			Jetpack::restate();
3326
		}
3327
3328
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3329
			// User clicked in the iframe to link their accounts
3330
			if ( ! Jetpack::is_user_connected() ) {
3331
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3332
				if ( isset( $_GET['notes_iframe'] ) )
3333
					$connect_url .= '&notes_iframe';
3334
				wp_redirect( $connect_url );
3335
				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...
3336
			} else {
3337
				if ( ! isset( $_GET['calypso_env'] ) ) {
3338
					Jetpack::state( 'message', 'already_authorized' );
3339
					wp_safe_redirect( Jetpack::admin_url() );
3340
				} else {
3341
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3342
					$connect_url .= '&already_authorized=true';
3343
					wp_redirect( $connect_url );
3344
				}
3345
			}
3346
		}
3347
3348
3349
		if ( isset( $_GET['action'] ) ) {
3350
			switch ( $_GET['action'] ) {
3351
			case 'authorize':
3352
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3353
					Jetpack::state( 'message', 'already_authorized' );
3354
					wp_safe_redirect( Jetpack::admin_url() );
3355
					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...
3356
				}
3357
				Jetpack::log( 'authorize' );
3358
				$client_server = new Jetpack_Client_Server;
3359
				$client_server->client_authorize();
3360
				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...
3361
			case 'register' :
3362
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3363
					$error = 'cheatin';
3364
					break;
3365
				}
3366
				check_admin_referer( 'jetpack-register' );
3367
				Jetpack::log( 'register' );
3368
				Jetpack::maybe_set_version_option();
3369
				$registered = Jetpack::try_registration();
3370
				if ( is_wp_error( $registered ) ) {
3371
					$error = $registered->get_error_code();
3372
					Jetpack::state( 'error', $error );
3373
					Jetpack::state( 'error', $registered->get_error_message() );
3374
					break;
3375
				}
3376
3377
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3378
3379
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3380
				exit;
3381
			case 'activate' :
3382
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3383
					$error = 'cheatin';
3384
					break;
3385
				}
3386
3387
				$module = stripslashes( $_GET['module'] );
3388
				check_admin_referer( "jetpack_activate-$module" );
3389
				Jetpack::log( 'activate', $module );
3390
				Jetpack::activate_module( $module );
3391
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3392
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3393
				exit;
3394
			case 'activate_default_modules' :
3395
				check_admin_referer( 'activate_default_modules' );
3396
				Jetpack::log( 'activate_default_modules' );
3397
				Jetpack::restate();
3398
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3399
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3400
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3401
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3402
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3403
				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...
3404
			case 'disconnect' :
3405
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3406
					$error = 'cheatin';
3407
					break;
3408
				}
3409
3410
				check_admin_referer( 'jetpack-disconnect' );
3411
				Jetpack::log( 'disconnect' );
3412
				Jetpack::disconnect();
3413
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3414
				exit;
3415
			case 'reconnect' :
3416
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3417
					$error = 'cheatin';
3418
					break;
3419
				}
3420
3421
				check_admin_referer( 'jetpack-reconnect' );
3422
				Jetpack::log( 'reconnect' );
3423
				$this->disconnect();
3424
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3425
				exit;
3426 View Code Duplication
			case 'deactivate' :
3427
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3428
					$error = 'cheatin';
3429
					break;
3430
				}
3431
3432
				$modules = stripslashes( $_GET['module'] );
3433
				check_admin_referer( "jetpack_deactivate-$modules" );
3434
				foreach ( explode( ',', $modules ) as $module ) {
3435
					Jetpack::log( 'deactivate', $module );
3436
					Jetpack::deactivate_module( $module );
3437
					Jetpack::state( 'message', 'module_deactivated' );
3438
				}
3439
				Jetpack::state( 'module', $modules );
3440
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3441
				exit;
3442
			case 'unlink' :
3443
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3444
				check_admin_referer( 'jetpack-unlink' );
3445
				Jetpack::log( 'unlink' );
3446
				$this->unlink_user();
3447
				Jetpack::state( 'message', 'unlinked' );
3448
				if ( 'sub-unlink' == $redirect ) {
3449
					wp_safe_redirect( admin_url() );
3450
				} else {
3451
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3452
				}
3453
				exit;
3454
			default:
3455
				/**
3456
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3457
				 *
3458
				 * @since 2.6.0
3459
				 *
3460
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3461
				 */
3462
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3463
			}
3464
		}
3465
3466
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3467
			self::activate_new_modules( true );
3468
		}
3469
3470
		$message_code = Jetpack::state( 'message' );
3471
		if ( Jetpack::state( 'optin-manage' ) ) {
3472
			$activated_manage = $message_code;
3473
			$message_code = 'jetpack-manage';
3474
		}
3475
3476
		switch ( $message_code ) {
3477
		case 'jetpack-manage':
3478
			$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>';
3479
			if ( $activated_manage ) {
3480
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3481
			}
3482
			break;
3483
3484
		}
3485
3486
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3487
3488
		if ( ! empty( $deactivated_plugins ) ) {
3489
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3490
			$deactivated_titles  = array();
3491
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3492
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3493
					continue;
3494
				}
3495
3496
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3497
			}
3498
3499
			if ( $deactivated_titles ) {
3500
				if ( $this->message ) {
3501
					$this->message .= "<br /><br />\n";
3502
				}
3503
3504
				$this->message .= wp_sprintf(
3505
					_n(
3506
						'Jetpack contains the most recent version of the old %l plugin.',
3507
						'Jetpack contains the most recent versions of the old %l plugins.',
3508
						count( $deactivated_titles ),
3509
						'jetpack'
3510
					),
3511
					$deactivated_titles
3512
				);
3513
3514
				$this->message .= "<br />\n";
3515
3516
				$this->message .= _n(
3517
					'The old version has been deactivated and can be removed from your site.',
3518
					'The old versions have been deactivated and can be removed from your site.',
3519
					count( $deactivated_titles ),
3520
					'jetpack'
3521
				);
3522
			}
3523
		}
3524
3525
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3526
3527
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3528
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3529
		}
3530
3531 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3532
			/**
3533
			 * Fires when a module configuration page is loaded.
3534
			 * The dynamic part of the hook is the configure parameter from the URL.
3535
			 *
3536
			 * @since 1.1.0
3537
			 */
3538
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3539
		}
3540
3541
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3542
	}
3543
3544
	function admin_notices() {
3545
3546
		if ( $this->error ) {
3547
?>
3548
<div id="message" class="jetpack-message jetpack-err">
3549
	<div class="squeezer">
3550
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3551
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3552
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3553
<?php	endif; ?>
3554
	</div>
3555
</div>
3556
<?php
3557
		}
3558
3559
		if ( $this->message ) {
3560
?>
3561
<div id="message" class="jetpack-message">
3562
	<div class="squeezer">
3563
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3564
	</div>
3565
</div>
3566
<?php
3567
		}
3568
3569
		if ( $this->privacy_checks ) :
3570
			$module_names = $module_slugs = array();
3571
3572
			$privacy_checks = explode( ',', $this->privacy_checks );
3573
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3574
			foreach ( $privacy_checks as $module_slug ) {
3575
				$module = Jetpack::get_module( $module_slug );
3576
				if ( ! $module ) {
3577
					continue;
3578
				}
3579
3580
				$module_slugs[] = $module_slug;
3581
				$module_names[] = "<strong>{$module['name']}</strong>";
3582
			}
3583
3584
			$module_slugs = join( ',', $module_slugs );
3585
?>
3586
<div id="message" class="jetpack-message jetpack-err">
3587
	<div class="squeezer">
3588
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3589
		<p><?php
3590
			echo wp_kses(
3591
				wptexturize(
3592
					wp_sprintf(
3593
						_nx(
3594
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3595
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3596
							count( $privacy_checks ),
3597
							'%l = list of Jetpack module/feature names',
3598
							'jetpack'
3599
						),
3600
						$module_names
3601
					)
3602
				),
3603
				array( 'strong' => true )
3604
			);
3605
3606
			echo "\n<br />\n";
3607
3608
			echo wp_kses(
3609
				sprintf(
3610
					_nx(
3611
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3612
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3613
						count( $privacy_checks ),
3614
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3615
						'jetpack'
3616
					),
3617
					wp_nonce_url(
3618
						Jetpack::admin_url(
3619
							array(
3620
								'page'   => 'jetpack',
3621
								'action' => 'deactivate',
3622
								'module' => urlencode( $module_slugs ),
3623
							)
3624
						),
3625
						"jetpack_deactivate-$module_slugs"
3626
					),
3627
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3628
				),
3629
				array( 'a' => array( 'href' => true, 'title' => true ) )
3630
			);
3631
		?></p>
3632
	</div>
3633
</div>
3634
<?php endif;
3635
	// only display the notice if the other stuff is not there
3636
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3637
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3638
			$this->opt_in_jetpack_manage_notice();
3639
		}
3640
	}
3641
3642
	/**
3643
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3644
	 */
3645
	function stat( $group, $detail ) {
3646
		if ( ! isset( $this->stats[ $group ] ) )
3647
			$this->stats[ $group ] = array();
3648
		$this->stats[ $group ][] = $detail;
3649
	}
3650
3651
	/**
3652
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3653
	 */
3654
	function do_stats( $method = '' ) {
3655
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3656
			foreach ( $this->stats as $group => $stats ) {
3657
				if ( is_array( $stats ) && count( $stats ) ) {
3658
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3659
					if ( 'server_side' === $method ) {
3660
						self::do_server_side_stat( $args );
3661
					} else {
3662
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3663
					}
3664
				}
3665
				unset( $this->stats[ $group ] );
3666
			}
3667
		}
3668
	}
3669
3670
	/**
3671
	 * Runs stats code for a one-off, server-side.
3672
	 *
3673
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3674
	 *
3675
	 * @return bool If it worked.
3676
	 */
3677
	static function do_server_side_stat( $args ) {
3678
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3679
		if ( is_wp_error( $response ) )
3680
			return false;
3681
3682
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3683
			return false;
3684
3685
		return true;
3686
	}
3687
3688
	/**
3689
	 * Builds the stats url.
3690
	 *
3691
	 * @param $args array|string The arguments to append to the URL.
3692
	 *
3693
	 * @return string The URL to be pinged.
3694
	 */
3695
	static function build_stats_url( $args ) {
3696
		$defaults = array(
3697
			'v'    => 'wpcom2',
3698
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
3699
		);
3700
		$args     = wp_parse_args( $args, $defaults );
3701
		/**
3702
		 * Filter the URL used as the Stats tracking pixel.
3703
		 *
3704
		 * @since 2.3.2
3705
		 *
3706
		 * @param string $url Base URL used as the Stats tracking pixel.
3707
		 */
3708
		$base_url = apply_filters(
3709
			'jetpack_stats_base_url',
3710
			'https://pixel.wp.com/g.gif'
3711
		);
3712
		$url      = add_query_arg( $args, $base_url );
3713
		return $url;
3714
	}
3715
3716
	static function translate_current_user_to_role() {
3717
		foreach ( self::$capability_translations as $role => $cap ) {
3718
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
3719
				return $role;
3720
			}
3721
		}
3722
3723
		return false;
3724
	}
3725
3726
	static function translate_role_to_cap( $role ) {
3727
		if ( ! isset( self::$capability_translations[$role] ) ) {
3728
			return false;
3729
		}
3730
3731
		return self::$capability_translations[$role];
3732
	}
3733
3734
	static function sign_role( $role ) {
3735
		if ( ! $user_id = (int) get_current_user_id() ) {
3736
			return false;
3737
		}
3738
3739
		$token = Jetpack_Data::get_access_token();
3740
		if ( ! $token || is_wp_error( $token ) ) {
3741
			return false;
3742
		}
3743
3744
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
3745
	}
3746
3747
3748
	/**
3749
	 * Builds a URL to the Jetpack connection auth page
3750
	 *
3751
	 * @since 3.9.5
3752
	 *
3753
	 * @param bool $raw If true, URL will not be escaped.
3754
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
3755
	 *                              If string, will be a custom redirect.
3756
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
3757
	 *
3758
	 * @return string Connect URL
3759
	 */
3760
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
3761
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
3762
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
3763
			if( is_network_admin() ) {
3764
			    $url = add_query_arg( 'is_multisite', network_admin_url(
3765
			    'admin.php?page=jetpack-settings' ), $url );
3766
			}
3767
		} else {
3768
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
3769
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
3770
			}
3771
3772
			$role = self::translate_current_user_to_role();
3773
			$signed_role = self::sign_role( $role );
3774
3775
			$user = wp_get_current_user();
3776
3777
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
3778
			$redirect = $redirect
3779
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
3780
				: $jetpack_admin_page;
3781
3782
			if( isset( $_REQUEST['is_multisite'] ) ) {
3783
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
3784
			}
3785
3786
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
3787
			@list( $secret ) = explode( ':', $secrets );
3788
3789
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
3790
				? get_site_icon_url()
3791
				: false;
3792
3793
			$args = urlencode_deep(
3794
				array(
3795
					'response_type' => 'code',
3796
					'client_id'     => Jetpack_Options::get_option( 'id' ),
3797
					'redirect_uri'  => add_query_arg(
3798
						array(
3799
							'action'   => 'authorize',
3800
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
3801
							'redirect' => urlencode( $redirect ),
3802
						),
3803
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
3804
					),
3805
					'state'         => $user->ID,
3806
					'scope'         => $signed_role,
3807
					'user_email'    => $user->user_email,
3808
					'user_login'    => $user->user_login,
3809
					'is_active'     => Jetpack::is_active(),
3810
					'jp_version'    => JETPACK__VERSION,
3811
					'auth_type'     => 'calypso',
3812
					'secret'        => $secret,
3813
					'locale'        => isset( $gp_locale->slug ) ? $gp_locale->slug : '',
3814
					'blogname'      => get_option( 'blogname' ),
3815
					'site_url'      => site_url(),
3816
					'home_url'      => home_url(),
3817
					'site_icon'     => $site_icon,
3818
				)
3819
			);
3820
3821
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
3822
		}
3823
3824
		if ( $from ) {
3825
			$url = add_query_arg( 'from', $from, $url );
3826
		}
3827
3828
		if ( isset( $_GET['calypso_env'] ) ) {
3829
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
3830
		}
3831
3832
		return $raw ? $url : esc_url( $url );
3833
	}
3834
3835
	function build_reconnect_url( $raw = false ) {
3836
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
3837
		return $raw ? $url : esc_url( $url );
3838
	}
3839
3840
	public static function admin_url( $args = null ) {
3841
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
3842
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
3843
		return $url;
3844
	}
3845
3846
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
3847
		$actionurl = str_replace( '&amp;', '&', $actionurl );
3848
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
3849
	}
3850
3851
	function dismiss_jetpack_notice() {
3852
3853
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
3854
			return;
3855
		}
3856
3857
		switch( $_GET['jetpack-notice'] ) {
3858
			case 'dismiss':
3859
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
3860
3861
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
3862
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
3863
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
3864
				}
3865
				break;
3866 View Code Duplication
			case 'jetpack-manage-opt-out':
3867
3868
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
3869
					// Don't show the banner again
3870
3871
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
3872
					// redirect back to the page that had the notice
3873
					if ( wp_get_referer() ) {
3874
						wp_safe_redirect( wp_get_referer() );
3875
					} else {
3876
						// Take me to Jetpack
3877
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3878
					}
3879
				}
3880
				break;
3881 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
3882
3883
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
3884
					// Don't show the banner again
3885
3886
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
3887
					// redirect back to the page that had the notice
3888
					if ( wp_get_referer() ) {
3889
						wp_safe_redirect( wp_get_referer() );
3890
					} else {
3891
						// Take me to Jetpack
3892
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
3893
					}
3894
				}
3895
				break;
3896
			case 'jetpack-manage-opt-in':
3897
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
3898
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
3899
3900
					$redirection_url = Jetpack::admin_url();
3901
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3902
3903
					// Don't redirect form the Jetpack Setting Page
3904
					$referer_parsed = parse_url ( wp_get_referer() );
3905
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
3906
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
3907
						// Take the user to Jetpack home except when on the setting page
3908
						$redirection_url = wp_get_referer();
3909
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
3910
					}
3911
					// Also update the JSON API FULL MANAGEMENT Option
3912
					Jetpack::activate_module( 'manage', false, false );
3913
3914
					// Special Message when option in.
3915
					Jetpack::state( 'optin-manage', 'true' );
3916
					// Activate the Module if not activated already
3917
3918
					// Redirect properly
3919
					wp_safe_redirect( $redirection_url );
3920
3921
				}
3922
				break;
3923
		}
3924
	}
3925
3926
	function debugger_page() {
3927
		nocache_headers();
3928
		if ( ! current_user_can( 'manage_options' ) ) {
3929
			die( '-1' );
3930
		}
3931
		Jetpack_Debugger::jetpack_debug_display_handler();
3932
		exit;
3933
	}
3934
3935
	public static function admin_screen_configure_module( $module_id ) {
3936
3937
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
3938
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
3939
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
3940
				/**
3941
				 * Fires to diplay a custom module activation screen.
3942
				 *
3943
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
3944
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3945
				 *
3946
				 * @module manage
3947
				 *
3948
				 * @since 3.8.0
3949
				 *
3950
				 * @param int $module_id Module ID.
3951
				 */
3952
				do_action( 'display_activate_module_setting_' . $module_id );
3953
			} else {
3954
				self::display_activate_module_link( $module_id );
3955
			}
3956
3957
			return false;
3958
		} ?>
3959
3960
		<div id="jp-settings-screen" style="position: relative">
3961
			<h3>
3962
			<?php
3963
				$module = Jetpack::get_module( $module_id );
3964
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
3965
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
3966
			?>
3967
			</h3>
3968
			<?php
3969
				/**
3970
				 * Fires within the displayed message when a feature configuation is updated.
3971
				 *
3972
				 * @since 3.4.0
3973
				 *
3974
				 * @param int $module_id Module ID.
3975
				 */
3976
				do_action( 'jetpack_notices_update_settings', $module_id );
3977
				/**
3978
				 * Fires when a feature configuation screen is loaded.
3979
				 * The dynamic part of the hook, $module_id, is the module ID.
3980
				 *
3981
				 * @since 1.1.0
3982
				 */
3983
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
3984
			?>
3985
		</div><?php
3986
	}
3987
3988
	/**
3989
	 * Display link to activate the module to see the settings screen.
3990
	 * @param  string $module_id
3991
	 * @return null
3992
	 */
3993
	public static function display_activate_module_link( $module_id ) {
3994
3995
		$info =  Jetpack::get_module( $module_id );
3996
		$extra = '';
3997
		$activate_url = wp_nonce_url(
3998
				Jetpack::admin_url(
3999
					array(
4000
						'page'   => 'jetpack',
4001
						'action' => 'activate',
4002
						'module' => $module_id,
4003
					)
4004
				),
4005
				"jetpack_activate-$module_id"
4006
			);
4007
4008
		?>
4009
4010
		<div class="wrap configure-module">
4011
			<div id="jp-settings-screen">
4012
				<?php
4013
				if ( $module_id == 'json-api' ) {
4014
4015
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4016
4017
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4018
4019
					$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' );
4020
4021
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4022
				} ?>
4023
4024
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4025
				<div class="narrow">
4026
					<p><?php echo  $info['description']; ?></p>
4027
					<?php if( $extra ) { ?>
4028
					<p><?php echo esc_html( $extra ); ?></p>
4029
					<?php } ?>
4030
					<p>
4031
						<?php
4032
						if( wp_get_referer() ) {
4033
							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() );
4034
						} else {
4035
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4036
						} ?>
4037
					</p>
4038
				</div>
4039
4040
			</div>
4041
		</div>
4042
4043
		<?php
4044
	}
4045
4046
	public static function sort_modules( $a, $b ) {
4047
		if ( $a['sort'] == $b['sort'] )
4048
			return 0;
4049
4050
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4051
	}
4052
4053
	function ajax_recheck_ssl() {
4054
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4055
		$result = Jetpack::permit_ssl( true );
4056
		wp_send_json( array(
4057
			'enabled' => $result,
4058
			'message' => get_transient( 'jetpack_https_test_message' )
4059
		) );
4060
	}
4061
4062
/* Client API */
4063
4064
	/**
4065
	 * Returns the requested Jetpack API URL
4066
	 *
4067
	 * @return string
4068
	 */
4069
	public static function api_url( $relative_url ) {
4070
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4071
	}
4072
4073
	/**
4074
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4075
	 */
4076
	public static function fix_url_for_bad_hosts( $url ) {
4077
		if ( 0 !== strpos( $url, 'https://' ) ) {
4078
			return $url;
4079
		}
4080
4081
		switch ( JETPACK_CLIENT__HTTPS ) {
4082
			case 'ALWAYS' :
4083
				return $url;
4084
			case 'NEVER' :
4085
				return set_url_scheme( $url, 'http' );
4086
			// default : case 'AUTO' :
4087
		}
4088
4089
		// we now return the unmodified SSL URL by default, as a security precaution
4090
		return $url;
4091
	}
4092
4093
	/**
4094
	 * Checks to see if the URL is using SSL to connect with Jetpack
4095
	 *
4096
	 * @since 2.3.3
4097
	 * @return boolean
4098
	 */
4099
	public static function permit_ssl( $force_recheck = false ) {
4100
		// Do some fancy tests to see if ssl is being supported
4101
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4102
			$message = '';
4103
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4104
				$ssl = 0;
4105
			} else {
4106
				switch ( JETPACK_CLIENT__HTTPS ) {
4107
					case 'NEVER':
4108
						$ssl = 0;
4109
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4110
						break;
4111
					case 'ALWAYS':
4112
					case 'AUTO':
4113
					default:
4114
						$ssl = 1;
4115
						break;
4116
				}
4117
4118
				// If it's not 'NEVER', test to see
4119
				if ( $ssl ) {
4120
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4121
						$ssl = 0;
4122
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4123
					} else {
4124
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4125
						if ( is_wp_error( $response ) ) {
4126
							$ssl = 0;
4127
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4128
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4129
							$ssl = 0;
4130
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4131
						}
4132
					}
4133
				}
4134
			}
4135
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4136
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4137
		}
4138
4139
		return (bool) $ssl;
4140
	}
4141
4142
	/*
4143
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4144
	 */
4145
	public function alert_auto_ssl_fail() {
4146
		if ( ! current_user_can( 'manage_options' ) )
4147
			return;
4148
4149
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4150
		?>
4151
4152
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4153
			<div class="jp-banner__content">
4154
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4155
				<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>
4156
				<p>
4157
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4158
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4159
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4160
				</p>
4161
				<p>
4162
					<?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' ),
4163
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4164
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4165
				</p>
4166
			</div>
4167
		</div>
4168
		<style>
4169
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4170
		</style>
4171
		<script type="text/javascript">
4172
			jQuery( document ).ready( function( $ ) {
4173
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4174
					var $this = $( this );
4175
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4176
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4177
					e.preventDefault();
4178
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4179
					$.post( ajaxurl, data )
4180
					  .done( function( response ) {
4181
					  	if ( response.enabled ) {
4182
					  		$( '#jetpack-ssl-warning' ).hide();
4183
					  	} else {
4184
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4185
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4186
					  	}
4187
					  }.bind( $this ) );
4188
				} );
4189
			} );
4190
		</script>
4191
4192
		<?php
4193
	}
4194
4195
	/**
4196
	 * Returns the Jetpack XML-RPC API
4197
	 *
4198
	 * @return string
4199
	 */
4200
	public static function xmlrpc_api_url() {
4201
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4202
		return untrailingslashit( $base ) . '/xmlrpc.php';
4203
	}
4204
4205
	/**
4206
	 * Creates two secret tokens and the end of life timestamp for them.
4207
	 *
4208
	 * Note these tokens are unique per call, NOT static per site for connecting.
4209
	 *
4210
	 * @since 2.6
4211
	 * @return array
4212
	 */
4213
	public function generate_secrets( $action, $exp = 600 ) {
4214
	    $secret = wp_generate_password( 32, false ) // secret_1
4215
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4216
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4217
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4218
		Jetpack_Options::update_option( $action, $secret );
4219
	    return Jetpack_Options::get_option( $action );
4220
	}
4221
4222
	/**
4223
	 * Builds the timeout limit for queries talking with the wpcom servers.
4224
	 *
4225
	 * Based on local php max_execution_time in php.ini
4226
	 *
4227
	 * @since 2.6
4228
	 * @return int
4229
	 **/
4230
	public function get_remote_query_timeout_limit() {
4231
	    $timeout = (int) ini_get( 'max_execution_time' );
4232
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4233
		$timeout = 30;
4234
	    return intval( $timeout / 2 );
4235
	}
4236
4237
4238
	/**
4239
	 * Takes the response from the Jetpack register new site endpoint and
4240
	 * verifies it worked properly.
4241
	 *
4242
	 * @since 2.6
4243
	 * @return true or Jetpack_Error
4244
	 **/
4245
	public function validate_remote_register_response( $response ) {
4246
	    	if ( is_wp_error( $response ) ) {
4247
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4248
		}
4249
4250
		$code   = wp_remote_retrieve_response_code( $response );
4251
		$entity = wp_remote_retrieve_body( $response );
4252
		if ( $entity )
4253
			$json = json_decode( $entity );
4254
		else
4255
			$json = false;
4256
4257
		$code_type = intval( $code / 100 );
4258
		if ( 5 == $code_type ) {
4259
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4260
		} elseif ( 408 == $code ) {
4261
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4262
		} elseif ( ! empty( $json->error ) ) {
4263
			$error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
4264
			return new Jetpack_Error( (string) $json->error, $error_description, $code );
4265
		} elseif ( 200 != $code ) {
4266
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4267
		}
4268
4269
		// Jetpack ID error block
4270
		if ( empty( $json->jetpack_id ) ) {
4271
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4272
		} elseif ( ! is_scalar( $json->jetpack_id ) ) {
4273
			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 );
4274
		} elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
4275
			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 );
4276
		}
4277
4278
	    return true;
4279
	}
4280
	/**
4281
	 * @return bool|WP_Error
4282
	 */
4283
	public static function register() {
4284
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4285
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4286
4287
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
4288 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4289
			return new Jetpack_Error( 'missing_secrets' );
4290
		}
4291
4292
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4293
4294
		$gmt_offset = get_option( 'gmt_offset' );
4295
		if ( ! $gmt_offset ) {
4296
			$gmt_offset = 0;
4297
		}
4298
4299
		$stats_options = get_option( 'stats_options' );
4300
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4301
4302
		$args = array(
4303
			'method'  => 'POST',
4304
			'body'    => array(
4305
				'siteurl'         => site_url(),
4306
				'home'            => home_url(),
4307
				'gmt_offset'      => $gmt_offset,
4308
				'timezone_string' => (string) get_option( 'timezone_string' ),
4309
				'site_name'       => (string) get_option( 'blogname' ),
4310
				'secret_1'        => $secret_1,
4311
				'secret_2'        => $secret_2,
4312
				'site_lang'       => get_locale(),
4313
				'timeout'         => $timeout,
4314
				'stats_id'        => $stats_id,
4315
				'state'           => get_current_user_id(),
4316
			),
4317
			'headers' => array(
4318
				'Accept' => 'application/json',
4319
			),
4320
			'timeout' => $timeout,
4321
		);
4322
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4323
4324
4325
		// Make sure the response is valid and does not contain any Jetpack errors
4326
		$valid_response = Jetpack::init()->validate_remote_register_response( $response );
4327
		if( is_wp_error( $valid_response ) || !$valid_response ) {
4328
		    return $valid_response;
4329
		}
4330
4331
		// Grab the response values to work with
4332
		$code   = wp_remote_retrieve_response_code( $response );
4333
		$entity = wp_remote_retrieve_body( $response );
4334
4335
		if ( $entity )
4336
			$json = json_decode( $entity );
4337
		else
4338
			$json = false;
4339
4340 View Code Duplication
		if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
4341
			return new Jetpack_Error( 'jetpack_secret', '', $code );
4342
4343
		if ( isset( $json->jetpack_public ) ) {
4344
			$jetpack_public = (int) $json->jetpack_public;
4345
		} else {
4346
			$jetpack_public = false;
4347
		}
4348
4349
		Jetpack_Options::update_options(
4350
			array(
4351
				'id'         => (int)    $json->jetpack_id,
4352
				'blog_token' => (string) $json->jetpack_secret,
4353
				'public'     => $jetpack_public,
4354
			)
4355
		);
4356
4357
		/**
4358
		 * Fires when a site is registered on WordPress.com.
4359
		 *
4360
		 * @since 3.7.0
4361
		 *
4362
		 * @param int $json->jetpack_id Jetpack Blog ID.
4363
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4364
		 * @param int|bool $jetpack_public Is the site public.
4365
		 */
4366
		do_action( 'jetpack_site_registered', $json->jetpack_id, $json->jetpack_secret, $jetpack_public );
4367
4368
		// Initialize Jump Start for the first and only time.
4369
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4370
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4371
4372
			$jetpack = Jetpack::init();
4373
4374
			$jetpack->stat( 'jumpstart', 'unique-views' );
4375
			$jetpack->do_stats( 'server_side' );
4376
		};
4377
4378
		return true;
4379
	}
4380
4381
	/**
4382
	 * If the db version is showing something other that what we've got now, bump it to current.
4383
	 *
4384
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4385
	 */
4386
	public static function maybe_set_version_option() {
4387
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4388
		if ( JETPACK__VERSION != $version ) {
4389
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4390
4391
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4392
				/** This action is documented in class.jetpack.php */
4393
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4394
			}
4395
4396
			return true;
4397
		}
4398
		return false;
4399
	}
4400
4401
/* Client Server API */
4402
4403
	/**
4404
	 * Loads the Jetpack XML-RPC client
4405
	 */
4406
	public static function load_xml_rpc_client() {
4407
		require_once ABSPATH . WPINC . '/class-IXR.php';
4408
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4409
	}
4410
4411
	function verify_xml_rpc_signature() {
4412
		if ( $this->xmlrpc_verification ) {
4413
			return $this->xmlrpc_verification;
4414
		}
4415
4416
		// It's not for us
4417
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4418
			return false;
4419
		}
4420
4421
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
4422
		if (
4423
			empty( $token_key )
4424
		||
4425
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4426
		) {
4427
			return false;
4428
		}
4429
4430
		if ( '0' === $user_id ) {
4431
			$token_type = 'blog';
4432
			$user_id = 0;
4433
		} else {
4434
			$token_type = 'user';
4435
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4436
				return false;
4437
			}
4438
			$user_id = (int) $user_id;
4439
4440
			$user = new WP_User( $user_id );
4441
			if ( ! $user || ! $user->exists() ) {
4442
				return false;
4443
			}
4444
		}
4445
4446
		$token = Jetpack_Data::get_access_token( $user_id );
4447
		if ( ! $token ) {
4448
			return false;
4449
		}
4450
4451
		$token_check = "$token_key.";
4452
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4453
			return false;
4454
		}
4455
4456
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4457
4458
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4459
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4460
			$post_data   = $_POST;
4461
			$file_hashes = array();
4462
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4463
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4464
					continue;
4465
				}
4466
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4467
				$file_hashes[$post_data_key] = $post_data_value;
4468
			}
4469
4470
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4471
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4472
				$post_data[$post_data_key] = $post_data_value;
4473
			}
4474
4475
			ksort( $post_data );
4476
4477
			$body = http_build_query( stripslashes_deep( $post_data ) );
4478
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4479
			$body = file_get_contents( 'php://input' );
4480
		} else {
4481
			$body = null;
4482
		}
4483
		$signature = $jetpack_signature->sign_current_request(
4484
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4485
		);
4486
4487
		if ( ! $signature ) {
4488
			return false;
4489
		} else if ( is_wp_error( $signature ) ) {
4490
			return $signature;
4491
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4492
			return false;
4493
		}
4494
4495
		$timestamp = (int) $_GET['timestamp'];
4496
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4497
4498
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4499
			return false;
4500
		}
4501
4502
		$this->xmlrpc_verification = array(
4503
			'type'    => $token_type,
4504
			'user_id' => $token->external_user_id,
4505
		);
4506
4507
		return $this->xmlrpc_verification;
4508
	}
4509
4510
	/**
4511
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4512
	 */
4513
	function authenticate_jetpack( $user, $username, $password ) {
4514
		if ( is_a( $user, 'WP_User' ) ) {
4515
			return $user;
4516
		}
4517
4518
		$token_details = $this->verify_xml_rpc_signature();
4519
4520
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4521
			return $user;
4522
		}
4523
4524
		if ( 'user' !== $token_details['type'] ) {
4525
			return $user;
4526
		}
4527
4528
		if ( ! $token_details['user_id'] ) {
4529
			return $user;
4530
		}
4531
4532
		nocache_headers();
4533
4534
		return new WP_User( $token_details['user_id'] );
4535
	}
4536
4537
	function add_nonce( $timestamp, $nonce ) {
4538
		global $wpdb;
4539
		static $nonces_used_this_request = array();
4540
4541
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4542
			return $nonces_used_this_request["$timestamp:$nonce"];
4543
		}
4544
4545
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4546
		$timestamp = (int) $timestamp;
4547
		$nonce     = esc_sql( $nonce );
4548
4549
		// Raw query so we can avoid races: add_option will also update
4550
		$show_errors = $wpdb->show_errors( false );
4551
4552
		$old_nonce = $wpdb->get_row(
4553
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4554
		);
4555
4556
		if ( is_null( $old_nonce ) ) {
4557
			$return = $wpdb->query(
4558
				$wpdb->prepare(
4559
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4560
					"jetpack_nonce_{$timestamp}_{$nonce}",
4561
					time(),
4562
					'no'
4563
				)
4564
			);
4565
		} else {
4566
			$return = false;
4567
		}
4568
4569
		$wpdb->show_errors( $show_errors );
4570
4571
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
4572
4573
		return $return;
4574
	}
4575
4576
	/**
4577
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
4578
	 * Capture it here so we can verify the signature later.
4579
	 */
4580
	function xmlrpc_methods( $methods ) {
4581
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4582
		return $methods;
4583
	}
4584
4585
	function public_xmlrpc_methods( $methods ) {
4586
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
4587
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
4588
		}
4589
		return $methods;
4590
	}
4591
4592
	function jetpack_getOptions( $args ) {
4593
		global $wp_xmlrpc_server;
4594
4595
		$wp_xmlrpc_server->escape( $args );
4596
4597
		$username	= $args[1];
4598
		$password	= $args[2];
4599
4600
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
4601
			return $wp_xmlrpc_server->error;
4602
		}
4603
4604
		$options = array();
4605
		$user_data = $this->get_connected_user_data();
4606
		if ( is_array( $user_data ) ) {
4607
			$options['jetpack_user_id'] = array(
4608
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
4609
				'readonly'      => true,
4610
				'value'         => $user_data['ID'],
4611
			);
4612
			$options['jetpack_user_login'] = array(
4613
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
4614
				'readonly'      => true,
4615
				'value'         => $user_data['login'],
4616
			);
4617
			$options['jetpack_user_email'] = array(
4618
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
4619
				'readonly'      => true,
4620
				'value'         => $user_data['email'],
4621
			);
4622
			$options['jetpack_user_site_count'] = array(
4623
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
4624
				'readonly'      => true,
4625
				'value'         => $user_data['site_count'],
4626
			);
4627
		}
4628
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
4629
		$args = stripslashes_deep( $args );
4630
		return $wp_xmlrpc_server->wp_getOptions( $args );
4631
	}
4632
4633
	function xmlrpc_options( $options ) {
4634
		$jetpack_client_id = false;
4635
		if ( self::is_active() ) {
4636
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
4637
		}
4638
		$options['jetpack_version'] = array(
4639
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
4640
				'readonly'      => true,
4641
				'value'         => JETPACK__VERSION,
4642
		);
4643
4644
		$options['jetpack_client_id'] = array(
4645
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
4646
				'readonly'      => true,
4647
				'value'         => $jetpack_client_id,
4648
		);
4649
		return $options;
4650
	}
4651
4652
	public static function clean_nonces( $all = false ) {
4653
		global $wpdb;
4654
4655
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
4656
		if ( method_exists ( $wpdb , 'esc_like' ) ) {
4657
			$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
4658
		} else {
4659
			$sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
4660
		}
4661
4662
		if ( true !== $all ) {
4663
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
4664
			$sql_args[] = time() - 3600;
4665
		}
4666
4667
		$sql .= ' ORDER BY `option_id` LIMIT 100';
4668
4669
		$sql = $wpdb->prepare( $sql, $sql_args );
4670
4671
		for ( $i = 0; $i < 1000; $i++ ) {
4672
			if ( ! $wpdb->query( $sql ) ) {
4673
				break;
4674
			}
4675
		}
4676
	}
4677
4678
	/**
4679
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
4680
	 * SET: state( $key, $value );
4681
	 * GET: $value = state( $key );
4682
	 *
4683
	 * @param string $key
4684
	 * @param string $value
4685
	 * @param bool $restate private
4686
	 */
4687
	public static function state( $key = null, $value = null, $restate = false ) {
4688
		static $state = array();
4689
		static $path, $domain;
4690
		if ( ! isset( $path ) ) {
4691
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
4692
			$admin_url = Jetpack::admin_url();
4693
			$bits      = parse_url( $admin_url );
4694
4695
			if ( is_array( $bits ) ) {
4696
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
4697
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
4698
			} else {
4699
				$path = $domain = null;
4700
			}
4701
		}
4702
4703
		// Extract state from cookies and delete cookies
4704
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
4705
			$yum = $_COOKIE[ 'jetpackState' ];
4706
			unset( $_COOKIE[ 'jetpackState' ] );
4707
			foreach ( $yum as $k => $v ) {
4708
				if ( strlen( $v ) )
4709
					$state[ $k ] = $v;
4710
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
4711
			}
4712
		}
4713
4714
		if ( $restate ) {
4715
			foreach ( $state as $k => $v ) {
4716
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
4717
			}
4718
			return;
4719
		}
4720
4721
		// Get a state variable
4722
		if ( isset( $key ) && ! isset( $value ) ) {
4723
			if ( array_key_exists( $key, $state ) )
4724
				return $state[ $key ];
4725
			return null;
4726
		}
4727
4728
		// Set a state variable
4729
		if ( isset ( $key ) && isset( $value ) ) {
4730
			if( is_array( $value ) && isset( $value[0] ) ) {
4731
				$value = $value[0];
4732
			}
4733
			$state[ $key ] = $value;
4734
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
4735
		}
4736
	}
4737
4738
	public static function restate() {
4739
		Jetpack::state( null, null, true );
4740
	}
4741
4742
	public static function check_privacy( $file ) {
4743
		static $is_site_publicly_accessible = null;
4744
4745
		if ( is_null( $is_site_publicly_accessible ) ) {
4746
			$is_site_publicly_accessible = false;
4747
4748
			Jetpack::load_xml_rpc_client();
4749
			$rpc = new Jetpack_IXR_Client();
4750
4751
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
4752
			if ( $success ) {
4753
				$response = $rpc->getResponse();
4754
				if ( $response ) {
4755
					$is_site_publicly_accessible = true;
4756
				}
4757
			}
4758
4759
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
4760
		}
4761
4762
		if ( $is_site_publicly_accessible ) {
4763
			return;
4764
		}
4765
4766
		$module_slug = self::get_module_slug( $file );
4767
4768
		$privacy_checks = Jetpack::state( 'privacy_checks' );
4769
		if ( ! $privacy_checks ) {
4770
			$privacy_checks = $module_slug;
4771
		} else {
4772
			$privacy_checks .= ",$module_slug";
4773
		}
4774
4775
		Jetpack::state( 'privacy_checks', $privacy_checks );
4776
	}
4777
4778
	/**
4779
	 * Helper method for multicall XMLRPC.
4780
	 */
4781
	public static function xmlrpc_async_call() {
4782
		global $blog_id;
4783
		static $clients = array();
4784
4785
		$client_blog_id = is_multisite() ? $blog_id : 0;
4786
4787
		if ( ! isset( $clients[$client_blog_id] ) ) {
4788
			Jetpack::load_xml_rpc_client();
4789
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
4790
			if ( function_exists( 'ignore_user_abort' ) ) {
4791
				ignore_user_abort( true );
4792
			}
4793
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
4794
		}
4795
4796
		$args = func_get_args();
4797
4798
		if ( ! empty( $args[0] ) ) {
4799
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
4800
		} elseif ( is_multisite() ) {
4801
			foreach ( $clients as $client_blog_id => $client ) {
4802
				if ( ! $client_blog_id || empty( $client->calls ) ) {
4803
					continue;
4804
				}
4805
4806
				$switch_success = switch_to_blog( $client_blog_id, true );
4807
				if ( ! $switch_success ) {
4808
					continue;
4809
				}
4810
4811
				flush();
4812
				$client->query();
4813
4814
				restore_current_blog();
4815
			}
4816
		} else {
4817
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
4818
				flush();
4819
				$clients[0]->query();
4820
			}
4821
		}
4822
	}
4823
4824
	public static function staticize_subdomain( $url ) {
4825
4826
		// Extract hostname from URL
4827
		$host = parse_url( $url, PHP_URL_HOST );
4828
4829
		// Explode hostname on '.'
4830
		$exploded_host = explode( '.', $host );
4831
4832
		// Retrieve the name and TLD
4833
		if ( count( $exploded_host ) > 1 ) {
4834
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
4835
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
4836
			// Rebuild domain excluding subdomains
4837
			$domain = $name . '.' . $tld;
4838
		} else {
4839
			$domain = $host;
4840
		}
4841
		// Array of Automattic domains
4842
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
4843
4844
		// Return $url if not an Automattic domain
4845
		if ( ! in_array( $domain, $domain_whitelist ) ) {
4846
			return $url;
4847
		}
4848
4849
		if ( is_ssl() ) {
4850
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
4851
		}
4852
4853
		srand( crc32( basename( $url ) ) );
4854
		$static_counter = rand( 0, 2 );
4855
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
4856
4857
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
4858
	}
4859
4860
/* JSON API Authorization */
4861
4862
	/**
4863
	 * Handles the login action for Authorizing the JSON API
4864
	 */
4865
	function login_form_json_api_authorization() {
4866
		$this->verify_json_api_authorization_request();
4867
4868
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
4869
4870
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
4871
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
4872
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
4873
	}
4874
4875
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
4876
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
4877
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
4878
			return $url;
4879
		}
4880
4881
		$parsed_url = parse_url( $url );
4882
		$url = strtok( $url, '?' );
4883
		$url = "$url?{$_SERVER['QUERY_STRING']}";
4884
		if ( ! empty( $parsed_url['query'] ) )
4885
			$url .= "&{$parsed_url['query']}";
4886
4887
		return $url;
4888
	}
4889
4890
	// Make sure the POSTed request is handled by the same action
4891
	function preserve_action_in_login_form_for_json_api_authorization() {
4892
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
4893
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
4894
	}
4895
4896
	// If someone logs in to approve API access, store the Access Code in usermeta
4897
	function store_json_api_authorization_token( $user_login, $user ) {
4898
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
4899
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
4900
		$token = wp_generate_password( 32, false );
4901
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
4902
	}
4903
4904
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
4905
	function allow_wpcom_public_api_domain( $domains ) {
4906
		$domains[] = 'public-api.wordpress.com';
4907
		return $domains;
4908
	}
4909
4910
	// Add the Access Code details to the public-api.wordpress.com redirect
4911
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
4912
		return add_query_arg(
4913
			urlencode_deep(
4914
				array(
4915
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
4916
					'jetpack-user-id' => (int) $user->ID,
4917
					'jetpack-state'   => $this->json_api_authorization_request['state'],
4918
				)
4919
			),
4920
			$redirect_to
4921
		);
4922
	}
4923
4924
	// Verifies the request by checking the signature
4925
	function verify_json_api_authorization_request() {
4926
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4927
4928
		$token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
4929
		if ( ! $token || empty( $token->secret ) ) {
4930
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
4931
		}
4932
4933
		$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' );
4934
4935
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4936
4937
		if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
4938
			$signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
4939
		} else {
4940
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
4941
		}
4942
4943
		if ( ! $signature ) {
4944
			wp_die( $die_error );
4945
		} else if ( is_wp_error( $signature ) ) {
4946
			wp_die( $die_error );
4947
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4948
			if ( is_ssl() ) {
4949
				// 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
4950
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
4951
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $_GET['signature'] ) ) {
4952
					wp_die( $die_error );
4953
				}
4954
			} else {
4955
				wp_die( $die_error );
4956
			}
4957
		}
4958
4959
		$timestamp = (int) $_GET['timestamp'];
4960
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4961
4962
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4963
			// De-nonce the nonce, at least for 5 minutes.
4964
			// 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)
4965
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
4966
			if ( $old_nonce_time < time() - 300 ) {
4967
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
4968
			}
4969
		}
4970
4971
		$data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
4972
		$data_filters = array(
4973
			'state'        => 'opaque',
4974
			'client_id'    => 'int',
4975
			'client_title' => 'string',
4976
			'client_image' => 'url',
4977
		);
4978
4979
		foreach ( $data_filters as $key => $sanitation ) {
4980
			if ( ! isset( $data->$key ) ) {
4981
				wp_die( $die_error );
4982
			}
4983
4984
			switch ( $sanitation ) {
4985
			case 'int' :
4986
				$this->json_api_authorization_request[$key] = (int) $data->$key;
4987
				break;
4988
			case 'opaque' :
4989
				$this->json_api_authorization_request[$key] = (string) $data->$key;
4990
				break;
4991
			case 'string' :
4992
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
4993
				break;
4994
			case 'url' :
4995
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
4996
				break;
4997
			}
4998
		}
4999
5000
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5001
			wp_die( $die_error );
5002
		}
5003
	}
5004
5005
	function login_message_json_api_authorization( $message ) {
5006
		return '<p class="message">' . sprintf(
5007
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5008
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5009
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5010
	}
5011
5012
	/**
5013
	 * Get $content_width, but with a <s>twist</s> filter.
5014
	 */
5015
	public static function get_content_width() {
5016
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5017
		/**
5018
		 * Filter the Content Width value.
5019
		 *
5020
		 * @since 2.2.3
5021
		 *
5022
		 * @param string $content_width Content Width value.
5023
		 */
5024
		return apply_filters( 'jetpack_content_width', $content_width );
5025
	}
5026
5027
	/**
5028
	 * Centralize the function here until it gets added to core.
5029
	 *
5030
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
5031
	 * @param int $size Size of the avatar image
5032
	 * @param string $default URL to a default image to use if no avatar is available
5033
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
5034
	 *
5035
	 * @return array First element is the URL, second is the class.
5036
	 */
5037
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
5038
		// Don't bother adding the __return_true filter if it's already there.
5039
		$has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
5040
5041
		if ( $force_display && ! $has_filter )
5042
			add_filter( 'pre_option_show_avatars', '__return_true' );
5043
5044
		$avatar = get_avatar( $id_or_email, $size, $default );
5045
5046
		if ( $force_display && ! $has_filter )
5047
			remove_filter( 'pre_option_show_avatars', '__return_true' );
5048
5049
		// If no data, fail out.
5050
		if ( is_wp_error( $avatar ) || ! $avatar )
5051
			return array( null, null );
5052
5053
		// Pull out the URL.  If it's not there, fail out.
5054
		if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
5055
			return array( null, null );
5056
		$url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
5057
5058
		// Pull out the class, but it's not a big deal if it's missing.
5059
		$class = '';
5060
		if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
5061
			$class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
5062
5063
		return array( $url, $class );
5064
	}
5065
5066
	/**
5067
	 * Pings the WordPress.com Mirror Site for the specified options.
5068
	 *
5069
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5070
	 *
5071
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5072
	 */
5073
	public function get_cloud_site_options( $option_names ) {
5074
		$option_names = array_filter( (array) $option_names, 'is_string' );
5075
5076
		Jetpack::load_xml_rpc_client();
5077
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5078
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5079
		if ( $xml->isError() ) {
5080
			return array(
5081
				'error_code' => $xml->getErrorCode(),
5082
				'error_msg'  => $xml->getErrorMessage(),
5083
			);
5084
		}
5085
		$cloud_site_options = $xml->getResponse();
5086
5087
		return $cloud_site_options;
5088
	}
5089
5090
	/**
5091
	 * Fetch the filtered array of options that we should compare to determine an identity crisis.
5092
	 *
5093
	 * @return array An array of options to check.
5094
	 */
5095
	public static function identity_crisis_options_to_check() {
5096
		return array(
5097
			'siteurl',
5098
			'home',
5099
		);
5100
	}
5101
5102
	/**
5103
	 * Checks to make sure that local options have the same values as remote options.  Will cache the results for up to 24 hours.
5104
	 *
5105
	 * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
5106
	 *
5107
	 * @return array An array of options that do not match.  If everything is good, it will evaluate to false.
5108
	 */
5109
	public static function check_identity_crisis( $force_recheck = false ) {
5110
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || Jetpack::is_staging_site() )
5111
			return false;
5112
5113
		if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
5114
			$options_to_check = self::identity_crisis_options_to_check();
5115
			$cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
5116
			$errors        = array();
5117
5118
			foreach ( $cloud_options as $cloud_key => $cloud_value ) {
5119
5120
				// If it's not the same as the local value...
5121
				if ( $cloud_value !== get_option( $cloud_key ) ) {
5122
5123
					// Break out if we're getting errors.  We are going to check the error keys later when we alert.
5124
					if ( 'error_code' == $cloud_key ) {
5125
						$errors[ $cloud_key ] = $cloud_value;
5126
						break;
5127
					}
5128
5129
					$parsed_cloud_value = parse_url( $cloud_value );
5130
					// If the current options is an IP address
5131
					if ( filter_var( $parsed_cloud_value['host'], FILTER_VALIDATE_IP ) ) {
5132
						// Give the new value a Jetpack to fly in to the clouds
5133
						continue;
5134
					}
5135
5136
					// And it's not been added to the whitelist...
5137
					if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
5138
						/*
5139
						 * This should be a temporary hack until a cleaner solution is found.
5140
						 *
5141
						 * The siteurl and home can be set to use http in General > Settings
5142
						 * however some constants can be defined that can force https in wp-admin
5143
						 * when this happens wpcom can confuse wporg with a fake identity
5144
						 * crisis with a mismatch of http vs https when it should be allowed.
5145
						 * we need to check that here.
5146
						 *
5147
						 * @see https://github.com/Automattic/jetpack/issues/1006
5148
						 */
5149
						if ( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
5150
							&& ( substr( $cloud_value, 0, 8 ) == "https://" )
5151
							&& Jetpack::init()->is_ssl_required_to_visit_site() ) {
5152
							// Ok, we found a mismatch of http and https because of wp-config, not an invalid url
5153
							continue;
5154
						}
5155
5156
5157
						// Then kick an error!
5158
						$errors[ $cloud_key ] = $cloud_value;
5159
					}
5160
				}
5161
			}
5162
		}
5163
5164
		/**
5165
		 * Filters the errors returned when checking for an Identity Crisis.
5166
		 *
5167
		 * @since 2.3.2
5168
		 *
5169
		 * @param array $errors Array of Identity Crisis errors.
5170
		 * @param bool $force_recheck Ignore any cached transient and manually re-check. Default to false.
5171
		 */
5172
		return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
5173
	}
5174
5175
	/**
5176
	 * Checks whether a value is already whitelisted.
5177
	 *
5178
	 * @param string $key The option name that we're checking the value for.
5179
	 * @param string $value The value that we're curious to see if it's on the whitelist.
5180
	 *
5181
	 * @return bool Whether the value is whitelisted.
5182
	 */
5183
	public static function is_identity_crisis_value_whitelisted( $key, $value ) {
5184
		$whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
5185
		if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
5186
			return true;
5187
		}
5188
		return false;
5189
	}
5190
5191
	/**
5192
	 * Checks whether the home and siteurl specifically are whitelisted
5193
	 * Written so that we don't have re-check $key and $value params every time
5194
	 * we want to check if this site is whitelisted, for example in footer.php
5195
	 *
5196
	 * @since  3.8.0
5197
	 * @return bool True = already whitelisted False = not whitelisted
5198
	 */
5199
	public static function is_staging_site() {
5200
		$is_staging = false;
5201
5202
		$known_staging = array(
5203
			'urls' => array(
5204
				'#\.staging\.wpengine\.com$#i', // WP Engine
5205
				),
5206
			'constants' => array(
5207
				'IS_WPE_SNAPSHOT',      // WP Engine
5208
				'KINSTA_DEV_ENV',       // Kinsta.com
5209
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5210
				'JETPACK_STAGING_MODE', // Generic
5211
				)
5212
			);
5213
		/**
5214
		 * Filters the flags of known staging sites.
5215
		 *
5216
		 * @since 3.9.0
5217
		 *
5218
		 * @param array $known_staging {
5219
		 *     An array of arrays that each are used to check if the current site is staging.
5220
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5221
		 *     @type array $constants PHP constants of known staging/developement environments.
5222
		 *  }
5223
		 */
5224
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5225
5226
		if ( isset( $known_staging['urls'] ) ) {
5227
			foreach ( $known_staging['urls'] as $url ){
5228
				if ( preg_match( $url, site_url() ) ) {
5229
					$is_staging = true;
5230
					break;
5231
				}
5232
			}
5233
		}
5234
5235
		if ( isset( $known_staging['constants'] ) ) {
5236
			foreach ( $known_staging['constants'] as $constant ) {
5237
				if ( defined( $constant ) && constant( $constant ) ) {
5238
					$is_staging = true;
5239
				}
5240
			}
5241
		}
5242
5243
		/**
5244
		 * Filters is_staging_site check.
5245
		 *
5246
		 * @since 3.9.0
5247
		 *
5248
		 * @param bool $is_staging If the current site is a staging site.
5249
		 */
5250
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5251
	}
5252
5253
	/**
5254
	 * Maybe Use a .min.css stylesheet, maybe not.
5255
	 *
5256
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5257
	 */
5258
	public static function maybe_min_asset( $url, $path, $plugin ) {
5259
		// Short out on things trying to find actual paths.
5260
		if ( ! $path || empty( $plugin ) ) {
5261
			return $url;
5262
		}
5263
5264
		// Strip out the abspath.
5265
		$base = dirname( plugin_basename( $plugin ) );
5266
5267
		// Short out on non-Jetpack assets.
5268
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5269
			return $url;
5270
		}
5271
5272
		// File name parsing.
5273
		$file              = "{$base}/{$path}";
5274
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5275
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5276
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5277
		$extension         = array_shift( $file_name_parts_r );
5278
5279
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5280
			// Already pointing at the minified version.
5281
			if ( 'min' === $file_name_parts_r[0] ) {
5282
				return $url;
5283
			}
5284
5285
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5286
			if ( file_exists( $min_full_path ) ) {
5287
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5288
			}
5289
		}
5290
5291
		return $url;
5292
	}
5293
5294
	/**
5295
	 * Maybe inlines a stylesheet.
5296
	 *
5297
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5298
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5299
	 *
5300
	 * Attached to `style_loader_tag` filter.
5301
	 *
5302
	 * @param string $tag The tag that would link to the external asset.
5303
	 * @param string $handle The registered handle of the script in question.
5304
	 *
5305
	 * @return string
5306
	 */
5307
	public static function maybe_inline_style( $tag, $handle ) {
5308
		global $wp_styles;
5309
		$item = $wp_styles->registered[ $handle ];
5310
5311
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5312
			return $tag;
5313
		}
5314
5315
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5316
			$href = $matches[1];
5317
			// Strip off query string
5318
			if ( $pos = strpos( $href, '?' ) ) {
5319
				$href = substr( $href, 0, $pos );
5320
			}
5321
			// Strip off fragment
5322
			if ( $pos = strpos( $href, '#' ) ) {
5323
				$href = substr( $href, 0, $pos );
5324
			}
5325
		} else {
5326
			return $tag;
5327
		}
5328
5329
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5330
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5331
			return $tag;
5332
		}
5333
5334
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5335
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5336
			// And this isn't the pass that actually deals with the RTL version...
5337
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5338
				// Short out, as the RTL version will deal with it in a moment.
5339
				return $tag;
5340
			}
5341
		}
5342
5343
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5344
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5345
		if ( $css ) {
5346
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5347
			if ( empty( $item->extra['after'] ) ) {
5348
				wp_add_inline_style( $handle, $css );
5349
			} else {
5350
				array_unshift( $item->extra['after'], $css );
5351
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5352
			}
5353
		}
5354
5355
		return $tag;
5356
	}
5357
5358
	/**
5359
	 * Loads a view file from the views
5360
	 *
5361
	 * Data passed in with the $data parameter will be available in the
5362
	 * template file as $data['value']
5363
	 *
5364
	 * @param string $template - Template file to load
5365
	 * @param array $data - Any data to pass along to the template
5366
	 * @return boolean - If template file was found
5367
	 **/
5368
	public function load_view( $template, $data = array() ) {
5369
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5370
5371
		if( file_exists( $views_dir . $template ) ) {
5372
			require_once( $views_dir . $template );
5373
			return true;
5374
		}
5375
5376
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5377
		return false;
5378
	}
5379
5380
	/**
5381
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5382
	 */
5383
	public function deprecated_hooks() {
5384
		global $wp_filter;
5385
5386
		/*
5387
		 * Format:
5388
		 * deprecated_filter_name => replacement_name
5389
		 *
5390
		 * If there is no replacement us null for replacement_name
5391
		 */
5392
		$deprecated_list = array(
5393
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5394
			'wpl_sharing_2014_1'                                     => null,
5395
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5396
			'jetpack_identity_crisis_options_to_check'               => null,
5397
			'update_option_jetpack_single_user_site'                 => null,
5398
			'audio_player_default_colors'                            => null,
5399
			'add_option_jetpack_featured_images_enabled'             => null,
5400
			'add_option_jetpack_update_details'                      => null,
5401
			'add_option_jetpack_updates'                             => null,
5402
			'add_option_jetpack_network_name'                        => null,
5403
			'add_option_jetpack_network_allow_new_registrations'     => null,
5404
			'add_option_jetpack_network_add_new_users'               => null,
5405
			'add_option_jetpack_network_site_upload_space'           => null,
5406
			'add_option_jetpack_network_upload_file_types'           => null,
5407
			'add_option_jetpack_network_enable_administration_menus' => null,
5408
			'add_option_jetpack_is_multi_site'                       => null,
5409
			'add_option_jetpack_is_main_network'                     => null,
5410
			'add_option_jetpack_main_network_site'                   => null,
5411
			'jetpack_sync_all_registered_options'                    => null,
5412
		);
5413
5414
		// This is a silly loop depth. Better way?
5415
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5416
			if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
5417
				foreach( $wp_filter[$hook] AS $func => $values ) {
5418
					foreach( $values AS $hooked ) {
5419
						_deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
5420
					}
5421
				}
5422
			}
5423
		}
5424
	}
5425
5426
	/**
5427
	 * Converts any url in a stylesheet, to the correct absolute url.
5428
	 *
5429
	 * Considerations:
5430
	 *  - Normal, relative URLs     `feh.png`
5431
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5432
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5433
	 *  - Absolute URLs             `http://domain.com/feh.png`
5434
	 *  - Domain root relative URLs `/feh.png`
5435
	 *
5436
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5437
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5438
	 *
5439
	 * @return mixed|string
5440
	 */
5441
	public static function absolutize_css_urls( $css, $css_file_url ) {
5442
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5443
		$css_dir = dirname( $css_file_url );
5444
		$p       = parse_url( $css_dir );
5445
		$domain  = sprintf(
5446
					'%1$s//%2$s%3$s%4$s',
5447
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5448
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5449
					$p['host'],
5450
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5451
				);
5452
5453
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5454
			$find = $replace = array();
5455
			foreach ( $matches as $match ) {
5456
				$url = trim( $match['path'], "'\" \t" );
5457
5458
				// If this is a data url, we don't want to mess with it.
5459
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5460
					continue;
5461
				}
5462
5463
				// If this is an absolute or protocol-agnostic url,
5464
				// we don't want to mess with it.
5465
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5466
					continue;
5467
				}
5468
5469
				switch ( substr( $url, 0, 1 ) ) {
5470
					case '/':
5471
						$absolute = $domain . $url;
5472
						break;
5473
					default:
5474
						$absolute = $css_dir . '/' . $url;
5475
				}
5476
5477
				$find[]    = $match[0];
5478
				$replace[] = sprintf( 'url("%s")', $absolute );
5479
			}
5480
			$css = str_replace( $find, $replace, $css );
5481
		}
5482
5483
		return $css;
5484
	}
5485
5486
	/**
5487
	 * This method checks to see if SSL is required by the site in
5488
	 * order to visit it in some way other than only setting the
5489
	 * https value in the home or siteurl values.
5490
	 *
5491
	 * @since 3.2
5492
	 * @return boolean
5493
	 **/
5494
	private function is_ssl_required_to_visit_site() {
5495
		global $wp_version;
5496
		$ssl = is_ssl();
5497
5498
		if ( force_ssl_admin() ) {
5499
			$ssl = true;
5500
		}
5501
		return $ssl;
5502
	}
5503
5504
	/**
5505
	 * This methods removes all of the registered css files on the front end
5506
	 * from Jetpack in favor of using a single file. In effect "imploding"
5507
	 * all the files into one file.
5508
	 *
5509
	 * Pros:
5510
	 * - Uses only ONE css asset connection instead of 15
5511
	 * - Saves a minimum of 56k
5512
	 * - Reduces server load
5513
	 * - Reduces time to first painted byte
5514
	 *
5515
	 * Cons:
5516
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5517
	 *		should not cause any issues with themes.
5518
	 * - Plugins/themes dequeuing styles no longer do anything. See
5519
	 *		jetpack_implode_frontend_css filter for a workaround
5520
	 *
5521
	 * For some situations developers may wish to disable css imploding and
5522
	 * instead operate in legacy mode where each file loads seperately and
5523
	 * can be edited individually or dequeued. This can be accomplished with
5524
	 * the following line:
5525
	 *
5526
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5527
	 *
5528
	 * @since 3.2
5529
	 **/
5530
	public function implode_frontend_css( $travis_test = false ) {
5531
		$do_implode = true;
5532
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5533
			$do_implode = false;
5534
		}
5535
5536
		/**
5537
		 * Allow CSS to be concatenated into a single jetpack.css file.
5538
		 *
5539
		 * @since 3.2.0
5540
		 *
5541
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5542
		 */
5543
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5544
5545
		// Do not use the imploded file when default behaviour was altered through the filter
5546
		if ( ! $do_implode ) {
5547
			return;
5548
		}
5549
5550
		// We do not want to use the imploded file in dev mode, or if not connected
5551
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5552
			if ( ! $travis_test ) {
5553
				return;
5554
			}
5555
		}
5556
5557
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
5558
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
5559
			return;
5560
		}
5561
5562
		/*
5563
		 * Now we assume Jetpack is connected and able to serve the single
5564
		 * file.
5565
		 *
5566
		 * In the future there will be a check here to serve the file locally
5567
		 * or potentially from the Jetpack CDN
5568
		 *
5569
		 * For now:
5570
		 * - Enqueue a single imploded css file
5571
		 * - Zero out the style_loader_tag for the bundled ones
5572
		 * - Be happy, drink scotch
5573
		 */
5574
5575
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
5576
5577
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
5578
5579
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
5580
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
5581
	}
5582
5583
	function concat_remove_style_loader_tag( $tag, $handle ) {
5584
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
5585
			$tag = '';
5586
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5587
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
5588
			}
5589
		}
5590
5591
		return $tag;
5592
	}
5593
5594
	/*
5595
	 * Check the heartbeat data
5596
	 *
5597
	 * Organizes the heartbeat data by severity.  For example, if the site
5598
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
5599
	 *
5600
	 * Data will be added to "caution" array, if it either:
5601
	 *  - Out of date Jetpack version
5602
	 *  - Out of date WP version
5603
	 *  - Out of date PHP version
5604
	 *
5605
	 * $return array $filtered_data
5606
	 */
5607
	public static function jetpack_check_heartbeat_data() {
5608
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
5609
5610
		$good    = array();
5611
		$caution = array();
5612
		$bad     = array();
5613
5614
		foreach ( $raw_data as $stat => $value ) {
5615
5616
			// Check jetpack version
5617
			if ( 'version' == $stat ) {
5618
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
5619
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
5620
					continue;
5621
				}
5622
			}
5623
5624
			// Check WP version
5625
			if ( 'wp-version' == $stat ) {
5626
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
5627
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
5628
					continue;
5629
				}
5630
			}
5631
5632
			// Check PHP version
5633
			if ( 'php-version' == $stat ) {
5634
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
5635
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
5636
					continue;
5637
				}
5638
			}
5639
5640
			// Check ID crisis
5641
			if ( 'identitycrisis' == $stat ) {
5642
				if ( 'yes' == $value ) {
5643
					$bad[ $stat ] = $value;
5644
					continue;
5645
				}
5646
			}
5647
5648
			// The rest are good :)
5649
			$good[ $stat ] = $value;
5650
		}
5651
5652
		$filtered_data = array(
5653
			'good'    => $good,
5654
			'caution' => $caution,
5655
			'bad'     => $bad
5656
		);
5657
5658
		return $filtered_data;
5659
	}
5660
5661
5662
	/*
5663
	 * This method is used to organize all options that can be reset
5664
	 * without disconnecting Jetpack.
5665
	 *
5666
	 * It is used in class.jetpack-cli.php to reset options
5667
	 *
5668
	 * @return array of options to delete.
5669
	 */
5670
	public static function get_jetpack_options_for_reset() {
5671
		$jetpack_options            = Jetpack_Options::get_option_names();
5672
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
5673
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
5674
5675
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
5676
5677
		// A manual build of the wp options
5678
		$wp_options = array(
5679
			'sharing-options',
5680
			'disabled_likes',
5681
			'disabled_reblogs',
5682
			'jetpack_comments_likes_enabled',
5683
			'wp_mobile_excerpt',
5684
			'wp_mobile_featured_images',
5685
			'wp_mobile_app_promos',
5686
			'stats_options',
5687
			'stats_dashboard_widget',
5688
			'safecss_preview_rev',
5689
			'safecss_rev',
5690
			'safecss_revision_migrated',
5691
			'nova_menu_order',
5692
			'jetpack_portfolio',
5693
			'jetpack_portfolio_posts_per_page',
5694
			'jetpack_testimonial',
5695
			'jetpack_testimonial_posts_per_page',
5696
			'wp_mobile_custom_css',
5697
			'sharedaddy_disable_resources',
5698
			'sharing-options',
5699
			'sharing-services',
5700
			'site_icon_temp_data',
5701
			'featured-content',
5702
			'site_logo',
5703
			'jetpack_dismissed_notices',
5704
		);
5705
5706
		// Flag some Jetpack options as unsafe
5707
		$unsafe_options = array(
5708
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
5709
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
5710
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
5711
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
5712
5713
			// non_compact
5714
			'activated',
5715
5716
			// private
5717
			'register',
5718
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
5719
			'user_token',                  // (string) The User Token of this site. (deprecated)
5720
			'user_tokens'
5721
		);
5722
5723
		// Remove the unsafe Jetpack options
5724
		foreach ( $unsafe_options as $unsafe_option ) {
5725
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
5726
				unset( $all_jp_options[ $key ] );
5727
			}
5728
		}
5729
5730
		$options = array(
5731
			'jp_options' => $all_jp_options,
5732
			'wp_options' => $wp_options
5733
		);
5734
5735
		return $options;
5736
	}
5737
5738
	/**
5739
	 * Check if an option of a Jetpack module has been updated.
5740
	 *
5741
	 * If any module option has been updated before Jump Start has been dismissed,
5742
	 * update the 'jumpstart' option so we can hide Jump Start.
5743
	 *
5744
	 * @param string $option_name
5745
	 *
5746
	 * @return bool
5747
	 */
5748
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
5749
		// Bail if Jump Start has already been dismissed
5750
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
5751
			return false;
5752
		}
5753
5754
		$jetpack = Jetpack::init();
5755
5756
		// Manual build of module options
5757
		$option_names = self::get_jetpack_options_for_reset();
5758
5759
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
5760
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
5761
5762
			//Jump start is being dismissed send data to MC Stats
5763
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
5764
5765
			$jetpack->do_stats( 'server_side' );
5766
		}
5767
5768
	}
5769
5770
	/*
5771
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
5772
	 * so we can bring them directly to their site in calypso.
5773
	 *
5774
	 * @param string | url
5775
	 * @return string | url without the guff
5776
	 */
5777
	public static function build_raw_urls( $url ) {
5778
		$strip_http = '/.*?:\/\//i';
5779
		$url = preg_replace( $strip_http, '', $url  );
5780
		$url = str_replace( '/', '::', $url );
5781
		return $url;
5782
	}
5783
5784
	/**
5785
	 * Stores and prints out domains to prefetch for page speed optimization.
5786
	 *
5787
	 * @param mixed $new_urls
5788
	 */
5789
	public static function dns_prefetch( $new_urls = null ) {
5790
		static $prefetch_urls = array();
5791
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
5792
			echo "\r\n";
5793
			foreach ( $prefetch_urls as $this_prefetch_url ) {
5794
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
5795
			}
5796
		} elseif ( ! empty( $new_urls ) ) {
5797
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
5798
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
5799
			}
5800
			foreach ( (array) $new_urls as $this_new_url ) {
5801
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
5802
			}
5803
			$prefetch_urls = array_unique( $prefetch_urls );
5804
		}
5805
	}
5806
5807
	public function wp_dashboard_setup() {
5808
		if ( self::is_active() ) {
5809
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
5810
			$widget_title = __( 'Site Stats', 'jetpack' );
5811
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
5812
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
5813
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
5814
		}
5815
5816
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
5817
			wp_add_dashboard_widget(
5818
				'jetpack_summary_widget',
5819
				$widget_title,
5820
				array( __CLASS__, 'dashboard_widget' )
5821
			);
5822
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
5823
5824
			// If we're inactive and not in development mode, sort our box to the top.
5825
			if ( ! self::is_active() && ! self::is_development_mode() ) {
5826
				global $wp_meta_boxes;
5827
5828
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
5829
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
5830
5831
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
5832
			}
5833
		}
5834
	}
5835
5836
	/**
5837
	 * @param mixed $result Value for the user's option
5838
	 * @return mixed
5839
	 */
5840
	function get_user_option_meta_box_order_dashboard( $sorted ) {
5841
		if ( ! is_array( $sorted ) ) {
5842
			return $sorted;
5843
		}
5844
5845
		foreach ( $sorted as $box_context => $ids ) {
5846
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
5847
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
5848
				continue;
5849
			}
5850
5851
			$ids_array = explode( ',', $ids );
5852
			$key = array_search( 'dashboard_stats', $ids_array );
5853
5854
			if ( false !== $key ) {
5855
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
5856
				$ids_array[ $key ] = 'jetpack_summary_widget';
5857
				$sorted[ $box_context ] = implode( ',', $ids_array );
5858
				// We've found it, stop searching, and just return.
5859
				break;
5860
			}
5861
		}
5862
5863
		return $sorted;
5864
	}
5865
5866
	public static function dashboard_widget() {
5867
		/**
5868
		 * Fires when the dashboard is loaded.
5869
		 *
5870
		 * @since 3.4.0
5871
		 */
5872
		do_action( 'jetpack_dashboard_widget' );
5873
	}
5874
5875
	public static function dashboard_widget_footer() {
5876
		?>
5877
		<footer>
5878
5879
		<div class="protect">
5880
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
5881
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
5882
				<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>
5883
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
5884
				<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' ); ?>">
5885
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
5886
				</a>
5887
			<?php else : ?>
5888
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
5889
			<?php endif; ?>
5890
		</div>
5891
5892
		<div class="akismet">
5893
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
5894
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
5895
				<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>
5896
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
5897
				<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">
5898
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
5899
				</a>
5900
			<?php else : ?>
5901
				<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>
5902
			<?php endif; ?>
5903
		</div>
5904
5905
		</footer>
5906
		<?php
5907
	}
5908
5909
	public function dashboard_widget_connect_to_wpcom() {
5910
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
5911
			return;
5912
		}
5913
		?>
5914
		<div class="wpcom-connect">
5915
			<div class="jp-emblem">
5916
			<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">
5917
				<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"/>
5918
			</svg>
5919
			</div>
5920
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
5921
			<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>
5922
5923
			<div class="actions">
5924
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
5925
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
5926
				</a>
5927
			</div>
5928
		</div>
5929
		<?php
5930
	}
5931
5932
	/*
5933
	 * A graceful transition to using Core's site icon.
5934
	 *
5935
	 * All of the hard work has already been done with the image
5936
	 * in all_done_page(). All that needs to be done now is update
5937
	 * the option and display proper messaging.
5938
	 *
5939
	 * @todo remove when WP 4.3 is minimum
5940
	 *
5941
	 * @since 3.6.1
5942
	 *
5943
	 * @return bool false = Core's icon not available || true = Core's icon is available
5944
	 */
5945
	public static function jetpack_site_icon_available_in_core() {
5946
		global $wp_version;
5947
		$core_icon_available = function_exists( 'has_site_icon' ) && version_compare( $wp_version, '4.3-beta' ) >= 0;
5948
5949
		if ( ! $core_icon_available ) {
5950
			return false;
5951
		}
5952
5953
		// No need for Jetpack's site icon anymore if core's is already set
5954
		if ( has_site_icon() ) {
5955
			if ( Jetpack::is_module_active( 'site-icon' ) ) {
5956
				Jetpack::log( 'deactivate', 'site-icon' );
5957
				Jetpack::deactivate_module( 'site-icon' );
5958
			}
5959
			return true;
5960
		}
5961
5962
		// Transfer Jetpack's site icon to use core.
5963
		$site_icon_id = Jetpack::get_option( 'site_icon_id' );
5964
		if ( $site_icon_id ) {
5965
			// Update core's site icon
5966
			update_option( 'site_icon', $site_icon_id );
5967
5968
			// Delete Jetpack's icon option. We still want the blavatar and attached data though.
5969
			delete_option( 'site_icon_id' );
5970
		}
5971
5972
		// No need for Jetpack's site icon anymore
5973
		if ( Jetpack::is_module_active( 'site-icon' ) ) {
5974
			Jetpack::log( 'deactivate', 'site-icon' );
5975
			Jetpack::deactivate_module( 'site-icon' );
5976
		}
5977
5978
		return true;
5979
	}
5980
5981
	/**
5982
	 * Return string containing the Jetpack logo.
5983
	 *
5984
	 * @since 3.9.0
5985
	 *
5986
	 * @return string
5987
	 */
5988
	public static function get_jp_emblem() {
5989
		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>';
5990
	}
5991
5992
	/*
5993
	 * Adds a "blank" column in the user admin table to display indication of user connection.
5994
	 */
5995
	function jetpack_icon_user_connected( $columns ) {
5996
		$columns['user_jetpack'] = '';
5997
		return $columns;
5998
	}
5999
6000
	/*
6001
	 * Show Jetpack icon if the user is linked.
6002
	 */
6003
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6004
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6005
			$emblem_html = sprintf(
6006
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6007
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6008
				Jetpack::get_jp_emblem()
6009
			);
6010
			return $emblem_html;
6011
		}
6012
6013
		return $val;
6014
	}
6015
6016
	/*
6017
	 * Style the Jetpack user column
6018
	 */
6019
	function jetpack_user_col_style() {
6020
		global $current_screen;
6021
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6022
			<style>
6023
				.fixed .column-user_jetpack {
6024
					width: 21px;
6025
				}
6026
				.jp-emblem-user-admin path {
6027
					fill: #8cc258;
6028
				}
6029
			</style>
6030
		<?php }
6031
	}
6032
6033
}
6034