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