Completed
Push — fix/markdown-auto-enable ( d52805...e88b39 )
by
unknown
15:32
created

class.jetpack.php (14 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
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
26
27
class Jetpack {
28
	public $xmlrpc_server = null;
29
30
	private $xmlrpc_verification = null;
31
	private $rest_authentication_status = null;
32
33
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
34
35
	/**
36
	 * @var array The handles of styles that are concatenated into jetpack.css
37
	 */
38
	public $concatenated_style_handles = array(
39
		'jetpack-carousel',
40
		'grunion.css',
41
		'the-neverending-homepage',
42
		'jetpack_likes',
43
		'jetpack_related-posts',
44
		'sharedaddy',
45
		'jetpack-slideshow',
46
		'presentations',
47
		'jetpack-subscriptions',
48
		'jetpack-responsive-videos-style',
49
		'jetpack-social-menu',
50
		'tiled-gallery',
51
		'jetpack_display_posts_widget',
52
		'gravatar-profile-widget',
53
		'goodreads-widget',
54
		'jetpack_social_media_icons_widget',
55
		'jetpack-top-posts-widget',
56
		'jetpack_image_widget',
57
		'jetpack-my-community-widget',
58
		'wordads',
59
	);
60
61
	public $plugins_to_deactivate = array(
62
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
63
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
64
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
65
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
66
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
67
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
68
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
69
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
70
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
71
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
72
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
73
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
74
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
75
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
76
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
77
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
78
	);
79
80
	static $capability_translations = array(
81
		'administrator' => 'manage_options',
82
		'editor'        => 'edit_others_posts',
83
		'author'        => 'publish_posts',
84
		'contributor'   => 'edit_posts',
85
		'subscriber'    => 'read',
86
	);
87
88
	/**
89
	 * Map of modules that have conflicts with plugins and should not be auto-activated
90
	 * if the plugins are active.  Used by filter_default_modules
91
	 *
92
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
93
	 * change `module-slug` and add this to your plugin:
94
	 *
95
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
96
	 * function my_jetpack_get_default_modules( $modules ) {
97
	 *     return array_diff( $modules, array( 'module-slug' ) );
98
	 * }
99
	 *
100
	 * @var array
101
	 */
102
	private $conflicting_plugins = array(
103
		'comments'          => array(
104
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
105
			'Disqus'                               => 'disqus-comment-system/disqus.php',
106
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
107
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
108
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
109
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
110
		),
111
		'contact-form'      => array(
112
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
113
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
114
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
115
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
116
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
117
		),
118
		'minileven'         => array(
119
			'WPtouch'                              => 'wptouch/wptouch.php',
120
		),
121
		'latex'             => array(
122
			'LaTeX for WordPress'                  => 'latex/latex.php',
123
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
124
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
125
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
126
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
127
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
128
		),
129
		'protect'           => array(
130
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
131
			'Captcha'                              => 'captcha/captcha.php',
132
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
133
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
134
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
135
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
136
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
137
			'Security-protection'                  => 'security-protection/security-protection.php',
138
			'Login Security'                       => 'login-security/login-security.php',
139
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
140
			'Wordfence Security'                   => 'wordfence/wordfence.php',
141
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
142
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
143
		),
144
		'random-redirect'   => array(
145
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
146
		),
147
		'related-posts'     => array(
148
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
149
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
150
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
151
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
152
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
153
			'outbrain'                             => 'outbrain/outbrain.php',
154
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
155
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
156
		),
157
		'sharedaddy'        => array(
158
			'AddThis'                              => 'addthis/addthis_social_widget.php',
159
			'Add To Any'                           => 'add-to-any/add-to-any.php',
160
			'ShareThis'                            => 'share-this/sharethis.php',
161
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
162
		),
163
		'seo-tools' => array(
164
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
165
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
166
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
167
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
168
		),
169
		'verification-tools' => array(
170
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
171
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
172
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
173
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
174
		),
175
		'widget-visibility' => array(
176
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
177
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
178
		),
179
		'sitemaps' => array(
180
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
181
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
182
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
183
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
184
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
185
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
186
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
187
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
188
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
189
			'Sitemap'                              => 'sitemap/sitemap.php',
190
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
191
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
192
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
193
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
194
		),
195
	);
196
197
	/**
198
	 * Plugins for which we turn off our Facebook OG Tags implementation.
199
	 *
200
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
201
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
202
	 *
203
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
204
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
205
	 */
206
	private $open_graph_conflicting_plugins = array(
207
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
208
		                                                         // 2 Click Social Media Buttons
209
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
210
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
211
		'autodescription/autodescription.php',                   // The SEO Framework
212
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
213
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
214
		                                                         // Open Graph Meta Tags by Heateor
215
		'facebook/facebook.php',                                 // Facebook (official plugin)
216
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
217
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
218
		                                                         // Facebook Featured Image & OG Meta Tags
219
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
220
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
221
		                                                         // Facebook Open Graph Meta Tags for WordPress
222
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
223
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
224
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
225
		                                                         // Fedmich's Facebook Open Graph Meta
226
		'header-footer/plugin.php',                              // Header and Footer
227
		'network-publisher/networkpub.php',                      // Network Publisher
228
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
229
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
230
		                                                         // NextScripts SNAP
231
		'og-tags/og-tags.php',                                   // OG Tags
232
		'opengraph/opengraph.php',                               // Open Graph
233
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
234
		                                                         // Open Graph Protocol Framework
235
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
236
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
237
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
238
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
239
		'sharepress/sharepress.php',                             // SharePress
240
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
241
		'social-discussions/social-discussions.php',             // Social Discussions
242
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
243
		'socialize/socialize.php',                               // Socialize
244
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
245
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
246
		                                                         // Tweet, Like, Google +1 and Share
247
		'wordbooker/wordbooker.php',                             // Wordbooker
248
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
249
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
250
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
251
		                                                         // WP Facebook Like Send & Open Graph Meta
252
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
253
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
254
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
255
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
256
	);
257
258
	/**
259
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
260
	 */
261
	private $twitter_cards_conflicting_plugins = array(
262
	//	'twitter/twitter.php',                       // The official one handles this on its own.
263
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
264
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
265
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
266
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
267
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
268
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
269
		'twitter-cards/twitter-cards.php',           // Twitter Cards
270
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
271
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
272
	);
273
274
	/**
275
	 * Message to display in admin_notice
276
	 * @var string
277
	 */
278
	public $message = '';
279
280
	/**
281
	 * Error to display in admin_notice
282
	 * @var string
283
	 */
284
	public $error = '';
285
286
	/**
287
	 * Modules that need more privacy description.
288
	 * @var string
289
	 */
290
	public $privacy_checks = '';
291
292
	/**
293
	 * Stats to record once the page loads
294
	 *
295
	 * @var array
296
	 */
297
	public $stats = array();
298
299
	/**
300
	 * Jetpack_Sync object
301
	 */
302
	public $sync;
303
304
	/**
305
	 * Verified data for JSON authorization request
306
	 */
307
	public $json_api_authorization_request = array();
308
309
	/**
310
	 * Holds the singleton instance of this class
311
	 * @since 2.3.3
312
	 * @var Jetpack
313
	 */
314
	static $instance = false;
315
316
	/**
317
	 * Singleton
318
	 * @static
319
	 */
320
	public static function init() {
321
		if ( ! self::$instance ) {
322
			self::$instance = new Jetpack;
323
324
			self::$instance->plugin_upgrade();
325
		}
326
327
		return self::$instance;
328
	}
329
330
	/**
331
	 * Must never be called statically
332
	 */
333
	function plugin_upgrade() {
334
		if ( Jetpack::is_active() ) {
335
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
336
			if ( JETPACK__VERSION != $version ) {
337
338
				// Check which active modules actually exist and remove others from active_modules list
339
				$unfiltered_modules = Jetpack::get_active_modules();
340
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
341
				if ( array_diff( $unfiltered_modules, $modules ) ) {
342
					Jetpack::update_active_modules( $modules );
343
				}
344
345
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
346
347
				// Upgrade to 4.3.0
348
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
349
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
350
				}
351
352
				Jetpack::maybe_set_version_option();
353
			}
354
		}
355
	}
356
357
	static function activate_manage( ) {
358
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
359
			self::activate_module( 'manage', false, false );
360
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
361
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
362
		}
363
	}
364
365
	static function update_active_modules( $modules ) {
366
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
367
368
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
369
370
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
371
			$new_active_modules = array_diff( $modules, $current_modules );
372
			foreach( $new_active_modules as $module ) {
373
				/**
374
				 * Fires when a specific module is activated.
375
				 *
376
				 * @since 1.9.0
377
				 *
378
				 * @param string $module Module slug.
379
				 * @param boolean $success whether the module was activated. @since 4.2
380
				 */
381
				do_action( 'jetpack_activate_module', $module, $success );
382
383
				/**
384
				 * Fires when a module is activated.
385
				 * The dynamic part of the filter, $module, is the module slug.
386
				 *
387
				 * @since 1.9.0
388
				 *
389
				 * @param string $module Module slug.
390
				 */
391
				do_action( "jetpack_activate_module_$module", $module );
392
			}
393
394
			$new_deactive_modules = array_diff( $current_modules, $modules );
395
			foreach( $new_deactive_modules as $module ) {
396
				/**
397
				 * Fired after a module has been deactivated.
398
				 *
399
				 * @since 4.2.0
400
				 *
401
				 * @param string $module Module slug.
402
				 * @param boolean $success whether the module was deactivated.
403
				 */
404
				do_action( 'jetpack_deactivate_module', $module, $success );
405
				/**
406
				 * Fires when a module is deactivated.
407
				 * The dynamic part of the filter, $module, is the module slug.
408
				 *
409
				 * @since 1.9.0
410
				 *
411
				 * @param string $module Module slug.
412
				 */
413
				do_action( "jetpack_deactivate_module_$module", $module );
414
			}
415
		}
416
417
		return $success;
418
	}
419
420
	static function delete_active_modules() {
421
		self::update_active_modules( array() );
422
	}
423
424
	/**
425
	 * Constructor.  Initializes WordPress hooks
426
	 */
427
	private function __construct() {
428
		/*
429
		 * Check for and alert any deprecated hooks
430
		 */
431
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
432
433
		/*
434
		 * Load things that should only be in Network Admin.
435
		 *
436
		 * For now blow away everything else until a more full
437
		 * understanding of what is needed at the network level is
438
		 * available
439
		 */
440
		if( is_multisite() ) {
441
			Jetpack_Network::init();
442
		}
443
444
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
445
446
		// Unlink user before deleting the user from .com
447
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
448
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
449
450
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
451
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
452
453
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
454
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
455
456
			$this->require_jetpack_authentication();
457
458
			if ( Jetpack::is_active() ) {
459
				// Hack to preserve $HTTP_RAW_POST_DATA
460
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
461
462
				$signed = $this->verify_xml_rpc_signature();
463
				if ( $signed && ! is_wp_error( $signed ) ) {
464
					// The actual API methods.
465
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
466
				} else {
467
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
468
					// active Jetpack connection, so that additional users can link their account.
469
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
470
				}
471
			} else {
472
				// The bootstrap API methods.
473
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
474
			}
475
476
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
477
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
478
		} elseif (
479
			is_admin() &&
480
			isset( $_POST['action'] ) && (
481
				'jetpack_upload_file' == $_POST['action'] ||
482
				'jetpack_update_file' == $_POST['action']
483
			)
484
		) {
485
			$this->require_jetpack_authentication();
486
			$this->add_remote_request_handlers();
487
		} else {
488
			if ( Jetpack::is_active() ) {
489
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
490
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
491
			}
492
		}
493
494
		if ( Jetpack::is_active() ) {
495
			Jetpack_Heartbeat::init();
496
		}
497
498
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
499
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
500
501
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
502
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
503
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
504
		}
505
506
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
507
508
		add_action( 'admin_init', array( $this, 'admin_init' ) );
509
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
510
511
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
512
513
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
514
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
515
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
516
517
		// returns HTTPS support status
518
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
519
520
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
521
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
522
523
		// JITM AJAX callback function
524
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
525
526
		// Universal ajax callback for all tracking events triggered via js
527
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
528
529
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
530
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
531
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
532
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
533
534
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
535
536
		/**
537
		 * These actions run checks to load additional files.
538
		 * They check for external files or plugins, so they need to run as late as possible.
539
		 */
540
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
541
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
542
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
543
544
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
545
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
546
547
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
548
549
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
550
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
551
552
		// A filter to control all just in time messages
553
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
554
555
		// Update the Jetpack plan from API on heartbeats
556
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
557
558
		/**
559
		 * This is the hack to concatinate all css files into one.
560
		 * For description and reasoning see the implode_frontend_css method
561
		 *
562
		 * Super late priority so we catch all the registered styles
563
		 */
564
		if( !is_admin() ) {
565
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
566
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
567
		}
568
	}
569
570
	function jetpack_admin_ajax_tracks_callback() {
571
		// Check for nonce
572
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
573
			wp_die( 'Permissions check failed.' );
574
		}
575
576
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
577
			wp_die( 'No valid event name or type.' );
578
		}
579
580
		$tracks_data = array();
581
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
582
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
583
		}
584
585
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
586
		wp_send_json_success();
587
		wp_die();
588
	}
589
590
	/**
591
	 * The callback for the JITM ajax requests.
592
	 */
593
	function jetpack_jitm_ajax_callback() {
594
		// Check for nonce
595
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
596
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
597
		}
598
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
599
			$module_slug = $_REQUEST['jitmModule'];
600
			Jetpack::log( 'activate', $module_slug );
601
			Jetpack::activate_module( $module_slug, false, false );
602
			Jetpack::state( 'message', 'no_message' );
603
604
			//A Jetpack module is being activated through a JITM, track it
605
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
606
			$this->do_stats( 'server_side' );
607
608
			wp_send_json_success();
609
		}
610
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
611
			// get the hide_jitm options array
612
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
613
			$module_slug = $_REQUEST['jitmModule'];
614
615
			if( ! $jetpack_hide_jitm ) {
616
				$jetpack_hide_jitm = array(
617
					$module_slug => 'hide'
618
				);
619
			} else {
620
				$jetpack_hide_jitm[$module_slug] = 'hide';
621
			}
622
623
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
624
625
			//jitm is being dismissed forever, track it
626
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
627
			$this->do_stats( 'server_side' );
628
629
			wp_send_json_success();
630
		}
631 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
632
			$module_slug = $_REQUEST['jitmModule'];
633
634
			// User went to WordPress.com, track this
635
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
636
			$this->do_stats( 'server_side' );
637
638
			wp_send_json_success();
639
		}
640 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
641
			$track = $_REQUEST['jitmModule'];
642
643
			// User is viewing JITM, track it.
644
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
645
			$this->do_stats( 'server_side' );
646
647
			wp_send_json_success();
648
		}
649
	}
650
651
	/**
652
	 * If there are any stats that need to be pushed, but haven't been, push them now.
653
	 */
654
	function __destruct() {
655
		if ( ! empty( $this->stats ) ) {
656
			$this->do_stats( 'server_side' );
657
		}
658
	}
659
660
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
661
		switch( $cap ) {
662
			case 'jetpack_connect' :
663
			case 'jetpack_reconnect' :
664
				if ( Jetpack::is_development_mode() ) {
665
					$caps = array( 'do_not_allow' );
666
					break;
667
				}
668
				/**
669
				 * Pass through. If it's not development mode, these should match disconnect.
670
				 * Let users disconnect if it's development mode, just in case things glitch.
671
				 */
672
			case 'jetpack_disconnect' :
673
				/**
674
				 * In multisite, can individual site admins manage their own connection?
675
				 *
676
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
677
				 */
678
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
679
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
680
						/**
681
						 * We need to update the option name -- it's terribly unclear which
682
						 * direction the override goes.
683
						 *
684
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
685
						 */
686
						$caps = array( 'do_not_allow' );
687
						break;
688
					}
689
				}
690
691
				$caps = array( 'manage_options' );
692
				break;
693
			case 'jetpack_manage_modules' :
694
			case 'jetpack_activate_modules' :
695
			case 'jetpack_deactivate_modules' :
696
				$caps = array( 'manage_options' );
697
				break;
698
			case 'jetpack_configure_modules' :
699
				$caps = array( 'manage_options' );
700
				break;
701
			case 'jetpack_network_admin_page':
702
			case 'jetpack_network_settings_page':
703
				$caps = array( 'manage_network_plugins' );
704
				break;
705
			case 'jetpack_network_sites_page':
706
				$caps = array( 'manage_sites' );
707
				break;
708
			case 'jetpack_admin_page' :
709
				if ( Jetpack::is_development_mode() ) {
710
					$caps = array( 'manage_options' );
711
					break;
712
				} else {
713
					$caps = array( 'read' );
714
				}
715
				break;
716
			case 'jetpack_connect_user' :
717
				if ( Jetpack::is_development_mode() ) {
718
					$caps = array( 'do_not_allow' );
719
					break;
720
				}
721
				$caps = array( 'read' );
722
				break;
723
		}
724
		return $caps;
725
	}
726
727
	function require_jetpack_authentication() {
728
		// Don't let anyone authenticate
729
		$_COOKIE = array();
730
		remove_all_filters( 'authenticate' );
731
		remove_all_actions( 'wp_login_failed' );
732
733
		if ( Jetpack::is_active() ) {
734
			// Allow Jetpack authentication
735
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
736
		}
737
	}
738
739
	/**
740
	 * Load language files
741
	 * @action plugins_loaded
742
	 */
743
	public static function plugin_textdomain() {
744
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
745
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
746
	}
747
748
	/**
749
	 * Register assets for use in various modules and the Jetpack admin page.
750
	 *
751
	 * @uses wp_script_is, wp_register_script, plugins_url
752
	 * @action wp_loaded
753
	 * @return null
754
	 */
755
	public function register_assets() {
756
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
757
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
758
		}
759
760 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
761
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
762
		}
763
764 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
765
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
766
		}
767
768 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
769
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
770
		}
771
772
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
773
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
774
775
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
776
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
777
			if ( ! is_numeric( $fb_app_id ) ) {
778
				$fb_app_id = '';
779
			}
780
			wp_localize_script(
781
				'jetpack-facebook-embed',
782
				'jpfbembed',
783
				array(
784
					'appid' => $fb_app_id,
785
					'locale' => $this->get_locale(),
786
				)
787
			);
788
		}
789
790
		/**
791
		 * As jetpack_register_genericons is by default fired off a hook,
792
		 * the hook may have already fired by this point.
793
		 * So, let's just trigger it manually.
794
		 */
795
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
796
		jetpack_register_genericons();
797
798
		/**
799
		 * Register the social logos
800
		 */
801
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
802
		jetpack_register_social_logos();
803
804 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
805
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
806
	}
807
808
	/**
809
	 * Guess locale from language code.
810
	 *
811
	 * @param string $lang Language code.
812
	 * @return string|bool
813
	 */
814 View Code Duplication
	function guess_locale_from_lang( $lang ) {
815
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
816
			return 'en_US';
817
		}
818
819
		if ( ! class_exists( 'GP_Locales' ) ) {
820
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
821
				return false;
822
			}
823
824
			require JETPACK__GLOTPRESS_LOCALES_PATH;
825
		}
826
827
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
828
			// WP.com: get_locale() returns 'it'
829
			$locale = GP_Locales::by_slug( $lang );
830
		} else {
831
			// Jetpack: get_locale() returns 'it_IT';
832
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
833
		}
834
835
		if ( ! $locale ) {
836
			return false;
837
		}
838
839
		if ( empty( $locale->facebook_locale ) ) {
840
			if ( empty( $locale->wp_locale ) ) {
841
				return false;
842
			} else {
843
				// Facebook SDK is smart enough to fall back to en_US if a
844
				// locale isn't supported. Since supported Facebook locales
845
				// can fall out of sync, we'll attempt to use the known
846
				// wp_locale value and rely on said fallback.
847
				return $locale->wp_locale;
848
			}
849
		}
850
851
		return $locale->facebook_locale;
852
	}
853
854
	/**
855
	 * Get the locale.
856
	 *
857
	 * @return string|bool
858
	 */
859
	function get_locale() {
860
		$locale = $this->guess_locale_from_lang( get_locale() );
861
862
		if ( ! $locale ) {
863
			$locale = 'en_US';
864
		}
865
866
		return $locale;
867
	}
868
869
	/**
870
	 * Device Pixels support
871
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
872
	 */
873
	function devicepx() {
874
		if ( Jetpack::is_active() ) {
875
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
876
		}
877
	}
878
879
	/**
880
	 * Return the network_site_url so that .com knows what network this site is a part of.
881
	 * @param  bool $option
882
	 * @return string
883
	 */
884
	public function jetpack_main_network_site_option( $option ) {
885
		return network_site_url();
886
	}
887
	/**
888
	 * Network Name.
889
	 */
890
	static function network_name( $option = null ) {
891
		global $current_site;
892
		return $current_site->site_name;
893
	}
894
	/**
895
	 * Does the network allow new user and site registrations.
896
	 * @return string
897
	 */
898
	static function network_allow_new_registrations( $option = null ) {
899
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
900
	}
901
	/**
902
	 * Does the network allow admins to add new users.
903
	 * @return boolian
904
	 */
905
	static function network_add_new_users( $option = null ) {
906
		return (bool) get_site_option( 'add_new_users' );
907
	}
908
	/**
909
	 * File upload psace left per site in MB.
910
	 *  -1 means NO LIMIT.
911
	 * @return number
912
	 */
913
	static function network_site_upload_space( $option = null ) {
914
		// value in MB
915
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
916
	}
917
918
	/**
919
	 * Network allowed file types.
920
	 * @return string
921
	 */
922
	static function network_upload_file_types( $option = null ) {
923
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
924
	}
925
926
	/**
927
	 * Maximum file upload size set by the network.
928
	 * @return number
929
	 */
930
	static function network_max_upload_file_size( $option = null ) {
931
		// value in KB
932
		return get_site_option( 'fileupload_maxk', 300 );
933
	}
934
935
	/**
936
	 * Lets us know if a site allows admins to manage the network.
937
	 * @return array
938
	 */
939
	static function network_enable_administration_menus( $option = null ) {
940
		return get_site_option( 'menu_items' );
941
	}
942
943
	/**
944
	 * If a user has been promoted to or demoted from admin, we need to clear the
945
	 * jetpack_other_linked_admins transient.
946
	 *
947
	 * @since 4.3.2
948
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
949
	 *
950
	 * @param int    $user_id   The user ID whose role changed.
951
	 * @param string $role      The new role.
952
	 * @param array  $old_roles An array of the user's previous roles.
953
	 */
954
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
955
		if ( 'administrator' == $role
956
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
957
			|| is_null( $old_roles )
958
		) {
959
			delete_transient( 'jetpack_other_linked_admins' );
960
		}
961
	}
962
963
	/**
964
	 * Checks to see if there are any other users available to become primary
965
	 * Users must both:
966
	 * - Be linked to wpcom
967
	 * - Be an admin
968
	 *
969
	 * @return mixed False if no other users are linked, Int if there are.
970
	 */
971
	static function get_other_linked_admins() {
972
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
973
974
		if ( false === $other_linked_users ) {
975
			$admins = get_users( array( 'role' => 'administrator' ) );
976
			if ( count( $admins ) > 1 ) {
977
				$available = array();
978
				foreach ( $admins as $admin ) {
979
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
980
						$available[] = $admin->ID;
981
					}
982
				}
983
984
				$count_connected_admins = count( $available );
985
				if ( count( $available ) > 1 ) {
986
					$other_linked_users = $count_connected_admins;
987
				} else {
988
					$other_linked_users = 0;
989
				}
990
			} else {
991
				$other_linked_users = 0;
992
			}
993
994
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
995
		}
996
997
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
998
	}
999
1000
	/**
1001
	 * Return whether we are dealing with a multi network setup or not.
1002
	 * The reason we are type casting this is because we want to avoid the situation where
1003
	 * the result is false since when is_main_network_option return false it cases
1004
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1005
	 * database which could be set to anything as opposed to what this function returns.
1006
	 * @param  bool  $option
1007
	 *
1008
	 * @return boolean
1009
	 */
1010
	public function is_main_network_option( $option ) {
1011
		// return '1' or ''
1012
		return (string) (bool) Jetpack::is_multi_network();
1013
	}
1014
1015
	/**
1016
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1017
	 *
1018
	 * @param  string  $option
1019
	 * @return boolean
1020
	 */
1021
	public function is_multisite( $option ) {
1022
		return (string) (bool) is_multisite();
1023
	}
1024
1025
	/**
1026
	 * Implemented since there is no core is multi network function
1027
	 * Right now there is no way to tell if we which network is the dominant network on the system
1028
	 *
1029
	 * @since  3.3
1030
	 * @return boolean
1031
	 */
1032
	public static function is_multi_network() {
1033
		global  $wpdb;
1034
1035
		// if we don't have a multi site setup no need to do any more
1036
		if ( ! is_multisite() ) {
1037
			return false;
1038
		}
1039
1040
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1041
		if ( $num_sites > 1 ) {
1042
			return true;
1043
		} else {
1044
			return false;
1045
		}
1046
	}
1047
1048
	/**
1049
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1050
	 * @return null
1051
	 */
1052
	function update_jetpack_main_network_site_option() {
1053
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1054
	}
1055
	/**
1056
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1057
	 *
1058
	 */
1059
	function update_jetpack_network_settings() {
1060
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1061
		// Only sync this info for the main network site.
1062
	}
1063
1064
	/**
1065
	 * Get back if the current site is single user site.
1066
	 *
1067
	 * @return bool
1068
	 */
1069
	public static function is_single_user_site() {
1070
		global $wpdb;
1071
1072 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1073
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1074
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1075
		}
1076
		return 1 === (int) $some_users;
1077
	}
1078
1079
	/**
1080
	 * Returns true if the site has file write access false otherwise.
1081
	 * @return string ( '1' | '0' )
1082
	 **/
1083
	public static function file_system_write_access() {
1084
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1085
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1086
		}
1087
1088
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1089
1090
		$filesystem_method = get_filesystem_method();
1091
		if ( $filesystem_method === 'direct' ) {
1092
			return 1;
1093
		}
1094
1095
		ob_start();
1096
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1097
		ob_end_clean();
1098
		if ( $filesystem_credentials_are_stored ) {
1099
			return 1;
1100
		}
1101
		return 0;
1102
	}
1103
1104
	/**
1105
	 * Finds out if a site is using a version control system.
1106
	 * @return string ( '1' | '0' )
1107
	 **/
1108
	public static function is_version_controlled() {
1109
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1110
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1111
	}
1112
1113
	/**
1114
	 * Determines whether the current theme supports featured images or not.
1115
	 * @return string ( '1' | '0' )
1116
	 */
1117
	public static function featured_images_enabled() {
1118
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1119
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1120
	}
1121
1122
	/**
1123
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1124
	 *
1125
	 * @deprecated 4.7 use get_avatar_url instead.
1126
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1127
	 * @param int $size Size of the avatar image
1128
	 * @param string $default URL to a default image to use if no avatar is available
1129
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1130
	 *
1131
	 * @return array
1132
	 */
1133
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1134
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1135
		return get_avatar_url( $id_or_email, array(
1136
			'size' => $size,
1137
			'default' => $default,
1138
			'force_default' => $force_display,
1139
		) );
1140
	}
1141
1142
	/**
1143
	 * jetpack_updates is saved in the following schema:
1144
	 *
1145
	 * array (
1146
	 *      'plugins'                       => (int) Number of plugin updates available.
1147
	 *      'themes'                        => (int) Number of theme updates available.
1148
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1149
	 *      'translations'                  => (int) Number of translation updates available.
1150
	 *      'total'                         => (int) Total of all available updates.
1151
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1152
	 * )
1153
	 * @return array
1154
	 */
1155
	public static function get_updates() {
1156
		$update_data = wp_get_update_data();
1157
1158
		// Stores the individual update counts as well as the total count.
1159
		if ( isset( $update_data['counts'] ) ) {
1160
			$updates = $update_data['counts'];
1161
		}
1162
1163
		// If we need to update WordPress core, let's find the latest version number.
1164 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1165
			$cur = get_preferred_from_update_core();
1166
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1167
				$updates['wp_update_version'] = $cur->current;
1168
			}
1169
		}
1170
		return isset( $updates ) ? $updates : array();
1171
	}
1172
1173
	public static function get_update_details() {
1174
		$update_details = array(
1175
			'update_core' => get_site_transient( 'update_core' ),
1176
			'update_plugins' => get_site_transient( 'update_plugins' ),
1177
			'update_themes' => get_site_transient( 'update_themes' ),
1178
		);
1179
		return $update_details;
1180
	}
1181
1182
	public static function refresh_update_data() {
1183
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1184
1185
	}
1186
1187
	public static function refresh_theme_data() {
1188
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1189
	}
1190
1191
	/**
1192
	 * Is Jetpack active?
1193
	 */
1194
	public static function is_active() {
1195
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1196
	}
1197
1198
	/**
1199
	 * Make an API call to WordPress.com for plan status
1200
	 *
1201
	 * @uses Jetpack_Options::get_option()
1202
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1203
	 * @uses update_option()
1204
	 *
1205
	 * @access public
1206
	 * @static
1207
	 *
1208
	 * @return bool True if plan is updated, false if no update
1209
	 */
1210
	public static function refresh_active_plan_from_wpcom() {
1211
		// Make the API request
1212
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1213
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1214
1215
		// Bail if there was an error or malformed response
1216
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1217
			return false;
1218
		}
1219
1220
		// Decode the results
1221
		$results = json_decode( $response['body'], true );
1222
1223
		// Bail if there were no results or plan details returned
1224
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1225
			return false;
1226
		}
1227
1228
		// Store the option and return true if updated
1229
		return update_option( 'jetpack_active_plan', $results['plan'] );
1230
	}
1231
1232
	/**
1233
	 * Get the plan that this Jetpack site is currently using
1234
	 *
1235
	 * @uses get_option()
1236
	 *
1237
	 * @access public
1238
	 * @static
1239
	 *
1240
	 * @return array Active Jetpack plan details
1241
	 */
1242
	public static function get_active_plan() {
1243
		$plan = get_option( 'jetpack_active_plan' );
1244
1245
		// Set the default options
1246
		if ( ! $plan ) {
1247
			$plan = array(
1248
				'product_slug' => 'jetpack_free',
1249
				'supports'     => array(),
1250
				'class'        => 'free',
1251
			);
1252
		}
1253
1254
		// Define what paid modules are supported by personal plans
1255
		$personal_plans = array(
1256
			'jetpack_personal',
1257
			'jetpack_personal_monthly',
1258
		);
1259
1260
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1261
			$plan['supports'] = array(
1262
				'akismet',
1263
			);
1264
			$plan['class'] = 'personal';
1265
		}
1266
1267
		// Define what paid modules are supported by premium plans
1268
		$premium_plans = array(
1269
			'jetpack_premium',
1270
			'jetpack_premium_monthly',
1271
		);
1272
1273 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1274
			$plan['supports'] = array(
1275
				'videopress',
1276
				'akismet',
1277
				'vaultpress',
1278
				'wordads',
1279
			);
1280
			$plan['class'] = 'premium';
1281
		}
1282
1283
		// Define what paid modules are supported by professional plans
1284
		$business_plans = array(
1285
			'jetpack_business',
1286
			'jetpack_business_monthly',
1287
		);
1288
1289 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1290
			$plan['supports'] = array(
1291
				'videopress',
1292
				'akismet',
1293
				'vaultpress',
1294
				'seo-tools',
1295
				'google-analytics',
1296
				'wordads',
1297
			);
1298
			$plan['class'] = 'business';
1299
		}
1300
1301
		// Make sure we have an array here in the event database data is stale
1302
		if ( ! isset( $plan['supports'] ) ) {
1303
			$plan['supports'] = array();
1304
		}
1305
1306
		return $plan;
1307
	}
1308
1309
	/**
1310
	 * Determine whether the active plan supports a particular feature
1311
	 *
1312
	 * @uses Jetpack::get_active_plan()
1313
	 *
1314
	 * @access public
1315
	 * @static
1316
	 *
1317
	 * @return bool True if plan supports feature, false if not
1318
	 */
1319
	public static function active_plan_supports( $feature ) {
1320
		$plan = Jetpack::get_active_plan();
1321
1322
		if ( in_array( $feature, $plan['supports'] ) ) {
1323
			return true;
1324
		}
1325
1326
		return false;
1327
	}
1328
1329
	/**
1330
	 * Is Jetpack in development (offline) mode?
1331
	 */
1332
	public static function is_development_mode() {
1333
		$development_mode = false;
1334
1335
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1336
			$development_mode = JETPACK_DEV_DEBUG;
1337
		} elseif ( $site_url = site_url() ) {
1338
			$development_mode = false === strpos( $site_url, '.' );
1339
		}
1340
1341
		/**
1342
		 * Filters Jetpack's development mode.
1343
		 *
1344
		 * @see https://jetpack.com/support/development-mode/
1345
		 *
1346
		 * @since 2.2.1
1347
		 *
1348
		 * @param bool $development_mode Is Jetpack's development mode active.
1349
		 */
1350
		return apply_filters( 'jetpack_development_mode', $development_mode );
1351
	}
1352
1353
	/**
1354
	* Get Jetpack development mode notice text and notice class.
1355
	*
1356
	* Mirrors the checks made in Jetpack::is_development_mode
1357
	*
1358
	*/
1359
	public static function show_development_mode_notice() {
1360
		if ( Jetpack::is_development_mode() ) {
1361
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1362
				$notice = sprintf(
1363
					/* translators: %s is a URL */
1364
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1365
					'https://jetpack.com/support/development-mode/'
1366
				);
1367
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1368
				$notice = sprintf(
1369
					/* translators: %s is a URL */
1370
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1371
					'https://jetpack.com/support/development-mode/'
1372
				);
1373
			} else {
1374
				$notice = sprintf(
1375
					/* translators: %s is a URL */
1376
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1377
					'https://jetpack.com/support/development-mode/'
1378
				);
1379
			}
1380
1381
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1382
		}
1383
1384
		// Throw up a notice if using a development version and as for feedback.
1385
		if ( Jetpack::is_development_version() ) {
1386
			/* translators: %s is a URL */
1387
			$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/' );
1388
1389
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1390
		}
1391
		// Throw up a notice if using staging mode
1392
		if ( Jetpack::is_staging_site() ) {
1393
			/* translators: %s is a URL */
1394
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1395
1396
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1397
		}
1398
	}
1399
1400
	/**
1401
	 * Whether Jetpack's version maps to a public release, or a development version.
1402
	 */
1403
	public static function is_development_version() {
1404
		/**
1405
		 * Allows filtering whether this is a development version of Jetpack.
1406
		 *
1407
		 * This filter is especially useful for tests.
1408
		 *
1409
		 * @since 4.3.0
1410
		 *
1411
		 * @param bool $development_version Is this a develoment version of Jetpack?
1412
		 */
1413
		return (bool) apply_filters(
1414
			'jetpack_development_version',
1415
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1416
		);
1417
	}
1418
1419
	/**
1420
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1421
	 */
1422
	public static function is_user_connected( $user_id = false ) {
1423
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1424
		if ( ! $user_id ) {
1425
			return false;
1426
		}
1427
1428
		return (bool) Jetpack_Data::get_access_token( $user_id );
1429
	}
1430
1431
	/**
1432
	 * Get the wpcom user data of the current|specified connected user.
1433
	 */
1434
	public static function get_connected_user_data( $user_id = null ) {
1435
		if ( ! $user_id ) {
1436
			$user_id = get_current_user_id();
1437
		}
1438
1439
		$transient_key = "jetpack_connected_user_data_$user_id";
1440
1441
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1442
			return $cached_user_data;
1443
		}
1444
1445
		Jetpack::load_xml_rpc_client();
1446
		$xml = new Jetpack_IXR_Client( array(
1447
			'user_id' => $user_id,
1448
		) );
1449
		$xml->query( 'wpcom.getUser' );
1450
		if ( ! $xml->isError() ) {
1451
			$user_data = $xml->getResponse();
1452
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1453
			return $user_data;
1454
		}
1455
1456
		return false;
1457
	}
1458
1459
	/**
1460
	 * Get the wpcom email of the current|specified connected user.
1461
	 */
1462 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1463
		if ( ! $user_id ) {
1464
			$user_id = get_current_user_id();
1465
		}
1466
		Jetpack::load_xml_rpc_client();
1467
		$xml = new Jetpack_IXR_Client( array(
1468
			'user_id' => $user_id,
1469
		) );
1470
		$xml->query( 'wpcom.getUserEmail' );
1471
		if ( ! $xml->isError() ) {
1472
			return $xml->getResponse();
1473
		}
1474
		return false;
1475
	}
1476
1477
	/**
1478
	 * Get the wpcom email of the master user.
1479
	 */
1480
	public static function get_master_user_email() {
1481
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1482
		if ( $master_user_id ) {
1483
			return self::get_connected_user_email( $master_user_id );
1484
		}
1485
		return '';
1486
	}
1487
1488
	function current_user_is_connection_owner() {
1489
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1490
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1491
	}
1492
1493
	/**
1494
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1495
	 */
1496
	function extra_oembed_providers() {
1497
		// Cloudup: https://dev.cloudup.com/#oembed
1498
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1499
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1500
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1501
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1502
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1503
	}
1504
1505
	/**
1506
	 * Synchronize connected user role changes
1507
	 */
1508
	function user_role_change( $user_id ) {
1509
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1510
		Jetpack_Sync_Users::user_role_change( $user_id );
1511
	}
1512
1513
	/**
1514
	 * Loads the currently active modules.
1515
	 */
1516
	public static function load_modules() {
1517
		if ( ! self::is_active() && !self::is_development_mode() ) {
1518
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1519
				return;
1520
			}
1521
		}
1522
1523
		$version = Jetpack_Options::get_option( 'version' );
1524 View Code Duplication
		if ( ! $version ) {
1525
			$version = $old_version = JETPACK__VERSION . ':' . time();
1526
			/** This action is documented in class.jetpack.php */
1527
			do_action( 'updating_jetpack_version', $version, false );
1528
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1529
		}
1530
		list( $version ) = explode( ':', $version );
1531
1532
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1533
1534
		$modules_data = array();
1535
1536
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1537
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1538
			$updated_modules = array();
1539
			foreach ( $modules as $module ) {
1540
				$modules_data[ $module ] = Jetpack::get_module( $module );
1541
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1542
					continue;
1543
				}
1544
1545
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1546
					continue;
1547
				}
1548
1549
				$updated_modules[] = $module;
1550
			}
1551
1552
			$modules = array_diff( $modules, $updated_modules );
1553
		}
1554
1555
		$is_development_mode = Jetpack::is_development_mode();
1556
1557
		foreach ( $modules as $index => $module ) {
1558
			// If we're in dev mode, disable modules requiring a connection
1559
			if ( $is_development_mode ) {
1560
				// Prime the pump if we need to
1561
				if ( empty( $modules_data[ $module ] ) ) {
1562
					$modules_data[ $module ] = Jetpack::get_module( $module );
1563
				}
1564
				// If the module requires a connection, but we're in local mode, don't include it.
1565
				if ( $modules_data[ $module ]['requires_connection'] ) {
1566
					continue;
1567
				}
1568
			}
1569
1570
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1571
				continue;
1572
			}
1573
1574
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1575
				unset( $modules[ $index ] );
1576
				self::update_active_modules( array_values( $modules ) );
1577
				continue;
1578
			}
1579
1580
			/**
1581
			 * Fires when a specific module is loaded.
1582
			 * The dynamic part of the hook, $module, is the module slug.
1583
			 *
1584
			 * @since 1.1.0
1585
			 */
1586
			do_action( 'jetpack_module_loaded_' . $module );
1587
		}
1588
1589
		/**
1590
		 * Fires when all the modules are loaded.
1591
		 *
1592
		 * @since 1.1.0
1593
		 */
1594
		do_action( 'jetpack_modules_loaded' );
1595
1596
		// 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.
1597
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1598
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1599
	}
1600
1601
	/**
1602
	 * Check if Jetpack's REST API compat file should be included
1603
	 * @action plugins_loaded
1604
	 * @return null
1605
	 */
1606
	public function check_rest_api_compat() {
1607
		/**
1608
		 * Filters the list of REST API compat files to be included.
1609
		 *
1610
		 * @since 2.2.5
1611
		 *
1612
		 * @param array $args Array of REST API compat files to include.
1613
		 */
1614
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1615
1616
		if ( function_exists( 'bbpress' ) )
1617
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1618
1619
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1620
			require_once $_jetpack_rest_api_compat_include;
1621
	}
1622
1623
	/**
1624
	 * Gets all plugins currently active in values, regardless of whether they're
1625
	 * traditionally activated or network activated.
1626
	 *
1627
	 * @todo Store the result in core's object cache maybe?
1628
	 */
1629
	public static function get_active_plugins() {
1630
		$active_plugins = (array) get_option( 'active_plugins', array() );
1631
1632
		if ( is_multisite() ) {
1633
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1634
			// whereas active_plugins stores them in the values.
1635
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1636
			if ( $network_plugins ) {
1637
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1638
			}
1639
		}
1640
1641
		sort( $active_plugins );
1642
1643
		return array_unique( $active_plugins );
1644
	}
1645
1646
	/**
1647
	 * Gets and parses additional plugin data to send with the heartbeat data
1648
	 *
1649
	 * @since 3.8.1
1650
	 *
1651
	 * @return array Array of plugin data
1652
	 */
1653
	public static function get_parsed_plugin_data() {
1654
		if ( ! function_exists( 'get_plugins' ) ) {
1655
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1656
		}
1657
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1658
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1659
		$active_plugins = Jetpack::get_active_plugins();
1660
1661
		$plugins = array();
1662
		foreach ( $all_plugins as $path => $plugin_data ) {
1663
			$plugins[ $path ] = array(
1664
					'is_active' => in_array( $path, $active_plugins ),
1665
					'file'      => $path,
1666
					'name'      => $plugin_data['Name'],
1667
					'version'   => $plugin_data['Version'],
1668
					'author'    => $plugin_data['Author'],
1669
			);
1670
		}
1671
1672
		return $plugins;
1673
	}
1674
1675
	/**
1676
	 * Gets and parses theme data to send with the heartbeat data
1677
	 *
1678
	 * @since 3.8.1
1679
	 *
1680
	 * @return array Array of theme data
1681
	 */
1682
	public static function get_parsed_theme_data() {
1683
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1684
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1685
1686
		$themes = array();
1687
		foreach ( $all_themes as $slug => $theme_data ) {
1688
			$theme_headers = array();
1689
			foreach ( $header_keys as $header_key ) {
1690
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1691
			}
1692
1693
			$themes[ $slug ] = array(
1694
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1695
					'slug' => $slug,
1696
					'theme_root' => $theme_data->get_theme_root_uri(),
1697
					'parent' => $theme_data->parent(),
1698
					'headers' => $theme_headers
1699
			);
1700
		}
1701
1702
		return $themes;
1703
	}
1704
1705
	/**
1706
	 * Checks whether a specific plugin is active.
1707
	 *
1708
	 * We don't want to store these in a static variable, in case
1709
	 * there are switch_to_blog() calls involved.
1710
	 */
1711
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1712
		return in_array( $plugin, self::get_active_plugins() );
1713
	}
1714
1715
	/**
1716
	 * Check if Jetpack's Open Graph tags should be used.
1717
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1718
	 *
1719
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1720
	 * @action plugins_loaded
1721
	 * @return null
1722
	 */
1723
	public function check_open_graph() {
1724
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1725
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1726
		}
1727
1728
		$active_plugins = self::get_active_plugins();
1729
1730
		if ( ! empty( $active_plugins ) ) {
1731
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1732
				if ( in_array( $plugin, $active_plugins ) ) {
1733
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1734
					break;
1735
				}
1736
			}
1737
		}
1738
1739
		/**
1740
		 * Allow the addition of Open Graph Meta Tags to all pages.
1741
		 *
1742
		 * @since 2.0.3
1743
		 *
1744
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1745
		 */
1746
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1747
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1748
		}
1749
	}
1750
1751
	/**
1752
	 * Check if Jetpack's Twitter tags should be used.
1753
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1754
	 *
1755
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1756
	 * @action plugins_loaded
1757
	 * @return null
1758
	 */
1759
	public function check_twitter_tags() {
1760
1761
		$active_plugins = self::get_active_plugins();
1762
1763
		if ( ! empty( $active_plugins ) ) {
1764
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1765
				if ( in_array( $plugin, $active_plugins ) ) {
1766
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1767
					break;
1768
				}
1769
			}
1770
		}
1771
1772
		/**
1773
		 * Allow Twitter Card Meta tags to be disabled.
1774
		 *
1775
		 * @since 2.6.0
1776
		 *
1777
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1778
		 */
1779
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1780
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1781
		}
1782
	}
1783
1784
	/**
1785
	 * Allows plugins to submit security reports.
1786
 	 *
1787
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1788
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1789
	 * @param array   $args         See definitions above
1790
	 */
1791
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1792
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1793
	}
1794
1795
/* Jetpack Options API */
1796
1797
	public static function get_option_names( $type = 'compact' ) {
1798
		return Jetpack_Options::get_option_names( $type );
1799
	}
1800
1801
	/**
1802
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1803
 	 *
1804
	 * @param string $name    Option name
1805
	 * @param mixed  $default (optional)
1806
	 */
1807
	public static function get_option( $name, $default = false ) {
1808
		return Jetpack_Options::get_option( $name, $default );
1809
	}
1810
1811
	/**
1812
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1813
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1814
	* $name must be a registered option name.
1815
	*/
1816
	public static function create_nonce( $name ) {
1817
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1818
1819
		Jetpack_Options::update_option( $name, $secret );
1820
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1821
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1822
			return new Jetpack_Error( 'missing_secrets' );
1823
1824
		return array(
1825
			'secret_1' => $secret_1,
1826
			'secret_2' => $secret_2,
1827
			'eol'      => $eol,
1828
		);
1829
	}
1830
1831
	/**
1832
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1833
 	 *
1834
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1835
	 * @param string $name  Option name
1836
	 * @param mixed  $value Option value
1837
	 */
1838
	public static function update_option( $name, $value ) {
1839
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1840
		return Jetpack_Options::update_option( $name, $value );
1841
	}
1842
1843
	/**
1844
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1845
 	 *
1846
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1847
	 * @param array $array array( option name => option value, ... )
1848
	 */
1849
	public static function update_options( $array ) {
1850
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1851
		return Jetpack_Options::update_options( $array );
1852
	}
1853
1854
	/**
1855
	 * Deletes the given option.  May be passed multiple option names as an array.
1856
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1857
	 *
1858
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1859
	 * @param string|array $names
1860
	 */
1861
	public static function delete_option( $names ) {
1862
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1863
		return Jetpack_Options::delete_option( $names );
1864
	}
1865
1866
	/**
1867
	 * Enters a user token into the user_tokens option
1868
	 *
1869
	 * @param int $user_id
1870
	 * @param string $token
1871
	 * return bool
1872
	 */
1873
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1874
		// not designed for concurrent updates
1875
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1876
		if ( ! is_array( $user_tokens ) )
1877
			$user_tokens = array();
1878
		$user_tokens[$user_id] = $token;
1879
		if ( $is_master_user ) {
1880
			$master_user = $user_id;
1881
			$options     = compact( 'user_tokens', 'master_user' );
1882
		} else {
1883
			$options = compact( 'user_tokens' );
1884
		}
1885
		return Jetpack_Options::update_options( $options );
1886
	}
1887
1888
	/**
1889
	 * Returns an array of all PHP files in the specified absolute path.
1890
	 * Equivalent to glob( "$absolute_path/*.php" ).
1891
	 *
1892
	 * @param string $absolute_path The absolute path of the directory to search.
1893
	 * @return array Array of absolute paths to the PHP files.
1894
	 */
1895
	public static function glob_php( $absolute_path ) {
1896
		if ( function_exists( 'glob' ) ) {
1897
			return glob( "$absolute_path/*.php" );
1898
		}
1899
1900
		$absolute_path = untrailingslashit( $absolute_path );
1901
		$files = array();
1902
		if ( ! $dir = @opendir( $absolute_path ) ) {
1903
			return $files;
1904
		}
1905
1906
		while ( false !== $file = readdir( $dir ) ) {
1907
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1908
				continue;
1909
			}
1910
1911
			$file = "$absolute_path/$file";
1912
1913
			if ( ! is_file( $file ) ) {
1914
				continue;
1915
			}
1916
1917
			$files[] = $file;
1918
		}
1919
1920
		closedir( $dir );
1921
1922
		return $files;
1923
	}
1924
1925
	public static function activate_new_modules( $redirect = false ) {
1926
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1927
			return;
1928
		}
1929
1930
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1931 View Code Duplication
		if ( ! $jetpack_old_version ) {
1932
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1933
			/** This action is documented in class.jetpack.php */
1934
			do_action( 'updating_jetpack_version', $version, false );
1935
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1936
		}
1937
1938
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1939
1940
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1941
			return;
1942
		}
1943
1944
		$active_modules     = Jetpack::get_active_modules();
1945
		$reactivate_modules = array();
1946
		foreach ( $active_modules as $active_module ) {
1947
			$module = Jetpack::get_module( $active_module );
1948
			if ( ! isset( $module['changed'] ) ) {
1949
				continue;
1950
			}
1951
1952
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1953
				continue;
1954
			}
1955
1956
			$reactivate_modules[] = $active_module;
1957
			Jetpack::deactivate_module( $active_module );
1958
		}
1959
1960
		$new_version = JETPACK__VERSION . ':' . time();
1961
		/** This action is documented in class.jetpack.php */
1962
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1963
		Jetpack_Options::update_options(
1964
			array(
1965
				'version'     => $new_version,
1966
				'old_version' => $jetpack_old_version,
1967
			)
1968
		);
1969
1970
		Jetpack::state( 'message', 'modules_activated' );
1971
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
1972
1973
		if ( $redirect ) {
1974
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1975
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1976
				$page = $_GET['page'];
1977
			}
1978
1979
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1980
			exit;
1981
		}
1982
	}
1983
1984
	/**
1985
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1986
	 * Make sure to tuck away module "library" files in a sub-directory.
1987
	 */
1988
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1989
		static $modules = null;
1990
1991
		if ( ! isset( $modules ) ) {
1992
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1993
			// Use the cache if we're on the front-end and it's available...
1994
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1995
				$modules = $available_modules_option[ JETPACK__VERSION ];
1996
			} else {
1997
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1998
1999
				$modules = array();
2000
2001
				foreach ( $files as $file ) {
2002
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2003
						continue;
2004
					}
2005
2006
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2007
				}
2008
2009
				Jetpack_Options::update_option( 'available_modules', array(
2010
					JETPACK__VERSION => $modules,
2011
				) );
2012
			}
2013
		}
2014
2015
		/**
2016
		 * Filters the array of modules available to be activated.
2017
		 *
2018
		 * @since 2.4.0
2019
		 *
2020
		 * @param array $modules Array of available modules.
2021
		 * @param string $min_version Minimum version number required to use modules.
2022
		 * @param string $max_version Maximum version number required to use modules.
2023
		 */
2024
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2025
2026
		if ( ! $min_version && ! $max_version ) {
2027
			return array_keys( $mods );
2028
		}
2029
2030
		$r = array();
2031
		foreach ( $mods as $slug => $introduced ) {
2032
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2033
				continue;
2034
			}
2035
2036
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2037
				continue;
2038
			}
2039
2040
			$r[] = $slug;
2041
		}
2042
2043
		return $r;
2044
	}
2045
2046
	/**
2047
	 * Default modules loaded on activation.
2048
	 */
2049
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2050
		$return = array();
2051
2052
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2053
			$module_data = Jetpack::get_module( $module );
2054
2055
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2056
				case 'yes' :
2057
					$return[] = $module;
2058
					break;
2059
				case 'public' :
2060
					if ( Jetpack_Options::get_option( 'public' ) ) {
2061
						$return[] = $module;
2062
					}
2063
					break;
2064
				case 'no' :
2065
				default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2066
					break;
2067
			}
2068
		}
2069
		/**
2070
		 * Filters the array of default modules.
2071
		 *
2072
		 * @since 2.5.0
2073
		 *
2074
		 * @param array $return Array of default modules.
2075
		 * @param string $min_version Minimum version number required to use modules.
2076
		 * @param string $max_version Maximum version number required to use modules.
2077
		 */
2078
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2079
	}
2080
2081
	/**
2082
	 * Checks activated modules during auto-activation to determine
2083
	 * if any of those modules are being deprecated.  If so, close
2084
	 * them out, and add any replacement modules.
2085
	 *
2086
	 * Runs at priority 99 by default.
2087
	 *
2088
	 * This is run late, so that it can still activate a module if
2089
	 * the new module is a replacement for another that the user
2090
	 * currently has active, even if something at the normal priority
2091
	 * would kibosh everything.
2092
	 *
2093
	 * @since 2.6
2094
	 * @uses jetpack_get_default_modules filter
2095
	 * @param array $modules
2096
	 * @return array
2097
	 */
2098
	function handle_deprecated_modules( $modules ) {
2099
		$deprecated_modules = array(
2100
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2101
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2102
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2103
		);
2104
2105
		// Don't activate SSO if they never completed activating WPCC.
2106
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2107
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2108
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2109
				$deprecated_modules['wpcc'] = null;
2110
			}
2111
		}
2112
2113
		foreach ( $deprecated_modules as $module => $replacement ) {
2114
			if ( Jetpack::is_module_active( $module ) ) {
2115
				self::deactivate_module( $module );
2116
				if ( $replacement ) {
2117
					$modules[] = $replacement;
2118
				}
2119
			}
2120
		}
2121
2122
		return array_unique( $modules );
2123
	}
2124
2125
	/**
2126
	 * Checks activated plugins during auto-activation to determine
2127
	 * if any of those plugins are in the list with a corresponding module
2128
	 * that is not compatible with the plugin. The module will not be allowed
2129
	 * to auto-activate.
2130
	 *
2131
	 * @since 2.6
2132
	 * @uses jetpack_get_default_modules filter
2133
	 * @param array $modules
2134
	 * @return array
2135
	 */
2136
	function filter_default_modules( $modules ) {
2137
2138
		$active_plugins = self::get_active_plugins();
2139
2140
		if ( ! empty( $active_plugins ) ) {
2141
2142
			// For each module we'd like to auto-activate...
2143
			foreach ( $modules as $key => $module ) {
2144
				// If there are potential conflicts for it...
2145
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2146
					// For each potential conflict...
2147
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2148
						// If that conflicting plugin is active...
2149
						if ( in_array( $plugin, $active_plugins ) ) {
2150
							// Remove that item from being auto-activated.
2151
							unset( $modules[ $key ] );
2152
						}
2153
					}
2154
				}
2155
			}
2156
		}
2157
2158
		return $modules;
2159
	}
2160
2161
	/**
2162
	 * Extract a module's slug from its full path.
2163
	 */
2164
	public static function get_module_slug( $file ) {
2165
		return str_replace( '.php', '', basename( $file ) );
2166
	}
2167
2168
	/**
2169
	 * Generate a module's path from its slug.
2170
	 */
2171
	public static function get_module_path( $slug ) {
2172
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2173
	}
2174
2175
	/**
2176
	 * Load module data from module file. Headers differ from WordPress
2177
	 * plugin headers to avoid them being identified as standalone
2178
	 * plugins on the WordPress plugins page.
2179
	 */
2180
	public static function get_module( $module ) {
2181
		$headers = array(
2182
			'name'                      => 'Module Name',
2183
			'description'               => 'Module Description',
2184
			'jumpstart_desc'            => 'Jumpstart Description',
2185
			'sort'                      => 'Sort Order',
2186
			'recommendation_order'      => 'Recommendation Order',
2187
			'introduced'                => 'First Introduced',
2188
			'changed'                   => 'Major Changes In',
2189
			'deactivate'                => 'Deactivate',
2190
			'free'                      => 'Free',
2191
			'requires_connection'       => 'Requires Connection',
2192
			'auto_activate'             => 'Auto Activate',
2193
			'module_tags'               => 'Module Tags',
2194
			'feature'                   => 'Feature',
2195
			'additional_search_queries' => 'Additional Search Queries',
2196
		);
2197
2198
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2199
2200
		$mod = Jetpack::get_file_data( $file, $headers );
2201
		if ( empty( $mod['name'] ) ) {
2202
			return false;
2203
		}
2204
2205
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2206
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2207
		$mod['deactivate']              = empty( $mod['deactivate'] );
2208
		$mod['free']                    = empty( $mod['free'] );
2209
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2210
2211
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2212
			$mod['auto_activate'] = 'No';
2213
		} else {
2214
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2215
		}
2216
2217
		if ( $mod['module_tags'] ) {
2218
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2219
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2220
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2221
		} else {
2222
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2223
		}
2224
2225
		if ( $mod['feature'] ) {
2226
			$mod['feature'] = explode( ',', $mod['feature'] );
2227
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2228
		} else {
2229
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2230
		}
2231
2232
		/**
2233
		 * Filters the feature array on a module.
2234
		 *
2235
		 * This filter allows you to control where each module is filtered: Recommended,
2236
		 * Jumpstart, and the default "Other" listing.
2237
		 *
2238
		 * @since 3.5.0
2239
		 *
2240
		 * @param array   $mod['feature'] The areas to feature this module:
2241
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2242
		 *     'Recommended' shows on the main Jetpack admin screen.
2243
		 *     'Other' should be the default if no other value is in the array.
2244
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2245
		 * @param array   $mod All the currently assembled module data.
2246
		 */
2247
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2248
2249
		/**
2250
		 * Filter the returned data about a module.
2251
		 *
2252
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2253
		 * so please be careful.
2254
		 *
2255
		 * @since 3.6.0
2256
		 *
2257
		 * @param array   $mod    The details of the requested module.
2258
		 * @param string  $module The slug of the module, e.g. sharedaddy
2259
		 * @param string  $file   The path to the module source file.
2260
		 */
2261
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2262
	}
2263
2264
	/**
2265
	 * Like core's get_file_data implementation, but caches the result.
2266
	 */
2267
	public static function get_file_data( $file, $headers ) {
2268
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2269
		$file_name = basename( $file );
2270
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2271
		$key              = md5( $file_name . serialize( $headers ) );
2272
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2273
2274
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2275
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2276
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2277
		}
2278
2279
		$data = get_file_data( $file, $headers );
2280
2281
		// Strip out any old Jetpack versions that are cluttering the option.
2282
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2283
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2284
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2285
2286
		return $data;
2287
	}
2288
2289
	/**
2290
	 * Return translated module tag.
2291
	 *
2292
	 * @param string $tag Tag as it appears in each module heading.
2293
	 *
2294
	 * @return mixed
2295
	 */
2296
	public static function translate_module_tag( $tag ) {
2297
		return jetpack_get_module_i18n_tag( $tag );
2298
	}
2299
2300
	/**
2301
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2302
	 *
2303
	 * @since 3.9.2
2304
	 *
2305
	 * @param array $modules
2306
	 *
2307
	 * @return string|void
2308
	 */
2309
	public static function get_translated_modules( $modules ) {
2310
		foreach ( $modules as $index => $module ) {
2311
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2312
			if ( isset( $module['name'] ) ) {
2313
				$modules[ $index ]['name'] = $i18n_module['name'];
2314
			}
2315
			if ( isset( $module['description'] ) ) {
2316
				$modules[ $index ]['description'] = $i18n_module['description'];
2317
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2318
			}
2319
		}
2320
		return $modules;
2321
	}
2322
2323
	/**
2324
	 * Get a list of activated modules as an array of module slugs.
2325
	 */
2326
	public static function get_active_modules() {
2327
		$active = Jetpack_Options::get_option( 'active_modules' );
2328
2329
		if ( ! is_array( $active ) ) {
2330
			$active = array();
2331
		}
2332
2333
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2334
			$active[] = 'vaultpress';
2335
		} else {
2336
			$active = array_diff( $active, array( 'vaultpress' ) );
2337
		}
2338
2339
		//If protect is active on the main site of a multisite, it should be active on all sites.
2340
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2341
			$active[] = 'protect';
2342
		}
2343
2344
		return array_unique( $active );
2345
	}
2346
2347
	/**
2348
	 * Check whether or not a Jetpack module is active.
2349
	 *
2350
	 * @param string $module The slug of a Jetpack module.
2351
	 * @return bool
2352
	 *
2353
	 * @static
2354
	 */
2355
	public static function is_module_active( $module ) {
2356
		return in_array( $module, self::get_active_modules() );
2357
	}
2358
2359
	public static function is_module( $module ) {
2360
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2361
	}
2362
2363
	/**
2364
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2365
	 *
2366
	 * @param bool $catch True to start catching, False to stop.
2367
	 *
2368
	 * @static
2369
	 */
2370
	public static function catch_errors( $catch ) {
2371
		static $display_errors, $error_reporting;
2372
2373
		if ( $catch ) {
2374
			$display_errors  = @ini_set( 'display_errors', 1 );
2375
			$error_reporting = @error_reporting( E_ALL );
2376
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2377
		} else {
2378
			@ini_set( 'display_errors', $display_errors );
2379
			@error_reporting( $error_reporting );
2380
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2381
		}
2382
	}
2383
2384
	/**
2385
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2386
	 */
2387
	public static function catch_errors_on_shutdown() {
2388
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2389
	}
2390
2391
	/**
2392
	 * Rewrite any string to make paths easier to read.
2393
	 *
2394
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2395
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2396
	 *
2397
	 * @param $string
2398
	 * @return mixed
2399
	 */
2400
	public static function alias_directories( $string ) {
2401
		// ABSPATH has a trailing slash.
2402
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2403
		// WP_CONTENT_DIR does not have a trailing slash.
2404
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2405
2406
		return $string;
2407
	}
2408
2409
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2410
		$jetpack = Jetpack::init();
2411
2412
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2413
		$modules = array_merge( $other_modules, $modules );
2414
2415
		// Look for standalone plugins and disable if active.
2416
2417
		$to_deactivate = array();
2418
		foreach ( $modules as $module ) {
2419
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2420
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2421
			}
2422
		}
2423
2424
		$deactivated = array();
2425
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2426
			list( $probable_file, $probable_title ) = $deactivate_me;
2427
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2428
				$deactivated[] = $module;
2429
			}
2430
		}
2431
2432
		if ( $deactivated && $redirect ) {
2433
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2434
2435
			$url = add_query_arg(
2436
				array(
2437
					'action'   => 'activate_default_modules',
2438
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2439
				),
2440
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2441
			);
2442
			wp_safe_redirect( $url );
2443
			exit;
2444
		}
2445
2446
		/**
2447
		 * Fires before default modules are activated.
2448
		 *
2449
		 * @since 1.9.0
2450
		 *
2451
		 * @param string $min_version Minimum version number required to use modules.
2452
		 * @param string $max_version Maximum version number required to use modules.
2453
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2454
		 */
2455
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2456
2457
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2458
		Jetpack::restate();
2459
		Jetpack::catch_errors( true );
2460
2461
		$active = Jetpack::get_active_modules();
2462
2463
		foreach ( $modules as $module ) {
2464
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2465
				$active[] = $module;
2466
				self::update_active_modules( $active );
2467
				continue;
2468
			}
2469
2470
			if ( in_array( $module, $active ) ) {
2471
				$module_info = Jetpack::get_module( $module );
2472
				if ( ! $module_info['deactivate'] ) {
2473
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2474 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2475
						$active_state = explode( ',', $active_state );
2476
					} else {
2477
						$active_state = array();
2478
					}
2479
					$active_state[] = $module;
2480
					Jetpack::state( $state, implode( ',', $active_state ) );
2481
				}
2482
				continue;
2483
			}
2484
2485
			$file = Jetpack::get_module_path( $module );
2486
			if ( ! file_exists( $file ) ) {
2487
				continue;
2488
			}
2489
2490
			// we'll override this later if the plugin can be included without fatal error
2491
			if ( $redirect ) {
2492
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2493
			}
2494
			Jetpack::state( 'error', 'module_activation_failed' );
2495
			Jetpack::state( 'module', $module );
2496
			ob_start();
2497
			require $file;
2498
2499
			$active[] = $module;
2500
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2501 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2502
				$active_state = explode( ',', $active_state );
2503
			} else {
2504
				$active_state = array();
2505
			}
2506
			$active_state[] = $module;
2507
			Jetpack::state( $state, implode( ',', $active_state ) );
2508
			Jetpack::update_active_modules( $active );
2509
2510
			ob_end_clean();
2511
		}
2512
		Jetpack::state( 'error', false );
2513
		Jetpack::state( 'module', false );
2514
		Jetpack::catch_errors( false );
2515
		/**
2516
		 * Fires when default modules are activated.
2517
		 *
2518
		 * @since 1.9.0
2519
		 *
2520
		 * @param string $min_version Minimum version number required to use modules.
2521
		 * @param string $max_version Maximum version number required to use modules.
2522
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2523
		 */
2524
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2525
	}
2526
2527
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2528
		/**
2529
		 * Fires before a module is activated.
2530
		 *
2531
		 * @since 2.6.0
2532
		 *
2533
		 * @param string $module Module slug.
2534
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2535
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2536
		 */
2537
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2538
2539
		$jetpack = Jetpack::init();
2540
2541
		if ( ! strlen( $module ) )
2542
			return false;
2543
2544
		if ( ! Jetpack::is_module( $module ) )
2545
			return false;
2546
2547
		// If it's already active, then don't do it again
2548
		$active = Jetpack::get_active_modules();
2549
		foreach ( $active as $act ) {
2550
			if ( $act == $module )
2551
				return true;
2552
		}
2553
2554
		$module_data = Jetpack::get_module( $module );
2555
2556
		if ( ! Jetpack::is_active() ) {
2557
			if ( !Jetpack::is_development_mode() )
2558
				return false;
2559
2560
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2561
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2562
				return false;
2563
		}
2564
2565
		// Check and see if the old plugin is active
2566
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2567
			// Deactivate the old plugin
2568
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2569
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2570
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2571
				Jetpack::state( 'deactivated_plugins', $module );
2572
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2573
				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...
2574
			}
2575
		}
2576
2577
		// Protect won't work with mis-configured IPs
2578
		if ( 'protect' === $module ) {
2579
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2580
			if ( ! jetpack_protect_get_ip() ) {
2581
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2582
				return false;
2583
			}
2584
		}
2585
2586
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2587
		Jetpack::state( 'module', $module );
2588
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2589
2590
		Jetpack::catch_errors( true );
2591
		ob_start();
2592
		require Jetpack::get_module_path( $module );
2593
		/** This action is documented in class.jetpack.php */
2594
		do_action( 'jetpack_activate_module', $module );
2595
		$active[] = $module;
2596
		Jetpack::update_active_modules( $active );
2597
2598
		Jetpack::state( 'error', false ); // the override
2599
		ob_end_clean();
2600
		Jetpack::catch_errors( false );
2601
2602
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2603 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2604
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2605
2606
			//Jump start is being dismissed send data to MC Stats
2607
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2608
2609
			$jetpack->do_stats( 'server_side' );
2610
		}
2611
2612
		if ( $redirect ) {
2613
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2614
		}
2615
		if ( $exit ) {
2616
			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...
2617
		}
2618
		return true;
2619
	}
2620
2621
	function activate_module_actions( $module ) {
2622
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2623
	}
2624
2625
	public static function deactivate_module( $module ) {
2626
		/**
2627
		 * Fires when a module is deactivated.
2628
		 *
2629
		 * @since 1.9.0
2630
		 *
2631
		 * @param string $module Module slug.
2632
		 */
2633
		do_action( 'jetpack_pre_deactivate_module', $module );
2634
2635
		$jetpack = Jetpack::init();
2636
2637
		$active = Jetpack::get_active_modules();
2638
		$new    = array_filter( array_diff( $active, (array) $module ) );
2639
2640
		// A flag for Jump Start so it's not shown again.
2641 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2642
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2643
2644
			//Jump start is being dismissed send data to MC Stats
2645
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2646
2647
			$jetpack->do_stats( 'server_side' );
2648
		}
2649
2650
		return self::update_active_modules( $new );
2651
	}
2652
2653
	public static function enable_module_configurable( $module ) {
2654
		$module = Jetpack::get_module_slug( $module );
2655
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2656
	}
2657
2658
	public static function module_configuration_url( $module ) {
2659
		$module = Jetpack::get_module_slug( $module );
2660
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2661
	}
2662
2663
	public static function module_configuration_load( $module, $method ) {
2664
		$module = Jetpack::get_module_slug( $module );
2665
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2666
	}
2667
2668
	public static function module_configuration_head( $module, $method ) {
2669
		$module = Jetpack::get_module_slug( $module );
2670
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2671
	}
2672
2673
	public static function module_configuration_screen( $module, $method ) {
2674
		$module = Jetpack::get_module_slug( $module );
2675
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2676
	}
2677
2678
	public static function module_configuration_activation_screen( $module, $method ) {
2679
		$module = Jetpack::get_module_slug( $module );
2680
		add_action( 'display_activate_module_setting_' . $module, $method );
2681
	}
2682
2683
/* Installation */
2684
2685
	public static function bail_on_activation( $message, $deactivate = true ) {
2686
?>
2687
<!doctype html>
2688
<html>
2689
<head>
2690
<meta charset="<?php bloginfo( 'charset' ); ?>">
2691
<style>
2692
* {
2693
	text-align: center;
2694
	margin: 0;
2695
	padding: 0;
2696
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2697
}
2698
p {
2699
	margin-top: 1em;
2700
	font-size: 18px;
2701
}
2702
</style>
2703
<body>
2704
<p><?php echo esc_html( $message ); ?></p>
2705
</body>
2706
</html>
2707
<?php
2708
		if ( $deactivate ) {
2709
			$plugins = get_option( 'active_plugins' );
2710
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2711
			$update  = false;
2712
			foreach ( $plugins as $i => $plugin ) {
2713
				if ( $plugin === $jetpack ) {
2714
					$plugins[$i] = false;
2715
					$update = true;
2716
				}
2717
			}
2718
2719
			if ( $update ) {
2720
				update_option( 'active_plugins', array_filter( $plugins ) );
2721
			}
2722
		}
2723
		exit;
2724
	}
2725
2726
	/**
2727
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2728
	 * @static
2729
	 */
2730
	public static function plugin_activation( $network_wide ) {
2731
		Jetpack_Options::update_option( 'activated', 1 );
2732
2733
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2734
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2735
		}
2736
2737
		if ( $network_wide )
2738
			Jetpack::state( 'network_nag', true );
2739
2740
		Jetpack::plugin_initialize();
2741
	}
2742
	/**
2743
	 * Runs before bumping version numbers up to a new version
2744
	 * @param  (string) $version    Version:timestamp
2745
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2746
	 * @return null              [description]
2747
	 */
2748
	public static function do_version_bump( $version, $old_version ) {
2749
2750
		if ( ! $old_version ) { // For new sites
2751
			// Setting up jetpack manage
2752
			Jetpack::activate_manage();
2753
		}
2754
	}
2755
2756
	/**
2757
	 * Sets the internal version number and activation state.
2758
	 * @static
2759
	 */
2760
	public static function plugin_initialize() {
2761
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2762
			Jetpack_Options::update_option( 'activated', 2 );
2763
		}
2764
2765 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2766
			$version = $old_version = JETPACK__VERSION . ':' . time();
2767
			/** This action is documented in class.jetpack.php */
2768
			do_action( 'updating_jetpack_version', $version, false );
2769
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2770
		}
2771
2772
		Jetpack::load_modules();
2773
2774
		Jetpack_Options::delete_option( 'do_activate' );
2775
	}
2776
2777
	/**
2778
	 * Removes all connection options
2779
	 * @static
2780
	 */
2781
	public static function plugin_deactivation( ) {
2782
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2783
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2784
			Jetpack_Network::init()->deactivate();
2785
		} else {
2786
			Jetpack::disconnect( false );
2787
			//Jetpack_Heartbeat::init()->deactivate();
2788
		}
2789
	}
2790
2791
	/**
2792
	 * Disconnects from the Jetpack servers.
2793
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2794
	 * @static
2795
	 */
2796
	public static function disconnect( $update_activated_state = true ) {
2797
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2798
		Jetpack::clean_nonces( true );
2799
2800
		// If the site is in an IDC because sync is not allowed,
2801
		// let's make sure to not disconnect the production site.
2802
		if ( ! self::validate_sync_error_idc_option() ) {
2803
			JetpackTracking::record_user_event( 'disconnect_site', array() );
2804
			Jetpack::load_xml_rpc_client();
2805
			$xml = new Jetpack_IXR_Client();
2806
			$xml->query( 'jetpack.deregister' );
2807
		}
2808
2809
		Jetpack_Options::delete_option(
2810
			array(
2811
				'register',
2812
				'blog_token',
2813
				'user_token',
2814
				'user_tokens',
2815
				'master_user',
2816
				'time_diff',
2817
				'fallback_no_verify_ssl_certs',
2818
			)
2819
		);
2820
2821
		Jetpack_IDC::clear_all_idc_options();
2822
2823
		if ( $update_activated_state ) {
2824
			Jetpack_Options::update_option( 'activated', 4 );
2825
		}
2826
2827
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2828
			// Check then record unique disconnection if site has never been disconnected previously
2829
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2830
				$jetpack_unique_connection['disconnected'] = 1;
2831
			} else {
2832
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2833
					//track unique disconnect
2834
					$jetpack = Jetpack::init();
2835
2836
					$jetpack->stat( 'connections', 'unique-disconnect' );
2837
					$jetpack->do_stats( 'server_side' );
2838
				}
2839
				// increment number of times disconnected
2840
				$jetpack_unique_connection['disconnected'] += 1;
2841
			}
2842
2843
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2844
		}
2845
2846
		// Delete cached connected user data
2847
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
2848
		delete_transient( $transient_key );
2849
2850
		// Delete all the sync related data. Since it could be taking up space.
2851
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2852
		Jetpack_Sync_Sender::get_instance()->uninstall();
2853
2854
		// Disable the Heartbeat cron
2855
		Jetpack_Heartbeat::init()->deactivate();
2856
	}
2857
2858
	/**
2859
	 * Unlinks the current user from the linked WordPress.com user
2860
	 */
2861
	public static function unlink_user( $user_id = null ) {
2862
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2863
			return false;
2864
2865
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2866
2867
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2868
			return false;
2869
2870
		if ( ! isset( $tokens[ $user_id ] ) )
2871
			return false;
2872
2873
		Jetpack::load_xml_rpc_client();
2874
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2875
		$xml->query( 'jetpack.unlink_user', $user_id );
2876
2877
		unset( $tokens[ $user_id ] );
2878
2879
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2880
2881
		/**
2882
		 * Fires after the current user has been unlinked from WordPress.com.
2883
		 *
2884
		 * @since 4.1.0
2885
		 *
2886
		 * @param int $user_id The current user's ID.
2887
		 */
2888
		do_action( 'jetpack_unlinked_user', $user_id );
2889
2890
		return true;
2891
	}
2892
2893
	/**
2894
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2895
	 */
2896
	public static function try_registration() {
2897
		// Let's get some testing in beta versions and such.
2898
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2899
			// Before attempting to connect, let's make sure that the domains are viable.
2900
			$domains_to_check = array_unique( array(
2901
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2902
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2903
			) );
2904
			foreach ( $domains_to_check as $domain ) {
2905
				$result = Jetpack_Data::is_usable_domain( $domain );
2906
				if ( is_wp_error( $result ) ) {
2907
					return $result;
2908
				}
2909
			}
2910
		}
2911
2912
		$result = Jetpack::register();
2913
2914
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2915
		if ( ! $result || is_wp_error( $result ) ) {
2916
			return $result;
2917
		} else {
2918
			return true;
2919
		}
2920
	}
2921
2922
	/**
2923
	 * Tracking an internal event log. Try not to put too much chaff in here.
2924
	 *
2925
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2926
	 */
2927
	public static function log( $code, $data = null ) {
2928
		// only grab the latest 200 entries
2929
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2930
2931
		// Append our event to the log
2932
		$log_entry = array(
2933
			'time'    => time(),
2934
			'user_id' => get_current_user_id(),
2935
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2936
			'code'    => $code,
2937
		);
2938
		// Don't bother storing it unless we've got some.
2939
		if ( ! is_null( $data ) ) {
2940
			$log_entry['data'] = $data;
2941
		}
2942
		$log[] = $log_entry;
2943
2944
		// Try add_option first, to make sure it's not autoloaded.
2945
		// @todo: Add an add_option method to Jetpack_Options
2946
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2947
			Jetpack_Options::update_option( 'log', $log );
2948
		}
2949
2950
		/**
2951
		 * Fires when Jetpack logs an internal event.
2952
		 *
2953
		 * @since 3.0.0
2954
		 *
2955
		 * @param array $log_entry {
2956
		 *	Array of details about the log entry.
2957
		 *
2958
		 *	@param string time Time of the event.
2959
		 *	@param int user_id ID of the user who trigerred the event.
2960
		 *	@param int blog_id Jetpack Blog ID.
2961
		 *	@param string code Unique name for the event.
2962
		 *	@param string data Data about the event.
2963
		 * }
2964
		 */
2965
		do_action( 'jetpack_log_entry', $log_entry );
2966
	}
2967
2968
	/**
2969
	 * Get the internal event log.
2970
	 *
2971
	 * @param $event (string) - only return the specific log events
2972
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2973
	 *
2974
	 * @return array of log events || WP_Error for invalid params
2975
	 */
2976
	public static function get_log( $event = false, $num = false ) {
2977
		if ( $event && ! is_string( $event ) ) {
2978
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2979
		}
2980
2981
		if ( $num && ! is_numeric( $num ) ) {
2982
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2983
		}
2984
2985
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2986
2987
		// If nothing set - act as it did before, otherwise let's start customizing the output
2988
		if ( ! $num && ! $event ) {
2989
			return $entire_log;
2990
		} else {
2991
			$entire_log = array_reverse( $entire_log );
2992
		}
2993
2994
		$custom_log_output = array();
2995
2996
		if ( $event ) {
2997
			foreach ( $entire_log as $log_event ) {
2998
				if ( $event == $log_event[ 'code' ] ) {
2999
					$custom_log_output[] = $log_event;
3000
				}
3001
			}
3002
		} else {
3003
			$custom_log_output = $entire_log;
3004
		}
3005
3006
		if ( $num ) {
3007
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3008
		}
3009
3010
		return $custom_log_output;
3011
	}
3012
3013
	/**
3014
	 * Log modification of important settings.
3015
	 */
3016
	public static function log_settings_change( $option, $old_value, $value ) {
3017
		switch( $option ) {
3018
			case 'jetpack_sync_non_public_post_stati':
3019
				self::log( $option, $value );
3020
				break;
3021
		}
3022
	}
3023
3024
	/**
3025
	 * Return stat data for WPCOM sync
3026
	 */
3027
	public static function get_stat_data( $encode = true, $extended = true ) {
3028
		$data = Jetpack_Heartbeat::generate_stats_array();
3029
3030
		if ( $extended ) {
3031
			$additional_data = self::get_additional_stat_data();
3032
			$data = array_merge( $data, $additional_data );
3033
		}
3034
3035
		if ( $encode ) {
3036
			return json_encode( $data );
3037
		}
3038
3039
		return $data;
3040
	}
3041
3042
	/**
3043
	 * Get additional stat data to sync to WPCOM
3044
	 */
3045
	public static function get_additional_stat_data( $prefix = '' ) {
3046
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3047
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3048
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3049
		$return["{$prefix}site-count"]     = 0;
3050
3051
		if ( function_exists( 'get_blog_count' ) ) {
3052
			$return["{$prefix}site-count"] = get_blog_count();
3053
		}
3054
		return $return;
3055
	}
3056
3057
	private static function get_site_user_count() {
3058
		global $wpdb;
3059
3060
		if ( function_exists( 'wp_is_large_network' ) ) {
3061
			if ( wp_is_large_network( 'users' ) ) {
3062
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3063
			}
3064
		}
3065 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3066
			// It wasn't there, so regenerate the data and save the transient
3067
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3068
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3069
		}
3070
		return $user_count;
3071
	}
3072
3073
	/* Admin Pages */
3074
3075
	function admin_init() {
3076
		// If the plugin is not connected, display a connect message.
3077
		if (
3078
			// the plugin was auto-activated and needs its candy
3079
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3080
		||
3081
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3082
			! Jetpack_Options::get_option( 'activated' )
3083
		) {
3084
			Jetpack::plugin_initialize();
3085
		}
3086
3087
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3088
			Jetpack_Connection_Banner::init();
3089
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3090
			// Upgrade: 1.1 -> 1.1.1
3091
			// Check and see if host can verify the Jetpack servers' SSL certificate
3092
			$args = array();
3093
			Jetpack_Client::_wp_remote_request(
3094
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3095
				$args,
3096
				true
3097
			);
3098
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3099
			// Show the notice on the Dashboard only for now
3100
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3101
		}
3102
3103
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3104
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3105
		}
3106
3107
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3108
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3109
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3110
3111
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3112
			// Artificially throw errors in certain whitelisted cases during plugin activation
3113
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3114
		}
3115
3116
		// Jetpack Manage Activation Screen from .com
3117
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3118
3119
		// Add custom column in wp-admin/users.php to show whether user is linked.
3120
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3121
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3122
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3123
	}
3124
3125
	function admin_body_class( $admin_body_class = '' ) {
3126
		$classes = explode( ' ', trim( $admin_body_class ) );
3127
3128
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3129
3130
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3131
		return " $admin_body_class ";
3132
	}
3133
3134
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3135
		return $admin_body_class . ' jetpack-pagestyles ';
3136
	}
3137
3138
	/**
3139
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3140
	 *
3141
	 * @return null
3142
	 */
3143
	function prepare_manage_jetpack_notice() {
3144
3145
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3146
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3147
	}
3148
3149
	function manage_activate_screen() {
3150
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3151
	}
3152
	/**
3153
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3154
	 * This function artificially throws errors for such cases (whitelisted).
3155
	 *
3156
	 * @param string $plugin The activated plugin.
3157
	 */
3158
	function throw_error_on_activate_plugin( $plugin ) {
3159
		$active_modules = Jetpack::get_active_modules();
3160
3161
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3162
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3163
			$throw = false;
3164
3165
			// Try and make sure it really was the stats plugin
3166
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3167
				if ( 'stats.php' == basename( $plugin ) ) {
3168
					$throw = true;
3169
				}
3170
			} else {
3171
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3172
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3173
					$throw = true;
3174
				}
3175
			}
3176
3177
			if ( $throw ) {
3178
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3179
			}
3180
		}
3181
	}
3182
3183
	function intercept_plugin_error_scrape_init() {
3184
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3185
	}
3186
3187
	function intercept_plugin_error_scrape( $action, $result ) {
3188
		if ( ! $result ) {
3189
			return;
3190
		}
3191
3192
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3193
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3194
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3195
			}
3196
		}
3197
	}
3198
3199
	function add_remote_request_handlers() {
3200
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3201
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3202
	}
3203
3204
	function remote_request_handlers() {
3205
		$action = current_filter();
3206
3207
		switch ( current_filter() ) {
3208
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3209
			$response = $this->upload_handler();
3210
			break;
3211
3212
		case 'wp_ajax_nopriv_jetpack_update_file' :
3213
			$response = $this->upload_handler( true );
3214
			break;
3215
		default :
0 ignored issues
show
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
3216
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3217
			break;
3218
		}
3219
3220
		if ( ! $response ) {
3221
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3222
		}
3223
3224
		if ( is_wp_error( $response ) ) {
3225
			$status_code       = $response->get_error_data();
3226
			$error             = $response->get_error_code();
3227
			$error_description = $response->get_error_message();
3228
3229
			if ( ! is_int( $status_code ) ) {
3230
				$status_code = 400;
3231
			}
3232
3233
			status_header( $status_code );
3234
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3235
		}
3236
3237
		status_header( 200 );
3238
		if ( true === $response ) {
3239
			exit;
3240
		}
3241
3242
		die( json_encode( (object) $response ) );
3243
	}
3244
3245
	/**
3246
	 * Uploads a file gotten from the global $_FILES.
3247
	 * If `$update_media_item` is true and `post_id` is defined
3248
	 * the attachment file of the media item (gotten through of the post_id)
3249
	 * will be updated instead of add a new one.
3250
	 * 
3251
	 * @param  boolean $update_media_item - update media attachment
3252
	 * @return array - An array describing the uploadind files process
3253
	 */
3254
	function upload_handler( $update_media_item = false ) {
3255
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3256
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3257
		}
3258
3259
		$user = wp_authenticate( '', '' );
3260
		if ( ! $user || is_wp_error( $user ) ) {
3261
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3262
		}
3263
3264
		wp_set_current_user( $user->ID );
3265
3266
		if ( ! current_user_can( 'upload_files' ) ) {
3267
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3268
		}
3269
3270
		if ( empty( $_FILES ) ) {
3271
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3272
		}
3273
3274
		foreach ( array_keys( $_FILES ) as $files_key ) {
3275
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3276
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3277
			}
3278
		}
3279
3280
		$media_keys = array_keys( $_FILES['media'] );
3281
3282
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3283
		if ( ! $token || is_wp_error( $token ) ) {
3284
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3285
		}
3286
3287
		$uploaded_files = array();
3288
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3289
		unset( $GLOBALS['post'] );
3290
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3291
			$file = array();
3292
			foreach ( $media_keys as $media_key ) {
3293
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3294
			}
3295
3296
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3297
3298
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3299
			if ( $hmac_provided !== $hmac_file ) {
3300
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3301
				continue;
3302
			}
3303
3304
			$_FILES['.jetpack.upload.'] = $file;
3305
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3306
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3307
				$post_id = 0;
3308
			}
3309
3310
			if ( $update_media_item ) {
3311
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3312
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3313
				}
3314
3315
				$media_array = $_FILES['media'];
3316
3317
				$file_array['name'] = $media_array['name'][0]; 
3318
				$file_array['type'] = $media_array['type'][0]; 
3319
				$file_array['tmp_name'] = $media_array['tmp_name'][0]; 
3320
				$file_array['error'] = $media_array['error'][0]; 
3321
				$file_array['size'] = $media_array['size'][0];
3322
3323
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3324
3325
				if ( is_wp_error( $edited_media_item ) ) {
3326
					return $edited_media_item;
3327
				}
3328
3329
				$response = (object) array(
3330
					'id'   => (string) $post_id,
3331
					'file' => (string) $edited_media_item->post_title,
3332
					'url'  => (string) wp_get_attachment_url( $post_id ),
3333
					'type' => (string) $edited_media_item->post_mime_type,
3334
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3335
				);
3336
3337
				return (array) array( $response );
3338
			}
3339
3340
			$attachment_id = media_handle_upload(
3341
				'.jetpack.upload.',
3342
				$post_id,
3343
				array(),
3344
				array(
3345
					'action' => 'jetpack_upload_file',
3346
				)
3347
			);
3348
3349
			if ( ! $attachment_id ) {
3350
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3351
			} elseif ( is_wp_error( $attachment_id ) ) {
3352
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3353
			} else {
3354
				$attachment = get_post( $attachment_id );
3355
				$uploaded_files[$index] = (object) array(
3356
					'id'   => (string) $attachment_id,
3357
					'file' => $attachment->post_title,
3358
					'url'  => wp_get_attachment_url( $attachment_id ),
3359
					'type' => $attachment->post_mime_type,
3360
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3361
				);
3362
				// Zip files uploads are not supported unless they are done for installation purposed
3363
				// lets delete them in case something goes wrong in this whole process
3364
				if ( 'application/zip' === $attachment->post_mime_type ) {
3365
					// Schedule a cleanup for 2 hours from now in case of failed install.
3366
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3367
				}
3368
			}
3369
		}
3370
		if ( ! is_null( $global_post ) ) {
3371
			$GLOBALS['post'] = $global_post;
3372
		}
3373
3374
		return $uploaded_files;
3375
	}
3376
3377
	/**
3378
	 * Add help to the Jetpack page
3379
	 *
3380
	 * @since Jetpack (1.2.3)
3381
	 * @return false if not the Jetpack page
3382
	 */
3383
	function admin_help() {
3384
		$current_screen = get_current_screen();
3385
3386
		// Overview
3387
		$current_screen->add_help_tab(
3388
			array(
3389
				'id'		=> 'home',
3390
				'title'		=> __( 'Home', 'jetpack' ),
3391
				'content'	=>
3392
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3393
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3394
					'<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>',
3395
			)
3396
		);
3397
3398
		// Screen Content
3399
		if ( current_user_can( 'manage_options' ) ) {
3400
			$current_screen->add_help_tab(
3401
				array(
3402
					'id'		=> 'settings',
3403
					'title'		=> __( 'Settings', 'jetpack' ),
3404
					'content'	=>
3405
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3406
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3407
						'<ol>' .
3408
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3409
							'<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>' .
3410
						'</ol>' .
3411
						'<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>'
3412
				)
3413
			);
3414
		}
3415
3416
		// Help Sidebar
3417
		$current_screen->set_help_sidebar(
3418
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3419
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3420
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3421
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3422
		);
3423
	}
3424
3425
	function admin_menu_css() {
3426
		wp_enqueue_style( 'jetpack-icons' );
3427
	}
3428
3429
	function admin_menu_order() {
3430
		return true;
3431
	}
3432
3433 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3434
		$jp_menu_order = array();
3435
3436
		foreach ( $menu_order as $index => $item ) {
3437
			if ( $item != 'jetpack' ) {
3438
				$jp_menu_order[] = $item;
3439
			}
3440
3441
			if ( $index == 0 ) {
3442
				$jp_menu_order[] = 'jetpack';
3443
			}
3444
		}
3445
3446
		return $jp_menu_order;
3447
	}
3448
3449
	function admin_head() {
3450 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3451
			/** This action is documented in class.jetpack-admin-page.php */
3452
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3453
	}
3454
3455
	function admin_banner_styles() {
3456
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3457
3458 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3459
			wp_register_style(
3460
				'jetpack-dops-style',
3461
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3462
				array(),
3463
				JETPACK__VERSION
3464
			);
3465
		}
3466
3467
		wp_enqueue_style(
3468
			'jetpack',
3469
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3470
			array( 'jetpack-dops-style' ),
3471
			 JETPACK__VERSION . '-20121016'
3472
		);
3473
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3474
		wp_style_add_data( 'jetpack', 'suffix', $min );
3475
	}
3476
3477
	function plugin_action_links( $actions ) {
3478
3479
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3480
3481
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3482
			return array_merge(
3483
				$jetpack_home,
3484
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3485
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3486
				$actions
3487
				);
3488
			}
3489
3490
		return array_merge( $jetpack_home, $actions );
3491
	}
3492
3493
	/**
3494
	 * This is the first banner
3495
	 * It should be visible only to user that can update the option
3496
	 * Are not connected
3497
	 *
3498
	 * @return null
3499
	 */
3500
	function admin_jetpack_manage_notice() {
3501
		$screen = get_current_screen();
3502
3503
		// Don't show the connect notice on the jetpack settings page.
3504
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3505
			return;
3506
		}
3507
3508
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3509
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3510
		/**
3511
		 * I think it would be great to have different wordsing depending on where you are
3512
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3513
		 * etc..
3514
		 */
3515
3516
		?>
3517
		<div id="message" class="updated jp-banner">
3518
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3519
				<div class="jp-banner__description-container">
3520
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3521
					<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>
3522
					<p class="jp-banner__button-container">
3523
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3524
						<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>
3525
					</p>
3526
				</div>
3527
		</div>
3528
		<?php
3529
	}
3530
3531
	/**
3532
	 * Returns the url that the user clicks to remove the notice for the big banner
3533
	 * @return (string)
3534
	 */
3535
	function opt_out_jetpack_manage_url() {
3536
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3537
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3538
	}
3539
	/**
3540
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3541
	 * @return (string)
3542
	 */
3543
	function opt_in_jetpack_manage_url() {
3544
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3545
	}
3546
3547
	function opt_in_jetpack_manage_notice() {
3548
		?>
3549
		<div class="wrap">
3550
			<div id="message" class="jetpack-message is-opt-in">
3551
				<?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' ); ?>
3552
			</div>
3553
		</div>
3554
		<?php
3555
3556
	}
3557
	/**
3558
	 * Determines whether to show the notice of not true = display notice
3559
	 * @return (bool)
3560
	 */
3561
	function can_display_jetpack_manage_notice() {
3562
		// never display the notice to users that can't do anything about it anyways
3563
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3564
			return false;
3565
3566
		// don't display if we are in development more
3567
		if( Jetpack::is_development_mode() ) {
3568
			return false;
3569
		}
3570
		// don't display if the site is private
3571
		if(  ! Jetpack_Options::get_option( 'public' ) )
3572
			return false;
3573
3574
		/**
3575
		 * Should the Jetpack Remote Site Management notice be displayed.
3576
		 *
3577
		 * @since 3.3.0
3578
		 *
3579
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3580
		 */
3581
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3582
	}
3583
3584
	/*
3585
	 * Registration flow:
3586
	 * 1 - ::admin_page_load() action=register
3587
	 * 2 - ::try_registration()
3588
	 * 3 - ::register()
3589
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3590
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3591
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3592
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3593
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3594
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3595
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3596
	 *       jetpack_id, jetpack_secret, jetpack_public
3597
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3598
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3599
	 * 5 - user logs in with WP.com account
3600
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3601
	 *		- Jetpack_Client_Server::authorize()
3602
	 *		- Jetpack_Client_Server::get_token()
3603
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3604
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3605
	 *			- which responds with access_token, token_type, scope
3606
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3607
	 *		- Jetpack::activate_default_modules()
3608
	 *     		- Deactivates deprecated plugins
3609
	 *     		- Activates all default modules
3610
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3611
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3612
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3613
	 *     Done!
3614
	 */
3615
3616
	/**
3617
	 * Handles the page load events for the Jetpack admin page
3618
	 */
3619
	function admin_page_load() {
3620
		$error = false;
3621
3622
		// Make sure we have the right body class to hook stylings for subpages off of.
3623
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3624
3625
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3626
			// Should only be used in intermediate redirects to preserve state across redirects
3627
			Jetpack::restate();
3628
		}
3629
3630
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3631
			// User clicked in the iframe to link their accounts
3632
			if ( ! Jetpack::is_user_connected() ) {
3633
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3634
				if ( isset( $_GET['notes_iframe'] ) )
3635
					$connect_url .= '&notes_iframe';
3636
				wp_redirect( $connect_url );
3637
				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...
3638
			} else {
3639
				if ( ! isset( $_GET['calypso_env'] ) ) {
3640
					Jetpack::state( 'message', 'already_authorized' );
3641
					wp_safe_redirect( Jetpack::admin_url() );
3642
				} else {
3643
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3644
					$connect_url .= '&already_authorized=true';
3645
					wp_redirect( $connect_url );
3646
				}
3647
			}
3648
		}
3649
3650
3651
		if ( isset( $_GET['action'] ) ) {
3652
			switch ( $_GET['action'] ) {
3653
			case 'authorize':
3654
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3655
					Jetpack::state( 'message', 'already_authorized' );
3656
					wp_safe_redirect( Jetpack::admin_url() );
3657
					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...
3658
				}
3659
				Jetpack::log( 'authorize' );
3660
				$client_server = new Jetpack_Client_Server;
3661
				$client_server->client_authorize();
3662
				exit;
3663
			case 'register' :
3664
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3665
					$error = 'cheatin';
3666
					break;
3667
				}
3668
				check_admin_referer( 'jetpack-register' );
3669
				Jetpack::log( 'register' );
3670
				Jetpack::maybe_set_version_option();
3671
				$registered = Jetpack::try_registration();
3672
				if ( is_wp_error( $registered ) ) {
3673
					$error = $registered->get_error_code();
3674
					Jetpack::state( 'error', $error );
3675
					Jetpack::state( 'error', $registered->get_error_message() );
3676
					break;
3677
				}
3678
3679
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3680
3681
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3682
				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...
3683
			case 'activate' :
3684
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3685
					$error = 'cheatin';
3686
					break;
3687
				}
3688
3689
				$module = stripslashes( $_GET['module'] );
3690
				check_admin_referer( "jetpack_activate-$module" );
3691
				Jetpack::log( 'activate', $module );
3692
				Jetpack::activate_module( $module );
3693
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3694
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3695
				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...
3696
			case 'activate_default_modules' :
3697
				check_admin_referer( 'activate_default_modules' );
3698
				Jetpack::log( 'activate_default_modules' );
3699
				Jetpack::restate();
3700
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3701
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3702
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3703
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3704
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3705
				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...
3706
			case 'disconnect' :
3707
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3708
					$error = 'cheatin';
3709
					break;
3710
				}
3711
3712
				check_admin_referer( 'jetpack-disconnect' );
3713
				Jetpack::log( 'disconnect' );
3714
				Jetpack::disconnect();
3715
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3716
				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...
3717
			case 'reconnect' :
3718
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3719
					$error = 'cheatin';
3720
					break;
3721
				}
3722
3723
				check_admin_referer( 'jetpack-reconnect' );
3724
				Jetpack::log( 'reconnect' );
3725
				$this->disconnect();
3726
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3727
				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...
3728 View Code Duplication
			case 'deactivate' :
3729
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3730
					$error = 'cheatin';
3731
					break;
3732
				}
3733
3734
				$modules = stripslashes( $_GET['module'] );
3735
				check_admin_referer( "jetpack_deactivate-$modules" );
3736
				foreach ( explode( ',', $modules ) as $module ) {
3737
					Jetpack::log( 'deactivate', $module );
3738
					Jetpack::deactivate_module( $module );
3739
					Jetpack::state( 'message', 'module_deactivated' );
3740
				}
3741
				Jetpack::state( 'module', $modules );
3742
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3743
				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...
3744
			case 'unlink' :
3745
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3746
				check_admin_referer( 'jetpack-unlink' );
3747
				Jetpack::log( 'unlink' );
3748
				$this->unlink_user();
3749
				Jetpack::state( 'message', 'unlinked' );
3750
				if ( 'sub-unlink' == $redirect ) {
3751
					wp_safe_redirect( admin_url() );
3752
				} else {
3753
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3754
				}
3755
				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...
3756
			default:
3757
				/**
3758
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
3759
				 *
3760
				 * @since 2.6.0
3761
				 *
3762
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
3763
				 */
3764
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
3765
			}
3766
		}
3767
3768
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
3769
			self::activate_new_modules( true );
3770
		}
3771
3772
		$message_code = Jetpack::state( 'message' );
3773
		if ( Jetpack::state( 'optin-manage' ) ) {
3774
			$activated_manage = $message_code;
3775
			$message_code = 'jetpack-manage';
3776
		}
3777
3778
		switch ( $message_code ) {
3779
		case 'jetpack-manage':
3780
			$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>';
3781
			if ( $activated_manage ) {
3782
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
3783
			}
3784
			break;
3785
3786
		}
3787
3788
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
3789
3790
		if ( ! empty( $deactivated_plugins ) ) {
3791
			$deactivated_plugins = explode( ',', $deactivated_plugins );
3792
			$deactivated_titles  = array();
3793
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
3794
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
3795
					continue;
3796
				}
3797
3798
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
3799
			}
3800
3801
			if ( $deactivated_titles ) {
3802
				if ( $this->message ) {
3803
					$this->message .= "<br /><br />\n";
3804
				}
3805
3806
				$this->message .= wp_sprintf(
3807
					_n(
3808
						'Jetpack contains the most recent version of the old %l plugin.',
3809
						'Jetpack contains the most recent versions of the old %l plugins.',
3810
						count( $deactivated_titles ),
3811
						'jetpack'
3812
					),
3813
					$deactivated_titles
3814
				);
3815
3816
				$this->message .= "<br />\n";
3817
3818
				$this->message .= _n(
3819
					'The old version has been deactivated and can be removed from your site.',
3820
					'The old versions have been deactivated and can be removed from your site.',
3821
					count( $deactivated_titles ),
3822
					'jetpack'
3823
				);
3824
			}
3825
		}
3826
3827
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
3828
3829
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
3830
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
3831
		}
3832
3833 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
3834
			/**
3835
			 * Fires when a module configuration page is loaded.
3836
			 * The dynamic part of the hook is the configure parameter from the URL.
3837
			 *
3838
			 * @since 1.1.0
3839
			 */
3840
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
3841
		}
3842
3843
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
3844
	}
3845
3846
	function admin_notices() {
3847
3848
		if ( $this->error ) {
3849
?>
3850
<div id="message" class="jetpack-message jetpack-err">
3851
	<div class="squeezer">
3852
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
3853
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
3854
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
3855
<?php	endif; ?>
3856
	</div>
3857
</div>
3858
<?php
3859
		}
3860
3861
		if ( $this->message ) {
3862
?>
3863
<div id="message" class="jetpack-message">
3864
	<div class="squeezer">
3865
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
3866
	</div>
3867
</div>
3868
<?php
3869
		}
3870
3871
		if ( $this->privacy_checks ) :
3872
			$module_names = $module_slugs = array();
3873
3874
			$privacy_checks = explode( ',', $this->privacy_checks );
3875
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
3876
			foreach ( $privacy_checks as $module_slug ) {
3877
				$module = Jetpack::get_module( $module_slug );
3878
				if ( ! $module ) {
3879
					continue;
3880
				}
3881
3882
				$module_slugs[] = $module_slug;
3883
				$module_names[] = "<strong>{$module['name']}</strong>";
3884
			}
3885
3886
			$module_slugs = join( ',', $module_slugs );
3887
?>
3888
<div id="message" class="jetpack-message jetpack-err">
3889
	<div class="squeezer">
3890
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
3891
		<p><?php
3892
			echo wp_kses(
3893
				wptexturize(
3894
					wp_sprintf(
3895
						_nx(
3896
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
3897
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
3898
							count( $privacy_checks ),
3899
							'%l = list of Jetpack module/feature names',
3900
							'jetpack'
3901
						),
3902
						$module_names
3903
					)
3904
				),
3905
				array( 'strong' => true )
3906
			);
3907
3908
			echo "\n<br />\n";
3909
3910
			echo wp_kses(
3911
				sprintf(
3912
					_nx(
3913
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
3914
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
3915
						count( $privacy_checks ),
3916
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
3917
						'jetpack'
3918
					),
3919
					wp_nonce_url(
3920
						Jetpack::admin_url(
3921
							array(
3922
								'page'   => 'jetpack',
3923
								'action' => 'deactivate',
3924
								'module' => urlencode( $module_slugs ),
3925
							)
3926
						),
3927
						"jetpack_deactivate-$module_slugs"
3928
					),
3929
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
3930
				),
3931
				array( 'a' => array( 'href' => true, 'title' => true ) )
3932
			);
3933
		?></p>
3934
	</div>
3935
</div>
3936
<?php endif;
3937
	// only display the notice if the other stuff is not there
3938
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
3939
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
3940
			$this->opt_in_jetpack_manage_notice();
3941
		}
3942
	}
3943
3944
	/**
3945
	 * Record a stat for later output.  This will only currently output in the admin_footer.
3946
	 */
3947
	function stat( $group, $detail ) {
3948
		if ( ! isset( $this->stats[ $group ] ) )
3949
			$this->stats[ $group ] = array();
3950
		$this->stats[ $group ][] = $detail;
3951
	}
3952
3953
	/**
3954
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
3955
	 */
3956
	function do_stats( $method = '' ) {
3957
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
3958
			foreach ( $this->stats as $group => $stats ) {
3959
				if ( is_array( $stats ) && count( $stats ) ) {
3960
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
3961
					if ( 'server_side' === $method ) {
3962
						self::do_server_side_stat( $args );
3963
					} else {
3964
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
3965
					}
3966
				}
3967
				unset( $this->stats[ $group ] );
3968
			}
3969
		}
3970
	}
3971
3972
	/**
3973
	 * Runs stats code for a one-off, server-side.
3974
	 *
3975
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
3976
	 *
3977
	 * @return bool If it worked.
3978
	 */
3979
	static function do_server_side_stat( $args ) {
3980
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
3981
		if ( is_wp_error( $response ) )
3982
			return false;
3983
3984
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
3985
			return false;
3986
3987
		return true;
3988
	}
3989
3990
	/**
3991
	 * Builds the stats url.
3992
	 *
3993
	 * @param $args array|string The arguments to append to the URL.
3994
	 *
3995
	 * @return string The URL to be pinged.
3996
	 */
3997
	static function build_stats_url( $args ) {
3998
		$defaults = array(
3999
			'v'    => 'wpcom2',
4000
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4001
		);
4002
		$args     = wp_parse_args( $args, $defaults );
4003
		/**
4004
		 * Filter the URL used as the Stats tracking pixel.
4005
		 *
4006
		 * @since 2.3.2
4007
		 *
4008
		 * @param string $url Base URL used as the Stats tracking pixel.
4009
		 */
4010
		$base_url = apply_filters(
4011
			'jetpack_stats_base_url',
4012
			'https://pixel.wp.com/g.gif'
4013
		);
4014
		$url      = add_query_arg( $args, $base_url );
4015
		return $url;
4016
	}
4017
4018
	static function translate_current_user_to_role() {
4019
		foreach ( self::$capability_translations as $role => $cap ) {
4020
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4021
				return $role;
4022
			}
4023
		}
4024
4025
		return false;
4026
	}
4027
4028
	static function translate_role_to_cap( $role ) {
4029
		if ( ! isset( self::$capability_translations[$role] ) ) {
4030
			return false;
4031
		}
4032
4033
		return self::$capability_translations[$role];
4034
	}
4035
4036
	static function sign_role( $role ) {
4037
		if ( ! $user_id = (int) get_current_user_id() ) {
4038
			return false;
4039
		}
4040
4041
		$token = Jetpack_Data::get_access_token();
4042
		if ( ! $token || is_wp_error( $token ) ) {
4043
			return false;
4044
		}
4045
4046
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4047
	}
4048
4049
4050
	/**
4051
	 * Builds a URL to the Jetpack connection auth page
4052
	 *
4053
	 * @since 3.9.5
4054
	 *
4055
	 * @param bool $raw If true, URL will not be escaped.
4056
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4057
	 *                              If string, will be a custom redirect.
4058
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4059
	 *
4060
	 * @return string Connect URL
4061
	 */
4062
	function build_connect_url( $raw = false, $redirect = false, $from = false ) {
4063
		if ( ! Jetpack_Options::get_option( 'blog_token' ) || ! Jetpack_Options::get_option( 'id' ) ) {
4064
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4065
			if( is_network_admin() ) {
4066
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4067
			}
4068
		} else {
4069
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4070
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4071
			}
4072
4073
			$role = self::translate_current_user_to_role();
4074
			$signed_role = self::sign_role( $role );
4075
4076
			$user = wp_get_current_user();
4077
4078
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4079
			$redirect = $redirect
4080
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4081
				: $jetpack_admin_page;
4082
4083
			if( isset( $_REQUEST['is_multisite'] ) ) {
4084
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4085
			}
4086
4087
			$secrets = Jetpack::init()->generate_secrets( 'authorize' );
4088
			@list( $secret ) = explode( ':', $secrets );
4089
4090
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4091
				? get_site_icon_url()
4092
				: false;
4093
4094
			/**
4095
			 * Filter the type of authorization.
4096
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4097
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4098
			 *
4099
			 * @since 4.3.3
4100
			 *
4101
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4102
			 */
4103
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4104
4105
			$args = urlencode_deep(
4106
				array(
4107
					'response_type' => 'code',
4108
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4109
					'redirect_uri'  => add_query_arg(
4110
						array(
4111
							'action'   => 'authorize',
4112
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4113
							'redirect' => urlencode( $redirect ),
4114
						),
4115
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4116
					),
4117
					'state'         => $user->ID,
4118
					'scope'         => $signed_role,
4119
					'user_email'    => $user->user_email,
4120
					'user_login'    => $user->user_login,
4121
					'is_active'     => Jetpack::is_active(),
4122
					'jp_version'    => JETPACK__VERSION,
4123
					'auth_type'     => $auth_type,
4124
					'secret'        => $secret,
4125
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4126
					'blogname'      => get_option( 'blogname' ),
4127
					'site_url'      => site_url(),
4128
					'home_url'      => home_url(),
4129
					'site_icon'     => $site_icon,
4130
				)
4131
			);
4132
4133
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4134
		}
4135
4136
		if ( $from ) {
4137
			$url = add_query_arg( 'from', $from, $url );
4138
		}
4139
4140
		if ( isset( $_GET['calypso_env'] ) ) {
4141
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4142
		}
4143
4144
		return $raw ? $url : esc_url( $url );
4145
	}
4146
4147
	function build_reconnect_url( $raw = false ) {
4148
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4149
		return $raw ? $url : esc_url( $url );
4150
	}
4151
4152
	public static function admin_url( $args = null ) {
4153
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4154
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4155
		return $url;
4156
	}
4157
4158
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4159
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4160
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4161
	}
4162
4163
	function dismiss_jetpack_notice() {
4164
4165
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4166
			return;
4167
		}
4168
4169
		switch( $_GET['jetpack-notice'] ) {
4170
			case 'dismiss':
4171
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4172
4173
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4174
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4175
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4176
				}
4177
				break;
4178 View Code Duplication
			case 'jetpack-manage-opt-out':
4179
4180
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4181
					// Don't show the banner again
4182
4183
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4184
					// redirect back to the page that had the notice
4185
					if ( wp_get_referer() ) {
4186
						wp_safe_redirect( wp_get_referer() );
4187
					} else {
4188
						// Take me to Jetpack
4189
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4190
					}
4191
				}
4192
				break;
4193 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4194
4195
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4196
					// Don't show the banner again
4197
4198
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4199
					// redirect back to the page that had the notice
4200
					if ( wp_get_referer() ) {
4201
						wp_safe_redirect( wp_get_referer() );
4202
					} else {
4203
						// Take me to Jetpack
4204
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4205
					}
4206
				}
4207
				break;
4208
			case 'jetpack-manage-opt-in':
4209
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4210
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4211
4212
					$redirection_url = Jetpack::admin_url();
4213
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4214
4215
					// Don't redirect form the Jetpack Setting Page
4216
					$referer_parsed = parse_url ( wp_get_referer() );
4217
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4218
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4219
						// Take the user to Jetpack home except when on the setting page
4220
						$redirection_url = wp_get_referer();
4221
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4222
					}
4223
					// Also update the JSON API FULL MANAGEMENT Option
4224
					Jetpack::activate_module( 'manage', false, false );
4225
4226
					// Special Message when option in.
4227
					Jetpack::state( 'optin-manage', 'true' );
4228
					// Activate the Module if not activated already
4229
4230
					// Redirect properly
4231
					wp_safe_redirect( $redirection_url );
4232
4233
				}
4234
				break;
4235
		}
4236
	}
4237
4238
	function debugger_page() {
4239
		nocache_headers();
4240
		if ( ! current_user_can( 'manage_options' ) ) {
4241
			die( '-1' );
4242
		}
4243
		Jetpack_Debugger::jetpack_debug_display_handler();
4244
		exit;
4245
	}
4246
4247
	public static function admin_screen_configure_module( $module_id ) {
4248
4249
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4250
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4251
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4252
				/**
4253
				 * Fires to diplay a custom module activation screen.
4254
				 *
4255
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4256
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4257
				 *
4258
				 * @module manage
4259
				 *
4260
				 * @since 3.8.0
4261
				 *
4262
				 * @param int $module_id Module ID.
4263
				 */
4264
				do_action( 'display_activate_module_setting_' . $module_id );
4265
			} else {
4266
				self::display_activate_module_link( $module_id );
4267
			}
4268
4269
			return false;
4270
		} ?>
4271
4272
		<div id="jp-settings-screen" style="position: relative">
4273
			<h3>
4274
			<?php
4275
				$module = Jetpack::get_module( $module_id );
4276
				echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
4277
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4278
			?>
4279
			</h3>
4280
			<?php
4281
				/**
4282
				 * Fires within the displayed message when a feature configuation is updated.
4283
				 *
4284
				 * @since 3.4.0
4285
				 *
4286
				 * @param int $module_id Module ID.
4287
				 */
4288
				do_action( 'jetpack_notices_update_settings', $module_id );
4289
				/**
4290
				 * Fires when a feature configuation screen is loaded.
4291
				 * The dynamic part of the hook, $module_id, is the module ID.
4292
				 *
4293
				 * @since 1.1.0
4294
				 */
4295
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4296
			?>
4297
		</div><?php
4298
	}
4299
4300
	/**
4301
	 * Display link to activate the module to see the settings screen.
4302
	 * @param  string $module_id
4303
	 * @return null
4304
	 */
4305
	public static function display_activate_module_link( $module_id ) {
4306
4307
		$info =  Jetpack::get_module( $module_id );
4308
		$extra = '';
4309
		$activate_url = wp_nonce_url(
4310
				Jetpack::admin_url(
4311
					array(
4312
						'page'   => 'jetpack',
4313
						'action' => 'activate',
4314
						'module' => $module_id,
4315
					)
4316
				),
4317
				"jetpack_activate-$module_id"
4318
			);
4319
4320
		?>
4321
4322
		<div class="wrap configure-module">
4323
			<div id="jp-settings-screen">
4324
				<?php
4325
				if ( $module_id == 'json-api' ) {
4326
4327
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4328
4329
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4330
4331
					$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' );
4332
4333
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4334
				} ?>
4335
4336
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4337
				<div class="narrow">
4338
					<p><?php echo  $info['description']; ?></p>
4339
					<?php if( $extra ) { ?>
4340
					<p><?php echo esc_html( $extra ); ?></p>
4341
					<?php } ?>
4342
					<p>
4343
						<?php
4344
						if( wp_get_referer() ) {
4345
							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() );
4346
						} else {
4347
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4348
						} ?>
4349
					</p>
4350
				</div>
4351
4352
			</div>
4353
		</div>
4354
4355
		<?php
4356
	}
4357
4358
	public static function sort_modules( $a, $b ) {
4359
		if ( $a['sort'] == $b['sort'] )
4360
			return 0;
4361
4362
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4363
	}
4364
4365
	function ajax_recheck_ssl() {
4366
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4367
		$result = Jetpack::permit_ssl( true );
4368
		wp_send_json( array(
4369
			'enabled' => $result,
4370
			'message' => get_transient( 'jetpack_https_test_message' )
4371
		) );
4372
	}
4373
4374
/* Client API */
4375
4376
	/**
4377
	 * Returns the requested Jetpack API URL
4378
	 *
4379
	 * @return string
4380
	 */
4381
	public static function api_url( $relative_url ) {
4382
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4383
	}
4384
4385
	/**
4386
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4387
	 */
4388
	public static function fix_url_for_bad_hosts( $url ) {
4389
		if ( 0 !== strpos( $url, 'https://' ) ) {
4390
			return $url;
4391
		}
4392
4393
		switch ( JETPACK_CLIENT__HTTPS ) {
4394
			case 'ALWAYS' :
4395
				return $url;
4396
			case 'NEVER' :
4397
				return set_url_scheme( $url, 'http' );
4398
			// default : case 'AUTO' :
4399
		}
4400
4401
		// we now return the unmodified SSL URL by default, as a security precaution
4402
		return $url;
4403
	}
4404
4405
	/**
4406
	 * Checks to see if the URL is using SSL to connect with Jetpack
4407
	 *
4408
	 * @since 2.3.3
4409
	 * @return boolean
4410
	 */
4411
	public static function permit_ssl( $force_recheck = false ) {
4412
		// Do some fancy tests to see if ssl is being supported
4413
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4414
			$message = '';
4415
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4416
				$ssl = 0;
4417
			} else {
4418
				switch ( JETPACK_CLIENT__HTTPS ) {
4419
					case 'NEVER':
4420
						$ssl = 0;
4421
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4422
						break;
4423
					case 'ALWAYS':
4424
					case 'AUTO':
4425
					default:
4426
						$ssl = 1;
4427
						break;
4428
				}
4429
4430
				// If it's not 'NEVER', test to see
4431
				if ( $ssl ) {
4432
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4433
						$ssl = 0;
4434
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4435
					} else {
4436
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4437
						if ( is_wp_error( $response ) ) {
4438
							$ssl = 0;
4439
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4440
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4441
							$ssl = 0;
4442
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4443
						}
4444
					}
4445
				}
4446
			}
4447
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4448
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4449
		}
4450
4451
		return (bool) $ssl;
4452
	}
4453
4454
	/*
4455
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4456
	 */
4457
	public function alert_auto_ssl_fail() {
4458
		if ( ! current_user_can( 'manage_options' ) )
4459
			return;
4460
4461
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4462
		?>
4463
4464
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4465
			<div class="jp-banner__content">
4466
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4467
				<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>
4468
				<p>
4469
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4470
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4471
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4472
				</p>
4473
				<p>
4474
					<?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' ),
4475
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4476
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4477
				</p>
4478
			</div>
4479
		</div>
4480
		<style>
4481
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4482
		</style>
4483
		<script type="text/javascript">
4484
			jQuery( document ).ready( function( $ ) {
4485
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4486
					var $this = $( this );
4487
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4488
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4489
					e.preventDefault();
4490
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4491
					$.post( ajaxurl, data )
4492
					  .done( function( response ) {
4493
					  	if ( response.enabled ) {
4494
					  		$( '#jetpack-ssl-warning' ).hide();
4495
					  	} else {
4496
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4497
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4498
					  	}
4499
					  }.bind( $this ) );
4500
				} );
4501
			} );
4502
		</script>
4503
4504
		<?php
4505
	}
4506
4507
	/**
4508
	 * Returns the Jetpack XML-RPC API
4509
	 *
4510
	 * @return string
4511
	 */
4512
	public static function xmlrpc_api_url() {
4513
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4514
		return untrailingslashit( $base ) . '/xmlrpc.php';
4515
	}
4516
4517
	/**
4518
	 * Creates two secret tokens and the end of life timestamp for them.
4519
	 *
4520
	 * Note these tokens are unique per call, NOT static per site for connecting.
4521
	 *
4522
	 * @since 2.6
4523
	 * @return array
4524
	 */
4525
	public function generate_secrets( $action, $exp = 600 ) {
4526
	    $secret = wp_generate_password( 32, false ) // secret_1
4527
	    		. ':' . wp_generate_password( 32, false ) // secret_2
4528
	    		. ':' . ( time() + $exp ) // eol ( End of Life )
4529
	    		. ':' . get_current_user_id(); // ties the secrets to the current user
4530
		Jetpack_Options::update_option( $action, $secret );
4531
	    return Jetpack_Options::get_option( $action );
4532
	}
4533
4534
	/**
4535
	 * Builds the timeout limit for queries talking with the wpcom servers.
4536
	 *
4537
	 * Based on local php max_execution_time in php.ini
4538
	 *
4539
	 * @since 2.6
4540
	 * @return int
4541
	 **/
4542
	public function get_remote_query_timeout_limit() {
4543
	    $timeout = (int) ini_get( 'max_execution_time' );
4544
	    if ( ! $timeout ) // Ensure exec time set in php.ini
4545
				$timeout = 30;
4546
	    return intval( $timeout / 2 );
4547
	}
4548
4549
4550
	/**
4551
	 * Takes the response from the Jetpack register new site endpoint and
4552
	 * verifies it worked properly.
4553
	 *
4554
	 * @since 2.6
4555
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4556
	 **/
4557
	public function validate_remote_register_response( $response ) {
4558
	  if ( is_wp_error( $response ) ) {
4559
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4560
		}
4561
4562
		$code   = wp_remote_retrieve_response_code( $response );
4563
		$entity = wp_remote_retrieve_body( $response );
4564
		if ( $entity )
4565
			$registration_response = json_decode( $entity );
4566
		else
4567
			$registration_response = false;
4568
4569
		$code_type = intval( $code / 100 );
4570
		if ( 5 == $code_type ) {
4571
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4572
		} elseif ( 408 == $code ) {
4573
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4574
		} elseif ( ! empty( $registration_response->error ) ) {
4575
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4576
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
4577
			} else {
4578
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4579
			}
4580
4581
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4582
		} elseif ( 200 != $code ) {
4583
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4584
		}
4585
4586
		// Jetpack ID error block
4587
		if ( empty( $registration_response->jetpack_id ) ) {
4588
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4589
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4590
			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 );
4591
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4592
			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 );
4593
		}
4594
4595
	    return $registration_response;
4596
	}
4597
	/**
4598
	 * @return bool|WP_Error
4599
	 */
4600
	public static function register() {
4601
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4602
		$secrets = Jetpack::init()->generate_secrets( 'register' );
4603
4604
		@list( $secret_1, $secret_2, $secret_eol ) = explode( ':', $secrets );
4605 View Code Duplication
		if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
4606
			return new Jetpack_Error( 'missing_secrets' );
4607
		}
4608
4609
		$timeout = Jetpack::init()->get_remote_query_timeout_limit();
4610
4611
		$gmt_offset = get_option( 'gmt_offset' );
4612
		if ( ! $gmt_offset ) {
4613
			$gmt_offset = 0;
4614
		}
4615
4616
		$stats_options = get_option( 'stats_options' );
4617
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4618
4619
		$args = array(
4620
			'method'  => 'POST',
4621
			'body'    => array(
4622
				'siteurl'         => site_url(),
4623
				'home'            => home_url(),
4624
				'gmt_offset'      => $gmt_offset,
4625
				'timezone_string' => (string) get_option( 'timezone_string' ),
4626
				'site_name'       => (string) get_option( 'blogname' ),
4627
				'secret_1'        => $secret_1,
4628
				'secret_2'        => $secret_2,
4629
				'site_lang'       => get_locale(),
4630
				'timeout'         => $timeout,
4631
				'stats_id'        => $stats_id,
4632
				'state'           => get_current_user_id(),
4633
			),
4634
			'headers' => array(
4635
				'Accept' => 'application/json',
4636
			),
4637
			'timeout' => $timeout,
4638
		);
4639
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4640
4641
		// Make sure the response is valid and does not contain any Jetpack errors
4642
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4643
		if ( is_wp_error( $registration_details ) ) {
4644
		    return $registration_details;
4645
		} elseif ( ! $registration_details ) {
4646
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
4647
		}
4648
4649 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4650
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
4651
		}
4652
4653
		if ( isset( $registration_details->jetpack_public ) ) {
4654
			$jetpack_public = (int) $registration_details->jetpack_public;
4655
		} else {
4656
			$jetpack_public = false;
4657
		}
4658
4659
		Jetpack_Options::update_options(
4660
			array(
4661
				'id'         => (int)    $registration_details->jetpack_id,
4662
				'blog_token' => (string) $registration_details->jetpack_secret,
4663
				'public'     => $jetpack_public,
4664
			)
4665
		);
4666
4667
		/**
4668
		 * Fires when a site is registered on WordPress.com.
4669
		 *
4670
		 * @since 3.7.0
4671
		 *
4672
		 * @param int $json->jetpack_id Jetpack Blog ID.
4673
		 * @param string $json->jetpack_secret Jetpack Blog Token.
4674
		 * @param int|bool $jetpack_public Is the site public.
4675
		 */
4676
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
4677
4678
		// Initialize Jump Start for the first and only time.
4679
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
4680
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
4681
4682
			$jetpack = Jetpack::init();
4683
4684
			$jetpack->stat( 'jumpstart', 'unique-views' );
4685
			$jetpack->do_stats( 'server_side' );
4686
		};
4687
4688
		return true;
4689
	}
4690
4691
	/**
4692
	 * If the db version is showing something other that what we've got now, bump it to current.
4693
	 *
4694
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
4695
	 */
4696
	public static function maybe_set_version_option() {
4697
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
4698
		if ( JETPACK__VERSION != $version ) {
4699
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
4700
4701
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
4702
				/** This action is documented in class.jetpack.php */
4703
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
4704
			}
4705
4706
			return true;
4707
		}
4708
		return false;
4709
	}
4710
4711
/* Client Server API */
4712
4713
	/**
4714
	 * Loads the Jetpack XML-RPC client
4715
	 */
4716
	public static function load_xml_rpc_client() {
4717
		require_once ABSPATH . WPINC . '/class-IXR.php';
4718
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
4719
	}
4720
4721
	/**
4722
	 * Resets the saved authentication state in between testing requests.
4723
	 */
4724
	public function reset_saved_auth_state() {
4725
		$this->xmlrpc_verification = null;
4726
		$this->rest_authentication_status = null;
4727
	}
4728
4729
	function verify_xml_rpc_signature() {
4730
		if ( $this->xmlrpc_verification ) {
4731
			return $this->xmlrpc_verification;
4732
		}
4733
4734
		// It's not for us
4735
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
4736
			return false;
4737
		}
4738
4739
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
4740
		if (
4741
			empty( $token_key )
4742
		||
4743
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
4744
		) {
4745
			return false;
4746
		}
4747
4748
		if ( '0' === $user_id ) {
4749
			$token_type = 'blog';
4750
			$user_id = 0;
4751
		} else {
4752
			$token_type = 'user';
4753
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
4754
				return false;
4755
			}
4756
			$user_id = (int) $user_id;
4757
4758
			$user = new WP_User( $user_id );
4759
			if ( ! $user || ! $user->exists() ) {
4760
				return false;
4761
			}
4762
		}
4763
4764
		$token = Jetpack_Data::get_access_token( $user_id );
4765
		if ( ! $token ) {
4766
			return false;
4767
		}
4768
4769
		$token_check = "$token_key.";
4770
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
4771
			return false;
4772
		}
4773
4774
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
4775
4776
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
4777
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
4778
			$post_data   = $_POST;
4779
			$file_hashes = array();
4780
			foreach ( $post_data as $post_data_key => $post_data_value ) {
4781
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
4782
					continue;
4783
				}
4784
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
4785
				$file_hashes[$post_data_key] = $post_data_value;
4786
			}
4787
4788
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
4789
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
4790
				$post_data[$post_data_key] = $post_data_value;
4791
			}
4792
4793
			ksort( $post_data );
4794
4795
			$body = http_build_query( stripslashes_deep( $post_data ) );
4796
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
4797
			$body = file_get_contents( 'php://input' );
4798
		} else {
4799
			$body = null;
4800
		}
4801
4802
		$signature = $jetpack_signature->sign_current_request(
4803
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
4804
		);
4805
4806
		if ( ! $signature ) {
4807
			return false;
4808
		} else if ( is_wp_error( $signature ) ) {
4809
			return $signature;
4810
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
4811
			return false;
4812
		}
4813
4814
		$timestamp = (int) $_GET['timestamp'];
4815
		$nonce     = stripslashes( (string) $_GET['nonce'] );
4816
4817
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
4818
			return false;
4819
		}
4820
4821
		$this->xmlrpc_verification = array(
4822
			'type'    => $token_type,
4823
			'user_id' => $token->external_user_id,
4824
		);
4825
4826
		return $this->xmlrpc_verification;
4827
	}
4828
4829
	/**
4830
	 * Authenticates XML-RPC and other requests from the Jetpack Server
4831
	 */
4832
	function authenticate_jetpack( $user, $username, $password ) {
4833
		if ( is_a( $user, 'WP_User' ) ) {
4834
			return $user;
4835
		}
4836
4837
		$token_details = $this->verify_xml_rpc_signature();
4838
4839
		if ( ! $token_details || is_wp_error( $token_details ) ) {
4840
			return $user;
4841
		}
4842
4843
		if ( 'user' !== $token_details['type'] ) {
4844
			return $user;
4845
		}
4846
4847
		if ( ! $token_details['user_id'] ) {
4848
			return $user;
4849
		}
4850
4851
		nocache_headers();
4852
4853
		return new WP_User( $token_details['user_id'] );
4854
	}
4855
4856
	// Authenticates requests from Jetpack server to WP REST API endpoints.
4857
	// Uses the existing XMLRPC request signing implementation.
4858
	function wp_rest_authenticate( $user ) {
4859
		if ( ! empty( $user ) ) {
4860
			// Another authentication method is in effect.
4861
			return $user;
4862
		}
4863
4864
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
4865
			// Nothing to do for this authentication method.
4866
			return null;
4867
		}
4868
4869
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
4870
			// Nothing to do for this authentication method.
4871
			return null;
4872
		}
4873
4874
		// Ensure that we always have the request body available.  At this
4875
		// point, the WP REST API code to determine the request body has not
4876
		// run yet.  That code may try to read from 'php://input' later, but
4877
		// this can only be done once per request in PHP versions prior to 5.6.
4878
		// So we will go ahead and perform this read now if needed, and save
4879
		// the request body where both the Jetpack signature verification code
4880
		// and the WP REST API code can see it.
4881
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
4882
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
4883
		}
4884
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
4885
4886
		// Only support specific request parameters that have been tested and
4887
		// are known to work with signature verification.  A different method
4888
		// can be passed to the WP REST API via the '?_method=' parameter if
4889
		// needed.
4890
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
4891
			$this->rest_authentication_status = new WP_Error(
4892
				'rest_invalid_request',
4893
				__( 'This request method is not supported.', 'jetpack' ),
4894
				array( 'status' => 400 )
4895
			);
4896
			return null;
4897
		}
4898
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
4899
			$this->rest_authentication_status = new WP_Error(
4900
				'rest_invalid_request',
4901
				__( 'This request method does not support body parameters.', 'jetpack' ),
4902
				array( 'status' => 400 )
4903
			);
4904
			return null;
4905
		}
4906
4907
		if ( ! empty( $_SERVER['CONTENT_TYPE'] ) ) {
4908
			$content_type = $_SERVER['CONTENT_TYPE'];
4909
		} elseif ( ! empty( $_SERVER['HTTP_CONTENT_TYPE'] ) ) {
4910
			$content_type = $_SERVER['HTTP_CONTENT_TYPE'];
4911
		}
4912
4913
		if (
4914
			isset( $content_type ) &&
4915
			$content_type !== 'application/x-www-form-urlencoded' &&
4916
			$content_type !== 'application/json'
4917
		) {
4918
			$this->rest_authentication_status = new WP_Error(
4919
				'rest_invalid_request',
4920
				__( 'This Content-Type is not supported.', 'jetpack' ),
4921
				array( 'status' => 400 )
4922
			);
4923
			return null;
4924
		}
4925
4926
		$verified = $this->verify_xml_rpc_signature();
4927
4928
		if ( is_wp_error( $verified ) ) {
4929
			$this->rest_authentication_status = $verified;
4930
			return null;
4931
		}
4932
4933
		if (
4934
			$verified &&
4935
			isset( $verified['type'] ) &&
4936
			'user' === $verified['type'] &&
4937
			! empty( $verified['user_id'] )
4938
		) {
4939
			// Authentication successful.
4940
			$this->rest_authentication_status = true;
4941
			return $verified['user_id'];
4942
		}
4943
4944
		// Something else went wrong.  Probably a signature error.
4945
		$this->rest_authentication_status = new WP_Error(
4946
			'rest_invalid_signature',
4947
			__( 'The request is not signed correctly.', 'jetpack' ),
4948
			array( 'status' => 400 )
4949
		);
4950
		return null;
4951
	}
4952
4953
	/**
4954
	 * Report authentication status to the WP REST API.
4955
	 *
4956
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
4957
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
4958
	 */
4959
	public function wp_rest_authentication_errors( $value ) {
4960
		if ( $value !== null ) {
4961
			return $value;
4962
		}
4963
		return $this->rest_authentication_status;
4964
	}
4965
4966
	function add_nonce( $timestamp, $nonce ) {
4967
		global $wpdb;
4968
		static $nonces_used_this_request = array();
4969
4970
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
4971
			return $nonces_used_this_request["$timestamp:$nonce"];
4972
		}
4973
4974
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
4975
		$timestamp = (int) $timestamp;
4976
		$nonce     = esc_sql( $nonce );
4977
4978
		// Raw query so we can avoid races: add_option will also update
4979
		$show_errors = $wpdb->show_errors( false );
4980
4981
		$old_nonce = $wpdb->get_row(
4982
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
4983
		);
4984
4985
		if ( is_null( $old_nonce ) ) {
4986
			$return = $wpdb->query(
4987
				$wpdb->prepare(
4988
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
4989
					"jetpack_nonce_{$timestamp}_{$nonce}",
4990
					time(),
4991
					'no'
4992
				)
4993
			);
4994
		} else {
4995
			$return = false;
4996
		}
4997
4998
		$wpdb->show_errors( $show_errors );
4999
5000
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5001
5002
		return $return;
5003
	}
5004
5005
	/**
5006
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5007
	 * Capture it here so we can verify the signature later.
5008
	 */
5009
	function xmlrpc_methods( $methods ) {
5010
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5011
		return $methods;
5012
	}
5013
5014
	function public_xmlrpc_methods( $methods ) {
5015
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5016
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5017
		}
5018
		return $methods;
5019
	}
5020
5021
	function jetpack_getOptions( $args ) {
5022
		global $wp_xmlrpc_server;
5023
5024
		$wp_xmlrpc_server->escape( $args );
5025
5026
		$username	= $args[1];
5027
		$password	= $args[2];
5028
5029
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5030
			return $wp_xmlrpc_server->error;
5031
		}
5032
5033
		$options = array();
5034
		$user_data = $this->get_connected_user_data();
5035
		if ( is_array( $user_data ) ) {
5036
			$options['jetpack_user_id'] = array(
5037
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5038
				'readonly'      => true,
5039
				'value'         => $user_data['ID'],
5040
			);
5041
			$options['jetpack_user_login'] = array(
5042
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5043
				'readonly'      => true,
5044
				'value'         => $user_data['login'],
5045
			);
5046
			$options['jetpack_user_email'] = array(
5047
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5048
				'readonly'      => true,
5049
				'value'         => $user_data['email'],
5050
			);
5051
			$options['jetpack_user_site_count'] = array(
5052
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5053
				'readonly'      => true,
5054
				'value'         => $user_data['site_count'],
5055
			);
5056
		}
5057
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5058
		$args = stripslashes_deep( $args );
5059
		return $wp_xmlrpc_server->wp_getOptions( $args );
5060
	}
5061
5062
	function xmlrpc_options( $options ) {
5063
		$jetpack_client_id = false;
5064
		if ( self::is_active() ) {
5065
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5066
		}
5067
		$options['jetpack_version'] = array(
5068
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5069
				'readonly'      => true,
5070
				'value'         => JETPACK__VERSION,
5071
		);
5072
5073
		$options['jetpack_client_id'] = array(
5074
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5075
				'readonly'      => true,
5076
				'value'         => $jetpack_client_id,
5077
		);
5078
		return $options;
5079
	}
5080
5081
	public static function clean_nonces( $all = false ) {
5082
		global $wpdb;
5083
5084
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5085
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5086
5087
		if ( true !== $all ) {
5088
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5089
			$sql_args[] = time() - 3600;
5090
		}
5091
5092
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5093
5094
		$sql = $wpdb->prepare( $sql, $sql_args );
5095
5096
		for ( $i = 0; $i < 1000; $i++ ) {
5097
			if ( ! $wpdb->query( $sql ) ) {
5098
				break;
5099
			}
5100
		}
5101
	}
5102
5103
	/**
5104
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5105
	 * SET: state( $key, $value );
5106
	 * GET: $value = state( $key );
5107
	 *
5108
	 * @param string $key
5109
	 * @param string $value
5110
	 * @param bool $restate private
5111
	 */
5112
	public static function state( $key = null, $value = null, $restate = false ) {
5113
		static $state = array();
5114
		static $path, $domain;
5115
		if ( ! isset( $path ) ) {
5116
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5117
			$admin_url = Jetpack::admin_url();
5118
			$bits      = parse_url( $admin_url );
5119
5120
			if ( is_array( $bits ) ) {
5121
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5122
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5123
			} else {
5124
				$path = $domain = null;
5125
			}
5126
		}
5127
5128
		// Extract state from cookies and delete cookies
5129
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5130
			$yum = $_COOKIE[ 'jetpackState' ];
5131
			unset( $_COOKIE[ 'jetpackState' ] );
5132
			foreach ( $yum as $k => $v ) {
5133
				if ( strlen( $v ) )
5134
					$state[ $k ] = $v;
5135
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5136
			}
5137
		}
5138
5139
		if ( $restate ) {
5140
			foreach ( $state as $k => $v ) {
5141
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5142
			}
5143
			return;
5144
		}
5145
5146
		// Get a state variable
5147
		if ( isset( $key ) && ! isset( $value ) ) {
5148
			if ( array_key_exists( $key, $state ) )
5149
				return $state[ $key ];
5150
			return null;
5151
		}
5152
5153
		// Set a state variable
5154
		if ( isset ( $key ) && isset( $value ) ) {
5155
			if( is_array( $value ) && isset( $value[0] ) ) {
5156
				$value = $value[0];
5157
			}
5158
			$state[ $key ] = $value;
5159
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5160
		}
5161
	}
5162
5163
	public static function restate() {
5164
		Jetpack::state( null, null, true );
5165
	}
5166
5167
	public static function check_privacy( $file ) {
5168
		static $is_site_publicly_accessible = null;
5169
5170
		if ( is_null( $is_site_publicly_accessible ) ) {
5171
			$is_site_publicly_accessible = false;
5172
5173
			Jetpack::load_xml_rpc_client();
5174
			$rpc = new Jetpack_IXR_Client();
5175
5176
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5177
			if ( $success ) {
5178
				$response = $rpc->getResponse();
5179
				if ( $response ) {
5180
					$is_site_publicly_accessible = true;
5181
				}
5182
			}
5183
5184
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5185
		}
5186
5187
		if ( $is_site_publicly_accessible ) {
5188
			return;
5189
		}
5190
5191
		$module_slug = self::get_module_slug( $file );
5192
5193
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5194
		if ( ! $privacy_checks ) {
5195
			$privacy_checks = $module_slug;
5196
		} else {
5197
			$privacy_checks .= ",$module_slug";
5198
		}
5199
5200
		Jetpack::state( 'privacy_checks', $privacy_checks );
5201
	}
5202
5203
	/**
5204
	 * Helper method for multicall XMLRPC.
5205
	 */
5206
	public static function xmlrpc_async_call() {
5207
		global $blog_id;
5208
		static $clients = array();
5209
5210
		$client_blog_id = is_multisite() ? $blog_id : 0;
5211
5212
		if ( ! isset( $clients[$client_blog_id] ) ) {
5213
			Jetpack::load_xml_rpc_client();
5214
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5215
			if ( function_exists( 'ignore_user_abort' ) ) {
5216
				ignore_user_abort( true );
5217
			}
5218
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5219
		}
5220
5221
		$args = func_get_args();
5222
5223
		if ( ! empty( $args[0] ) ) {
5224
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5225
		} elseif ( is_multisite() ) {
5226
			foreach ( $clients as $client_blog_id => $client ) {
5227
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5228
					continue;
5229
				}
5230
5231
				$switch_success = switch_to_blog( $client_blog_id, true );
5232
				if ( ! $switch_success ) {
5233
					continue;
5234
				}
5235
5236
				flush();
5237
				$client->query();
5238
5239
				restore_current_blog();
5240
			}
5241
		} else {
5242
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5243
				flush();
5244
				$clients[0]->query();
5245
			}
5246
		}
5247
	}
5248
5249
	public static function staticize_subdomain( $url ) {
5250
5251
		// Extract hostname from URL
5252
		$host = parse_url( $url, PHP_URL_HOST );
5253
5254
		// Explode hostname on '.'
5255
		$exploded_host = explode( '.', $host );
5256
5257
		// Retrieve the name and TLD
5258
		if ( count( $exploded_host ) > 1 ) {
5259
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5260
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5261
			// Rebuild domain excluding subdomains
5262
			$domain = $name . '.' . $tld;
5263
		} else {
5264
			$domain = $host;
5265
		}
5266
		// Array of Automattic domains
5267
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5268
5269
		// Return $url if not an Automattic domain
5270
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5271
			return $url;
5272
		}
5273
5274
		if ( is_ssl() ) {
5275
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5276
		}
5277
5278
		srand( crc32( basename( $url ) ) );
5279
		$static_counter = rand( 0, 2 );
5280
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5281
5282
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5283
	}
5284
5285
/* JSON API Authorization */
5286
5287
	/**
5288
	 * Handles the login action for Authorizing the JSON API
5289
	 */
5290
	function login_form_json_api_authorization() {
5291
		$this->verify_json_api_authorization_request();
5292
5293
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5294
5295
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5296
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5297
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5298
	}
5299
5300
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5301
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5302
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5303
			return $url;
5304
		}
5305
5306
		$parsed_url = parse_url( $url );
5307
		$url = strtok( $url, '?' );
5308
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5309
		if ( ! empty( $parsed_url['query'] ) )
5310
			$url .= "&{$parsed_url['query']}";
5311
5312
		return $url;
5313
	}
5314
5315
	// Make sure the POSTed request is handled by the same action
5316
	function preserve_action_in_login_form_for_json_api_authorization() {
5317
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5318
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5319
	}
5320
5321
	// If someone logs in to approve API access, store the Access Code in usermeta
5322
	function store_json_api_authorization_token( $user_login, $user ) {
5323
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5324
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5325
		$token = wp_generate_password( 32, false );
5326
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5327
	}
5328
5329
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5330
	function allow_wpcom_public_api_domain( $domains ) {
5331
		$domains[] = 'public-api.wordpress.com';
5332
		return $domains;
5333
	}
5334
5335
	// Add the Access Code details to the public-api.wordpress.com redirect
5336
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5337
		return add_query_arg(
5338
			urlencode_deep(
5339
				array(
5340
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5341
					'jetpack-user-id' => (int) $user->ID,
5342
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5343
				)
5344
			),
5345
			$redirect_to
5346
		);
5347
	}
5348
5349
5350
	/**
5351
	 * Verifies the request by checking the signature
5352
	 *
5353
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5354
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5355
	 *
5356
	 * @param null|array $environment
5357
	 */
5358
	function verify_json_api_authorization_request( $environment = null ) {
5359
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5360
5361
		$environment = is_null( $environment )
5362
			? $_REQUEST
5363
			: $environment;
5364
5365
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
5366
		$token = Jetpack_Data::get_access_token( $envUserId );
5367
		if ( ! $token || empty( $token->secret ) ) {
5368
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5369
		}
5370
5371
		$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' );
5372
5373
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5374
5375
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5376
			$signature = $jetpack_signature->sign_request(
5377
				$environment['token'],
5378
				$environment['timestamp'],
5379
				$environment['nonce'],
5380
				'',
5381
				'GET',
5382
				$environment['jetpack_json_api_original_query'],
5383
				null,
5384
				true
5385
			);
5386
		} else {
5387
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5388
		}
5389
5390
		if ( ! $signature ) {
5391
			wp_die( $die_error );
5392
		} else if ( is_wp_error( $signature ) ) {
5393
			wp_die( $die_error );
5394
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5395
			if ( is_ssl() ) {
5396
				// 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
5397
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5398
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5399
					wp_die( $die_error );
5400
				}
5401
			} else {
5402
				wp_die( $die_error );
5403
			}
5404
		}
5405
5406
		$timestamp = (int) $environment['timestamp'];
5407
		$nonce     = stripslashes( (string) $environment['nonce'] );
5408
5409
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5410
			// De-nonce the nonce, at least for 5 minutes.
5411
			// 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)
5412
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5413
			if ( $old_nonce_time < time() - 300 ) {
5414
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5415
			}
5416
		}
5417
5418
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5419
		$data_filters = array(
5420
			'state'        => 'opaque',
5421
			'client_id'    => 'int',
5422
			'client_title' => 'string',
5423
			'client_image' => 'url',
5424
		);
5425
5426
		foreach ( $data_filters as $key => $sanitation ) {
5427
			if ( ! isset( $data->$key ) ) {
5428
				wp_die( $die_error );
5429
			}
5430
5431
			switch ( $sanitation ) {
5432
			case 'int' :
5433
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5434
				break;
5435
			case 'opaque' :
5436
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5437
				break;
5438
			case 'string' :
5439
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5440
				break;
5441
			case 'url' :
5442
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5443
				break;
5444
			}
5445
		}
5446
5447
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5448
			wp_die( $die_error );
5449
		}
5450
	}
5451
5452
	function login_message_json_api_authorization( $message ) {
5453
		return '<p class="message">' . sprintf(
5454
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5455
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5456
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5457
	}
5458
5459
	/**
5460
	 * Get $content_width, but with a <s>twist</s> filter.
5461
	 */
5462
	public static function get_content_width() {
5463
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5464
		/**
5465
		 * Filter the Content Width value.
5466
		 *
5467
		 * @since 2.2.3
5468
		 *
5469
		 * @param string $content_width Content Width value.
5470
		 */
5471
		return apply_filters( 'jetpack_content_width', $content_width );
5472
	}
5473
5474
	/**
5475
	 * Pings the WordPress.com Mirror Site for the specified options.
5476
	 *
5477
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5478
	 *
5479
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5480
	 */
5481
	public function get_cloud_site_options( $option_names ) {
5482
		$option_names = array_filter( (array) $option_names, 'is_string' );
5483
5484
		Jetpack::load_xml_rpc_client();
5485
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5486
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5487
		if ( $xml->isError() ) {
5488
			return array(
5489
				'error_code' => $xml->getErrorCode(),
5490
				'error_msg'  => $xml->getErrorMessage(),
5491
			);
5492
		}
5493
		$cloud_site_options = $xml->getResponse();
5494
5495
		return $cloud_site_options;
5496
	}
5497
5498
	/**
5499
	 * Checks if the site is currently in an identity crisis.
5500
	 *
5501
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5502
	 */
5503
	public static function check_identity_crisis() {
5504
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5505
			return false;
5506
		}
5507
5508
		return Jetpack_Options::get_option( 'sync_error_idc' );
5509
	}
5510
5511
	/**
5512
	 * Checks whether the home and siteurl specifically are whitelisted
5513
	 * Written so that we don't have re-check $key and $value params every time
5514
	 * we want to check if this site is whitelisted, for example in footer.php
5515
	 *
5516
	 * @since  3.8.0
5517
	 * @return bool True = already whitelisted False = not whitelisted
5518
	 */
5519
	public static function is_staging_site() {
5520
		$is_staging = false;
5521
5522
		$known_staging = array(
5523
			'urls' => array(
5524
				'#\.staging\.wpengine\.com$#i', // WP Engine
5525
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5526
				),
5527
			'constants' => array(
5528
				'IS_WPE_SNAPSHOT',      // WP Engine
5529
				'KINSTA_DEV_ENV',       // Kinsta.com
5530
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5531
				'JETPACK_STAGING_MODE', // Generic
5532
				)
5533
			);
5534
		/**
5535
		 * Filters the flags of known staging sites.
5536
		 *
5537
		 * @since 3.9.0
5538
		 *
5539
		 * @param array $known_staging {
5540
		 *     An array of arrays that each are used to check if the current site is staging.
5541
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5542
		 *     @type array $constants PHP constants of known staging/developement environments.
5543
		 *  }
5544
		 */
5545
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5546
5547
		if ( isset( $known_staging['urls'] ) ) {
5548
			foreach ( $known_staging['urls'] as $url ){
5549
				if ( preg_match( $url, site_url() ) ) {
5550
					$is_staging = true;
5551
					break;
5552
				}
5553
			}
5554
		}
5555
5556
		if ( isset( $known_staging['constants'] ) ) {
5557
			foreach ( $known_staging['constants'] as $constant ) {
5558
				if ( defined( $constant ) && constant( $constant ) ) {
5559
					$is_staging = true;
5560
				}
5561
			}
5562
		}
5563
5564
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5565
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5566
			$is_staging = true;
5567
		}
5568
5569
		/**
5570
		 * Filters is_staging_site check.
5571
		 *
5572
		 * @since 3.9.0
5573
		 *
5574
		 * @param bool $is_staging If the current site is a staging site.
5575
		 */
5576
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5577
	}
5578
5579
	/**
5580
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5581
	 *
5582
	 * @return bool
5583
	 */
5584
	public static function validate_sync_error_idc_option() {
5585
		$is_valid = false;
5586
5587
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5588
		if ( false === $idc_allowed ) {
5589
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5590
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5591
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5592
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5593
				$transient_duration = HOUR_IN_SECONDS;
5594
			} else {
5595
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5596
				$idc_allowed = '1';
5597
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5598
			}
5599
5600
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5601
		}
5602
5603
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5604
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5605
		$local_options = self::get_sync_error_idc_option();
5606
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5607
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5608
				$is_valid = true;
5609
			}
5610
		}
5611
5612
		/**
5613
		 * Filters whether the sync_error_idc option is valid.
5614
		 *
5615
		 * @since 4.4.0
5616
		 *
5617
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5618
		 */
5619
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5620
5621
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5622
			// Since the option exists, and did not validate, delete it
5623
			Jetpack_Options::delete_option( 'sync_error_idc' );
5624
		}
5625
5626
		return $is_valid;
5627
	}
5628
5629
	/**
5630
	 * Normalizes a url by doing three things:
5631
	 *  - Strips protocol
5632
	 *  - Strips www
5633
	 *  - Adds a trailing slash
5634
	 *
5635
	 * @since 4.4.0
5636
	 * @param string $url
5637
	 * @return WP_Error|string
5638
	 */
5639
	public static function normalize_url_protocol_agnostic( $url ) {
5640
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5641
		if ( ! $parsed_url ) {
5642
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5643
		}
5644
5645
		// Strip www and protocols
5646
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5647
		return $url;
5648
	}
5649
5650
	/**
5651
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5652
	 *
5653
	 * @since 4.4.0
5654
	 *
5655
	 * @param array $response
5656
	 * @return array Array of the local urls, wpcom urls, and error code
5657
	 */
5658
	public static function get_sync_error_idc_option( $response = array() ) {
5659
		$local_options = array(
5660
			'home' => get_home_url(),
5661
			'siteurl' => get_site_url(),
5662
		);
5663
5664
		$options = array_merge( $local_options, $response );
5665
5666
		$returned_values = array();
5667
		foreach( $options as $key => $option ) {
5668
			if ( 'error_code' === $key ) {
5669
				$returned_values[ $key ] = $option;
5670
				continue;
5671
			}
5672
5673
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5674
				continue;
5675
			}
5676
5677
			$returned_values[ $key ] = $normalized_url;
5678
		}
5679
5680
		return $returned_values;
5681
	}
5682
5683
	/**
5684
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5685
	 * If set to true, the site will be put into staging mode.
5686
	 *
5687
	 * @since 4.3.2
5688
	 * @return bool
5689
	 */
5690
	public static function sync_idc_optin() {
5691
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5692
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5693
		} else {
5694
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5695
		}
5696
5697
		/**
5698
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5699
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5700
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5701
		 *
5702
		 * @since 4.3.2
5703
		 *
5704
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5705
		 */
5706
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5707
	}
5708
5709
	/**
5710
	 * Maybe Use a .min.css stylesheet, maybe not.
5711
	 *
5712
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5713
	 */
5714
	public static function maybe_min_asset( $url, $path, $plugin ) {
5715
		// Short out on things trying to find actual paths.
5716
		if ( ! $path || empty( $plugin ) ) {
5717
			return $url;
5718
		}
5719
5720
		// Strip out the abspath.
5721
		$base = dirname( plugin_basename( $plugin ) );
5722
5723
		// Short out on non-Jetpack assets.
5724
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5725
			return $url;
5726
		}
5727
5728
		// File name parsing.
5729
		$file              = "{$base}/{$path}";
5730
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5731
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5732
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5733
		$extension         = array_shift( $file_name_parts_r );
5734
5735
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5736
			// Already pointing at the minified version.
5737
			if ( 'min' === $file_name_parts_r[0] ) {
5738
				return $url;
5739
			}
5740
5741
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5742
			if ( file_exists( $min_full_path ) ) {
5743
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5744
			}
5745
		}
5746
5747
		return $url;
5748
	}
5749
5750
	/**
5751
	 * Maybe inlines a stylesheet.
5752
	 *
5753
	 * If you'd like to inline a stylesheet instead of printing a link to it,
5754
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
5755
	 *
5756
	 * Attached to `style_loader_tag` filter.
5757
	 *
5758
	 * @param string $tag The tag that would link to the external asset.
5759
	 * @param string $handle The registered handle of the script in question.
5760
	 *
5761
	 * @return string
5762
	 */
5763
	public static function maybe_inline_style( $tag, $handle ) {
5764
		global $wp_styles;
5765
		$item = $wp_styles->registered[ $handle ];
5766
5767
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
5768
			return $tag;
5769
		}
5770
5771
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
5772
			$href = $matches[1];
5773
			// Strip off query string
5774
			if ( $pos = strpos( $href, '?' ) ) {
5775
				$href = substr( $href, 0, $pos );
5776
			}
5777
			// Strip off fragment
5778
			if ( $pos = strpos( $href, '#' ) ) {
5779
				$href = substr( $href, 0, $pos );
5780
			}
5781
		} else {
5782
			return $tag;
5783
		}
5784
5785
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
5786
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
5787
			return $tag;
5788
		}
5789
5790
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
5791
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
5792
			// And this isn't the pass that actually deals with the RTL version...
5793
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
5794
				// Short out, as the RTL version will deal with it in a moment.
5795
				return $tag;
5796
			}
5797
		}
5798
5799
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
5800
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
5801
		if ( $css ) {
5802
			$tag = "<!-- Inline {$item->handle} -->\r\n";
5803
			if ( empty( $item->extra['after'] ) ) {
5804
				wp_add_inline_style( $handle, $css );
5805
			} else {
5806
				array_unshift( $item->extra['after'], $css );
5807
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
5808
			}
5809
		}
5810
5811
		return $tag;
5812
	}
5813
5814
	/**
5815
	 * Loads a view file from the views
5816
	 *
5817
	 * Data passed in with the $data parameter will be available in the
5818
	 * template file as $data['value']
5819
	 *
5820
	 * @param string $template - Template file to load
5821
	 * @param array $data - Any data to pass along to the template
5822
	 * @return boolean - If template file was found
5823
	 **/
5824
	public function load_view( $template, $data = array() ) {
5825
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
5826
5827
		if( file_exists( $views_dir . $template ) ) {
5828
			require_once( $views_dir . $template );
5829
			return true;
5830
		}
5831
5832
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
5833
		return false;
5834
	}
5835
5836
	/**
5837
	 * Throws warnings for deprecated hooks to be removed from Jetpack
5838
	 */
5839
	public function deprecated_hooks() {
5840
		global $wp_filter;
5841
5842
		/*
5843
		 * Format:
5844
		 * deprecated_filter_name => replacement_name
5845
		 *
5846
		 * If there is no replacement, use null for replacement_name
5847
		 */
5848
		$deprecated_list = array(
5849
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
5850
			'wpl_sharing_2014_1'                                     => null,
5851
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
5852
			'jetpack_identity_crisis_options_to_check'               => null,
5853
			'update_option_jetpack_single_user_site'                 => null,
5854
			'audio_player_default_colors'                            => null,
5855
			'add_option_jetpack_featured_images_enabled'             => null,
5856
			'add_option_jetpack_update_details'                      => null,
5857
			'add_option_jetpack_updates'                             => null,
5858
			'add_option_jetpack_network_name'                        => null,
5859
			'add_option_jetpack_network_allow_new_registrations'     => null,
5860
			'add_option_jetpack_network_add_new_users'               => null,
5861
			'add_option_jetpack_network_site_upload_space'           => null,
5862
			'add_option_jetpack_network_upload_file_types'           => null,
5863
			'add_option_jetpack_network_enable_administration_menus' => null,
5864
			'add_option_jetpack_is_multi_site'                       => null,
5865
			'add_option_jetpack_is_main_network'                     => null,
5866
			'add_option_jetpack_main_network_site'                   => null,
5867
			'jetpack_sync_all_registered_options'                    => null,
5868
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
5869
			'jetpack_is_post_mailable'                               => null,
5870
		);
5871
5872
		// This is a silly loop depth. Better way?
5873
		foreach( $deprecated_list AS $hook => $hook_alt ) {
5874
			if ( has_action( $hook ) ) {
5875
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
5876
					foreach( $values AS $hooked ) {
5877
						if ( is_callable( $hooked['function'] ) ) {
5878
							$function_name = 'an anonymous function';
5879
						} else {
5880
							$function_name = $hooked['function'];
5881
						}
5882
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
5883
					}
5884
				}
5885
			}
5886
		}
5887
	}
5888
5889
	/**
5890
	 * Converts any url in a stylesheet, to the correct absolute url.
5891
	 *
5892
	 * Considerations:
5893
	 *  - Normal, relative URLs     `feh.png`
5894
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
5895
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
5896
	 *  - Absolute URLs             `http://domain.com/feh.png`
5897
	 *  - Domain root relative URLs `/feh.png`
5898
	 *
5899
	 * @param $css string: The raw CSS -- should be read in directly from the file.
5900
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
5901
	 *
5902
	 * @return mixed|string
5903
	 */
5904
	public static function absolutize_css_urls( $css, $css_file_url ) {
5905
		$pattern = '#url\((?P<path>[^)]*)\)#i';
5906
		$css_dir = dirname( $css_file_url );
5907
		$p       = parse_url( $css_dir );
5908
		$domain  = sprintf(
5909
					'%1$s//%2$s%3$s%4$s',
5910
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
5911
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5912
					$p['host'],
5913
					isset( $p['port'] )             ? ":{$p['port']}" : ''
5914
				);
5915
5916
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5917
			$find = $replace = array();
5918
			foreach ( $matches as $match ) {
5919
				$url = trim( $match['path'], "'\" \t" );
5920
5921
				// If this is a data url, we don't want to mess with it.
5922
				if ( 'data:' === substr( $url, 0, 5 ) ) {
5923
					continue;
5924
				}
5925
5926
				// If this is an absolute or protocol-agnostic url,
5927
				// we don't want to mess with it.
5928
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5929
					continue;
5930
				}
5931
5932
				switch ( substr( $url, 0, 1 ) ) {
5933
					case '/':
5934
						$absolute = $domain . $url;
5935
						break;
5936
					default:
5937
						$absolute = $css_dir . '/' . $url;
5938
				}
5939
5940
				$find[]    = $match[0];
5941
				$replace[] = sprintf( 'url("%s")', $absolute );
5942
			}
5943
			$css = str_replace( $find, $replace, $css );
5944
		}
5945
5946
		return $css;
5947
	}
5948
5949
	/**
5950
	 * This methods removes all of the registered css files on the front end
5951
	 * from Jetpack in favor of using a single file. In effect "imploding"
5952
	 * all the files into one file.
5953
	 *
5954
	 * Pros:
5955
	 * - Uses only ONE css asset connection instead of 15
5956
	 * - Saves a minimum of 56k
5957
	 * - Reduces server load
5958
	 * - Reduces time to first painted byte
5959
	 *
5960
	 * Cons:
5961
	 * - Loads css for ALL modules. However all selectors are prefixed so it
5962
	 *		should not cause any issues with themes.
5963
	 * - Plugins/themes dequeuing styles no longer do anything. See
5964
	 *		jetpack_implode_frontend_css filter for a workaround
5965
	 *
5966
	 * For some situations developers may wish to disable css imploding and
5967
	 * instead operate in legacy mode where each file loads seperately and
5968
	 * can be edited individually or dequeued. This can be accomplished with
5969
	 * the following line:
5970
	 *
5971
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
5972
	 *
5973
	 * @since 3.2
5974
	 **/
5975
	public function implode_frontend_css( $travis_test = false ) {
5976
		$do_implode = true;
5977
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
5978
			$do_implode = false;
5979
		}
5980
5981
		/**
5982
		 * Allow CSS to be concatenated into a single jetpack.css file.
5983
		 *
5984
		 * @since 3.2.0
5985
		 *
5986
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
5987
		 */
5988
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
5989
5990
		// Do not use the imploded file when default behaviour was altered through the filter
5991
		if ( ! $do_implode ) {
5992
			return;
5993
		}
5994
5995
		// We do not want to use the imploded file in dev mode, or if not connected
5996
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
5997
			if ( ! $travis_test ) {
5998
				return;
5999
			}
6000
		}
6001
6002
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6003
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6004
			return;
6005
		}
6006
6007
		/*
6008
		 * Now we assume Jetpack is connected and able to serve the single
6009
		 * file.
6010
		 *
6011
		 * In the future there will be a check here to serve the file locally
6012
		 * or potentially from the Jetpack CDN
6013
		 *
6014
		 * For now:
6015
		 * - Enqueue a single imploded css file
6016
		 * - Zero out the style_loader_tag for the bundled ones
6017
		 * - Be happy, drink scotch
6018
		 */
6019
6020
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6021
6022
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6023
6024
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6025
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6026
	}
6027
6028
	function concat_remove_style_loader_tag( $tag, $handle ) {
6029
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6030
			$tag = '';
6031
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6032
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6033
			}
6034
		}
6035
6036
		return $tag;
6037
	}
6038
6039
	/*
6040
	 * Check the heartbeat data
6041
	 *
6042
	 * Organizes the heartbeat data by severity.  For example, if the site
6043
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6044
	 *
6045
	 * Data will be added to "caution" array, if it either:
6046
	 *  - Out of date Jetpack version
6047
	 *  - Out of date WP version
6048
	 *  - Out of date PHP version
6049
	 *
6050
	 * $return array $filtered_data
6051
	 */
6052
	public static function jetpack_check_heartbeat_data() {
6053
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6054
6055
		$good    = array();
6056
		$caution = array();
6057
		$bad     = array();
6058
6059
		foreach ( $raw_data as $stat => $value ) {
6060
6061
			// Check jetpack version
6062
			if ( 'version' == $stat ) {
6063
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6064
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6065
					continue;
6066
				}
6067
			}
6068
6069
			// Check WP version
6070
			if ( 'wp-version' == $stat ) {
6071
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6072
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6073
					continue;
6074
				}
6075
			}
6076
6077
			// Check PHP version
6078
			if ( 'php-version' == $stat ) {
6079
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6080
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6081
					continue;
6082
				}
6083
			}
6084
6085
			// Check ID crisis
6086
			if ( 'identitycrisis' == $stat ) {
6087
				if ( 'yes' == $value ) {
6088
					$bad[ $stat ] = $value;
6089
					continue;
6090
				}
6091
			}
6092
6093
			// The rest are good :)
6094
			$good[ $stat ] = $value;
6095
		}
6096
6097
		$filtered_data = array(
6098
			'good'    => $good,
6099
			'caution' => $caution,
6100
			'bad'     => $bad
6101
		);
6102
6103
		return $filtered_data;
6104
	}
6105
6106
6107
	/*
6108
	 * This method is used to organize all options that can be reset
6109
	 * without disconnecting Jetpack.
6110
	 *
6111
	 * It is used in class.jetpack-cli.php to reset options
6112
	 *
6113
	 * @return array of options to delete.
6114
	 */
6115
	public static function get_jetpack_options_for_reset() {
6116
		$jetpack_options            = Jetpack_Options::get_option_names();
6117
		$jetpack_options_non_compat = Jetpack_Options::get_option_names( 'non_compact' );
6118
		$jetpack_options_private    = Jetpack_Options::get_option_names( 'private' );
6119
6120
		$all_jp_options = array_merge( $jetpack_options, $jetpack_options_non_compat, $jetpack_options_private );
6121
6122
		// A manual build of the wp options
6123
		$wp_options = array(
6124
			'sharing-options',
6125
			'disabled_likes',
6126
			'disabled_reblogs',
6127
			'jetpack_comments_likes_enabled',
6128
			'wp_mobile_excerpt',
6129
			'wp_mobile_featured_images',
6130
			'wp_mobile_app_promos',
6131
			'stats_options',
6132
			'stats_dashboard_widget',
6133
			'safecss_preview_rev',
6134
			'safecss_rev',
6135
			'safecss_revision_migrated',
6136
			'nova_menu_order',
6137
			'jetpack_portfolio',
6138
			'jetpack_portfolio_posts_per_page',
6139
			'jetpack_testimonial',
6140
			'jetpack_testimonial_posts_per_page',
6141
			'wp_mobile_custom_css',
6142
			'sharedaddy_disable_resources',
6143
			'sharing-options',
6144
			'sharing-services',
6145
			'site_icon_temp_data',
6146
			'featured-content',
6147
			'site_logo',
6148
			'jetpack_dismissed_notices',
6149
		);
6150
6151
		// Flag some Jetpack options as unsafe
6152
		$unsafe_options = array(
6153
			'id',                           // (int)    The Client ID/WP.com Blog ID of this site.
6154
			'master_user',                  // (int)    The local User ID of the user who connected this site to jetpack.wordpress.com.
6155
			'version',                      // (string) Used during upgrade procedure to auto-activate new modules. version:time
6156
			'jumpstart',                    // (string) A flag for whether or not to show the Jump Start.  Accepts: new_connection, jumpstart_activated, jetpack_action_taken, jumpstart_dismissed.
6157
6158
			// non_compact
6159
			'activated',
6160
6161
			// private
6162
			'register',
6163
			'blog_token',                  // (string) The Client Secret/Blog Token of this site.
6164
			'user_token',                  // (string) The User Token of this site. (deprecated)
6165
			'user_tokens'
6166
		);
6167
6168
		// Remove the unsafe Jetpack options
6169
		foreach ( $unsafe_options as $unsafe_option ) {
6170
			if ( false !== ( $key = array_search( $unsafe_option, $all_jp_options ) ) ) {
6171
				unset( $all_jp_options[ $key ] );
6172
			}
6173
		}
6174
6175
		$options = array(
6176
			'jp_options' => $all_jp_options,
6177
			'wp_options' => $wp_options
6178
		);
6179
6180
		return $options;
6181
	}
6182
6183
	/**
6184
	 * Check if an option of a Jetpack module has been updated.
6185
	 *
6186
	 * If any module option has been updated before Jump Start has been dismissed,
6187
	 * update the 'jumpstart' option so we can hide Jump Start.
6188
	 *
6189
	 * @param string $option_name
6190
	 *
6191
	 * @return bool
6192
	 */
6193
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6194
		// Bail if Jump Start has already been dismissed
6195
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6196
			return false;
6197
		}
6198
6199
		$jetpack = Jetpack::init();
6200
6201
		// Manual build of module options
6202
		$option_names = self::get_jetpack_options_for_reset();
6203
6204
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6205
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6206
6207
			//Jump start is being dismissed send data to MC Stats
6208
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6209
6210
			$jetpack->do_stats( 'server_side' );
6211
		}
6212
6213
	}
6214
6215
	/*
6216
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6217
	 * so we can bring them directly to their site in calypso.
6218
	 *
6219
	 * @param string | url
6220
	 * @return string | url without the guff
6221
	 */
6222
	public static function build_raw_urls( $url ) {
6223
		$strip_http = '/.*?:\/\//i';
6224
		$url = preg_replace( $strip_http, '', $url  );
6225
		$url = str_replace( '/', '::', $url );
6226
		return $url;
6227
	}
6228
6229
	/**
6230
	 * Stores and prints out domains to prefetch for page speed optimization.
6231
	 *
6232
	 * @param mixed $new_urls
6233
	 */
6234
	public static function dns_prefetch( $new_urls = null ) {
6235
		static $prefetch_urls = array();
6236
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6237
			echo "\r\n";
6238
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6239
				printf( "<link rel='dns-prefetch' href='%s'>\r\n", esc_attr( $this_prefetch_url ) );
6240
			}
6241
		} elseif ( ! empty( $new_urls ) ) {
6242
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6243
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6244
			}
6245
			foreach ( (array) $new_urls as $this_new_url ) {
6246
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6247
			}
6248
			$prefetch_urls = array_unique( $prefetch_urls );
6249
		}
6250
	}
6251
6252
	public function wp_dashboard_setup() {
6253
		if ( self::is_active() ) {
6254
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6255
			$widget_title = __( 'Site Stats', 'jetpack' );
6256
		} elseif ( ! self::is_development_mode() && current_user_can( 'jetpack_connect' ) ) {
6257
			add_action( 'jetpack_dashboard_widget', array( $this, 'dashboard_widget_connect_to_wpcom' ) );
6258
			$widget_title = __( 'Please Connect Jetpack', 'jetpack' );
6259
		}
6260
6261
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6262
			wp_add_dashboard_widget(
6263
				'jetpack_summary_widget',
6264
				$widget_title,
6265
				array( __CLASS__, 'dashboard_widget' )
6266
			);
6267
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6268
6269
			// If we're inactive and not in development mode, sort our box to the top.
6270
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6271
				global $wp_meta_boxes;
6272
6273
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6274
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6275
6276
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6277
			}
6278
		}
6279
	}
6280
6281
	/**
6282
	 * @param mixed $result Value for the user's option
6283
	 * @return mixed
6284
	 */
6285
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6286
		if ( ! is_array( $sorted ) ) {
6287
			return $sorted;
6288
		}
6289
6290
		foreach ( $sorted as $box_context => $ids ) {
6291
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6292
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6293
				continue;
6294
			}
6295
6296
			$ids_array = explode( ',', $ids );
6297
			$key = array_search( 'dashboard_stats', $ids_array );
6298
6299
			if ( false !== $key ) {
6300
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6301
				$ids_array[ $key ] = 'jetpack_summary_widget';
6302
				$sorted[ $box_context ] = implode( ',', $ids_array );
6303
				// We've found it, stop searching, and just return.
6304
				break;
6305
			}
6306
		}
6307
6308
		return $sorted;
6309
	}
6310
6311
	public static function dashboard_widget() {
6312
		/**
6313
		 * Fires when the dashboard is loaded.
6314
		 *
6315
		 * @since 3.4.0
6316
		 */
6317
		do_action( 'jetpack_dashboard_widget' );
6318
	}
6319
6320
	public static function dashboard_widget_footer() {
6321
		?>
6322
		<footer>
6323
6324
		<div class="protect">
6325
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6326
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6327
				<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>
6328
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6329
				<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' ); ?>">
6330
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6331
				</a>
6332
			<?php else : ?>
6333
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6334
			<?php endif; ?>
6335
		</div>
6336
6337
		<div class="akismet">
6338
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6339
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6340
				<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>
6341
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6342
				<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">
6343
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6344
				</a>
6345
			<?php else : ?>
6346
				<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>
6347
			<?php endif; ?>
6348
		</div>
6349
6350
		</footer>
6351
		<?php
6352
	}
6353
6354
	public function dashboard_widget_connect_to_wpcom() {
6355
		if ( Jetpack::is_active() || Jetpack::is_development_mode() || ! current_user_can( 'jetpack_connect' ) ) {
6356
			return;
6357
		}
6358
		?>
6359
		<div class="wpcom-connect">
6360
			<div class="jp-emblem">
6361
			<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">
6362
				<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"/>
6363
			</svg>
6364
			</div>
6365
			<h3><?php esc_html_e( 'Please Connect Jetpack', 'jetpack' ); ?></h3>
6366
			<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>
6367
6368
			<div class="actions">
6369
				<a href="<?php echo $this->build_connect_url( false, false, 'widget-btn' ); ?>" class="button button-primary">
6370
					<?php esc_html_e( 'Connect Jetpack', 'jetpack' ); ?>
6371
				</a>
6372
			</div>
6373
		</div>
6374
		<?php
6375
	}
6376
6377
	/**
6378
	 * Return string containing the Jetpack logo.
6379
	 *
6380
	 * @since 3.9.0
6381
	 *
6382
	 * @return string
6383
	 */
6384
	public static function get_jp_emblem() {
6385
		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>';
6386
	}
6387
6388
	/*
6389
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6390
	 */
6391
	function jetpack_icon_user_connected( $columns ) {
6392
		$columns['user_jetpack'] = '';
6393
		return $columns;
6394
	}
6395
6396
	/*
6397
	 * Show Jetpack icon if the user is linked.
6398
	 */
6399
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6400
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6401
			$emblem_html = sprintf(
6402
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6403
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6404
				Jetpack::get_jp_emblem()
6405
			);
6406
			return $emblem_html;
6407
		}
6408
6409
		return $val;
6410
	}
6411
6412
	/*
6413
	 * Style the Jetpack user column
6414
	 */
6415
	function jetpack_user_col_style() {
6416
		global $current_screen;
6417
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6418
			<style>
6419
				.fixed .column-user_jetpack {
6420
					width: 21px;
6421
				}
6422
				.jp-emblem-user-admin svg {
6423
					width: 20px;
6424
					height: 20px;
6425
				}
6426
				.jp-emblem-user-admin path {
6427
					fill: #8cc258;
6428
				}
6429
			</style>
6430
		<?php }
6431
	}
6432
}
6433