Completed
Push — master-stable ( b0661e...7c8a41 )
by
unknown
134:26 queued 126:49
created

class.jetpack.php (9 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
Options:
5
jetpack_options (array)
6
	An array of options.
7
	@see Jetpack_Options::get_option_names()
8
9
jetpack_register (string)
10
	Temporary verification secrets.
11
12
jetpack_activated (int)
13
	1: the plugin was activated normally
14
	2: the plugin was activated on this site because of a network-wide activation
15
	3: the plugin was auto-installed
16
	4: the plugin was manually disconnected (but is still installed)
17
18
jetpack_active_modules (array)
19
	Array of active module slugs.
20
21
jetpack_do_activate (bool)
22
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
23
*/
24
25
class Jetpack {
26
	public $xmlrpc_server = null;
27
28
	private $xmlrpc_verification = null;
29
30
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
31
32
	/**
33
	 * @var array The handles of styles that are concatenated into jetpack.css
34
	 */
35
	public $concatenated_style_handles = array(
36
		'jetpack-carousel',
37
		'grunion.css',
38
		'the-neverending-homepage',
39
		'jetpack_likes',
40
		'jetpack_related-posts',
41
		'sharedaddy',
42
		'jetpack-slideshow',
43
		'presentations',
44
		'jetpack-subscriptions',
45
		'jetpack-responsive-videos-style',
46
		'jetpack-social-menu',
47
		'tiled-gallery',
48
		'jetpack_display_posts_widget',
49
		'gravatar-profile-widget',
50
		'goodreads-widget',
51
		'jetpack_social_media_icons_widget',
52
		'jetpack-top-posts-widget',
53
		'jetpack_image_widget',
54
		'jetpack-my-community-widget',
55
	);
56
57
	public $plugins_to_deactivate = array(
58
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
59
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
60
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
61
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
62
		'after-the-deadline'  => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
63
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
64
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
65
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
66
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
67
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
68
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
69
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
70
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
71
		'omnisearch'          => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
72
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
73
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
74
	);
75
76
	static $capability_translations = array(
77
		'administrator' => 'manage_options',
78
		'editor'        => 'edit_others_posts',
79
		'author'        => 'publish_posts',
80
		'contributor'   => 'edit_posts',
81
		'subscriber'    => 'read',
82
	);
83
84
	/**
85
	 * Map of modules that have conflicts with plugins and should not be auto-activated
86
	 * if the plugins are active.  Used by filter_default_modules
87
	 *
88
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
89
	 * change `module-slug` and add this to your plugin:
90
	 *
91
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
92
	 * function my_jetpack_get_default_modules( $modules ) {
93
	 *     return array_diff( $modules, array( 'module-slug' ) );
94
	 * }
95
	 *
96
	 * @var array
97
	 */
98
	private $conflicting_plugins = array(
99
		'comments'          => array(
100
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
101
			'Disqus'                               => 'disqus-comment-system/disqus.php',
102
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
103
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
104
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
105
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
106
		),
107
		'contact-form'      => array(
108
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
109
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
110
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
111
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
112
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
113
		),
114
		'minileven'         => array(
115
			'WPtouch'                              => 'wptouch/wptouch.php',
116
		),
117
		'latex'             => array(
118
			'LaTeX for WordPress'                  => 'latex/latex.php',
119
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
120
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
121
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
122
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
123
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
124
		),
125
		'protect'           => array(
126
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
127
			'Captcha'                              => 'captcha/captcha.php',
128
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
129
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
130
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
131
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
132
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
133
			'Security-protection'                  => 'security-protection/security-protection.php',
134
			'Login Security'                       => 'login-security/login-security.php',
135
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
136
			'Wordfence Security'                   => 'wordfence/wordfence.php',
137
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
138
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
139
		),
140
		'random-redirect'   => array(
141
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
142
		),
143
		'related-posts'     => array(
144
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
145
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
146
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
147
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
148
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
149
			'outbrain'                             => 'outbrain/outbrain.php',
150
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
151
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
152
		),
153
		'sharedaddy'        => array(
154
			'AddThis'                              => 'addthis/addthis_social_widget.php',
155
			'Add To Any'                           => 'add-to-any/add-to-any.php',
156
			'ShareThis'                            => 'share-this/sharethis.php',
157
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
158
		),
159
		'seo-tools' => array(
160
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
161
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
162
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
163
		),
164
		'verification-tools' => array(
165
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
166
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
167
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
168
		),
169
		'widget-visibility' => array(
170
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
171
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
172
		),
173
		'sitemaps' => array(
174
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
175
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
176
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
177
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
178
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
179
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
180
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
181
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
182
			'Sitemap'                              => 'sitemap/sitemap.php',
183
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
184
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
185
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
186
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
187
		),
188
	);
189
190
	/**
191
	 * Plugins for which we turn off our Facebook OG Tags implementation.
192
	 *
193
	 * Note: WordPress SEO by Yoast and WordPress SEO Premium by Yoast automatically deactivate
194
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
195
	 *
196
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
197
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
198
	 */
199
	private $open_graph_conflicting_plugins = array(
200
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
201
		                                                         // 2 Click Social Media Buttons
202
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
203
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
204
		'autodescription/autodescription.php',                   // The SEO Framework
205
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
206
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
207
		                                                         // Open Graph Meta Tags by Heateor
208
		'facebook/facebook.php',                                 // Facebook (official plugin)
209
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
210
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
211
		                                                         // Facebook Featured Image & OG Meta Tags
212
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
213
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
214
		                                                         // Facebook Open Graph Meta Tags for WordPress
215
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
216
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
217
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
218
		                                                         // Fedmich's Facebook Open Graph Meta
219
		'header-footer/plugin.php',                              // Header and Footer
220
		'network-publisher/networkpub.php',                      // Network Publisher
221
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
222
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
223
		                                                         // NextScripts SNAP
224
		'og-tags/og-tags.php',                                   // OG Tags
225
		'opengraph/opengraph.php',                               // Open Graph
226
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
227
		                                                         // Open Graph Protocol Framework
228
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
229
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
230
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
231
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
232
		'sharepress/sharepress.php',                             // SharePress
233
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
234
		'social-discussions/social-discussions.php',             // Social Discussions
235
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
236
		'socialize/socialize.php',                               // Socialize
237
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
238
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
239
		                                                         // Tweet, Like, Google +1 and Share
240
		'wordbooker/wordbooker.php',                             // Wordbooker
241
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
242
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
243
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
244
		                                                         // WP Facebook Like Send & Open Graph Meta
245
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
246
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
247
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
248
		'wp-fb-share-like-button/wp_fb_share-like_widget.php'    // WP Facebook Like Button
249
	);
250
251
	/**
252
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
253
	 */
254
	private $twitter_cards_conflicting_plugins = array(
255
	//	'twitter/twitter.php',                       // The official one handles this on its own.
256
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
257
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
258
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
259
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
260
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
261
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
262
		'twitter-cards/twitter-cards.php',           // Twitter Cards
263
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
264
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
265
	);
266
267
	/**
268
	 * Message to display in admin_notice
269
	 * @var string
270
	 */
271
	public $message = '';
272
273
	/**
274
	 * Error to display in admin_notice
275
	 * @var string
276
	 */
277
	public $error = '';
278
279
	/**
280
	 * Modules that need more privacy description.
281
	 * @var string
282
	 */
283
	public $privacy_checks = '';
284
285
	/**
286
	 * Stats to record once the page loads
287
	 *
288
	 * @var array
289
	 */
290
	public $stats = array();
291
292
	/**
293
	 * Jetpack_Sync object
294
	 */
295
	public $sync;
296
297
	/**
298
	 * Verified data for JSON authorization request
299
	 */
300
	public $json_api_authorization_request = array();
301
302
	/**
303
	 * Holds the singleton instance of this class
304
	 * @since 2.3.3
305
	 * @var Jetpack
306
	 */
307
	static $instance = false;
308
309
	/**
310
	 * Singleton
311
	 * @static
312
	 */
313
	public static function init() {
314
		if ( ! self::$instance ) {
315
			self::$instance = new Jetpack;
316
317
			self::$instance->plugin_upgrade();
318
		}
319
320
		return self::$instance;
321
	}
322
323
	/**
324
	 * Must never be called statically
325
	 */
326
	function plugin_upgrade() {
327
		if ( Jetpack::is_active() ) {
328
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
329
			if ( JETPACK__VERSION != $version ) {
330
331
				// Check which active modules actually exist and remove others from active_modules list
332
				$unfiltered_modules = Jetpack::get_active_modules();
333
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
334
				if ( array_diff( $unfiltered_modules, $modules ) ) {
335
					Jetpack::update_active_modules( $modules );
336
				}
337
338
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
339
340
				// Upgrade to 4.3.0
341
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
342
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
343
				}
344
345
				Jetpack::maybe_set_version_option();
346
			}
347
		}
348
	}
349
350
	static function activate_manage( ) {
351
		if ( did_action( 'init' ) || current_filter() == 'init' ) {
352
			self::activate_module( 'manage', false, false );
353
		} else if ( !  has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
354
			add_action( 'init', array( __CLASS__, 'activate_manage' ) );
355
		}
356
	}
357
358
	static function update_active_modules( $modules ) {
359
		$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
360
361
		$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
362
363
		if ( is_array( $modules ) && is_array( $current_modules ) ) {
364
			$new_active_modules = array_diff( $modules, $current_modules );
365
			foreach( $new_active_modules as $module ) {
366
				/**
367
				 * Fires when a specific module is activated.
368
				 *
369
				 * @since 1.9.0
370
				 *
371
				 * @param string $module Module slug.
372
				 * @param boolean $success whether the module was activated. @since 4.2
373
				 */
374
				do_action( 'jetpack_activate_module', $module, $success );
375
376
				/**
377
				 * Fires when a module is activated.
378
				 * The dynamic part of the filter, $module, is the module slug.
379
				 *
380
				 * @since 1.9.0
381
				 *
382
				 * @param string $module Module slug.
383
				 */
384
				do_action( "jetpack_activate_module_$module", $module );
385
			}
386
387
			$new_deactive_modules = array_diff( $current_modules, $modules );
388
			foreach( $new_deactive_modules as $module ) {
389
				/**
390
				 * Fired after a module has been deactivated.
391
				 *
392
				 * @since 4.2.0
393
				 *
394
				 * @param string $module Module slug.
395
				 * @param boolean $success whether the module was deactivated.
396
				 */
397
				do_action( 'jetpack_deactivate_module', $module, $success );
398
				/**
399
				 * Fires when a module is deactivated.
400
				 * The dynamic part of the filter, $module, is the module slug.
401
				 *
402
				 * @since 1.9.0
403
				 *
404
				 * @param string $module Module slug.
405
				 */
406
				do_action( "jetpack_deactivate_module_$module", $module );
407
			}
408
		}
409
410
		return $success;
411
	}
412
413
	static function delete_active_modules() {
414
		self::update_active_modules( array() );
415
	}
416
417
	/**
418
	 * Constructor.  Initializes WordPress hooks
419
	 */
420
	private function __construct() {
421
		/*
422
		 * Check for and alert any deprecated hooks
423
		 */
424
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
425
426
427
		/*
428
		 * Load things that should only be in Network Admin.
429
		 *
430
		 * For now blow away everything else until a more full
431
		 * understanding of what is needed at the network level is
432
		 * available
433
		 */
434
		if( is_multisite() ) {
435
			Jetpack_Network::init();
436
		}
437
438
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
439
440
		// Unlink user before deleting the user from .com
441
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
442
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
443
444
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
445
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
446
447
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
448
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
449
450
			$this->require_jetpack_authentication();
451
452
			if ( Jetpack::is_active() ) {
453
				// Hack to preserve $HTTP_RAW_POST_DATA
454
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
455
456
				$signed = $this->verify_xml_rpc_signature();
457
				if ( $signed && ! is_wp_error( $signed ) ) {
458
					// The actual API methods.
459
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
460
				} else {
461
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
462
					// active Jetpack connection, so that additional users can link their account.
463
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
464
				}
465
			} else {
466
				// The bootstrap API methods.
467
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
468
			}
469
470
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
471
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
472
		} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
473
			$this->require_jetpack_authentication();
474
			$this->add_remote_request_handlers();
475
		} else {
476
			if ( Jetpack::is_active() ) {
477
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
478
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
479
			}
480
		}
481
482
		if ( Jetpack::is_active() ) {
483
			Jetpack_Heartbeat::init();
484
		}
485
486
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
487
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
488
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
489
		}
490
491
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
492
493
		add_action( 'admin_init', array( $this, 'admin_init' ) );
494
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
495
496
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
497
498
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
499
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
500
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
501
502
		// returns HTTPS support status
503
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
504
505
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
506
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
507
508
		// JITM AJAX callback function
509
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
510
511
		// Universal ajax callback for all tracking events triggered via js
512
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
513
514
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
515
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
516
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
517
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
518
519
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
520
521
		/**
522
		 * These actions run checks to load additional files.
523
		 * They check for external files or plugins, so they need to run as late as possible.
524
		 */
525
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
526
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
527
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
528
529
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
530
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
531
532
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
533
534
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
535
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
536
537
		// A filter to control all just in time messages
538
		add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
539
540
		/**
541
		 * This is the hack to concatinate all css files into one.
542
		 * For description and reasoning see the implode_frontend_css method
543
		 *
544
		 * Super late priority so we catch all the registered styles
545
		 */
546
		if( !is_admin() ) {
547
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
548
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
549
		}
550
	}
551
552
	function jetpack_admin_ajax_tracks_callback() {
553
		// Check for nonce
554
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
555
			wp_die( 'Permissions check failed.' );
556
		}
557
558
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
559
			wp_die( 'No valid event name or type.' );
560
		}
561
562
		$tracks_data = array();
563
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
564
			$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
565
		}
566
567
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
568
		wp_send_json_success();
569
		wp_die();
570
	}
571
572
	/**
573
	 * The callback for the JITM ajax requests.
574
	 */
575
	function jetpack_jitm_ajax_callback() {
576
		// Check for nonce
577
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
578
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
579
		}
580
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
581
			$module_slug = $_REQUEST['jitmModule'];
582
			Jetpack::log( 'activate', $module_slug );
583
			Jetpack::activate_module( $module_slug, false, false );
584
			Jetpack::state( 'message', 'no_message' );
585
586
			//A Jetpack module is being activated through a JITM, track it
587
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
588
			$this->do_stats( 'server_side' );
589
590
			wp_send_json_success();
591
		}
592
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
593
			// get the hide_jitm options array
594
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
595
			$module_slug = $_REQUEST['jitmModule'];
596
597
			if( ! $jetpack_hide_jitm ) {
598
				$jetpack_hide_jitm = array(
599
					$module_slug => 'hide'
600
				);
601
			} else {
602
				$jetpack_hide_jitm[$module_slug] = 'hide';
603
			}
604
605
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
606
607
			//jitm is being dismissed forever, track it
608
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
609
			$this->do_stats( 'server_side' );
610
611
			wp_send_json_success();
612
		}
613 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
614
			$module_slug = $_REQUEST['jitmModule'];
615
616
			// User went to WordPress.com, track this
617
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
618
			$this->do_stats( 'server_side' );
619
620
			wp_send_json_success();
621
		}
622 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
623
			$track = $_REQUEST['jitmModule'];
624
625
			// User is viewing JITM, track it.
626
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
627
			$this->do_stats( 'server_side' );
628
629
			wp_send_json_success();
630
		}
631
	}
632
633
	/**
634
	 * If there are any stats that need to be pushed, but haven't been, push them now.
635
	 */
636
	function __destruct() {
637
		if ( ! empty( $this->stats ) ) {
638
			$this->do_stats( 'server_side' );
639
		}
640
	}
641
642
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
643
		switch( $cap ) {
644
			case 'jetpack_connect' :
645
			case 'jetpack_reconnect' :
646
				if ( Jetpack::is_development_mode() ) {
647
					$caps = array( 'do_not_allow' );
648
					break;
649
				}
650
				/**
651
				 * Pass through. If it's not development mode, these should match disconnect.
652
				 * Let users disconnect if it's development mode, just in case things glitch.
653
				 */
654
			case 'jetpack_disconnect' :
655
				/**
656
				 * In multisite, can individual site admins manage their own connection?
657
				 *
658
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
659
				 */
660
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
661
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
662
						/**
663
						 * We need to update the option name -- it's terribly unclear which
664
						 * direction the override goes.
665
						 *
666
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
667
						 */
668
						$caps = array( 'do_not_allow' );
669
						break;
670
					}
671
				}
672
673
				$caps = array( 'manage_options' );
674
				break;
675
			case 'jetpack_manage_modules' :
676
			case 'jetpack_activate_modules' :
677
			case 'jetpack_deactivate_modules' :
678
				$caps = array( 'manage_options' );
679
				break;
680
			case 'jetpack_configure_modules' :
681
				$caps = array( 'manage_options' );
682
				break;
683
			case 'jetpack_network_admin_page':
684
			case 'jetpack_network_settings_page':
685
				$caps = array( 'manage_network_plugins' );
686
				break;
687
			case 'jetpack_network_sites_page':
688
				$caps = array( 'manage_sites' );
689
				break;
690
			case 'jetpack_admin_page' :
691
				if ( Jetpack::is_development_mode() ) {
692
					$caps = array( 'manage_options' );
693
					break;
694
				} else {
695
					$caps = array( 'read' );
696
				}
697
				break;
698
			case 'jetpack_connect_user' :
699
				if ( Jetpack::is_development_mode() ) {
700
					$caps = array( 'do_not_allow' );
701
					break;
702
				}
703
				$caps = array( 'read' );
704
				break;
705
		}
706
		return $caps;
707
	}
708
709
	function require_jetpack_authentication() {
710
		// Don't let anyone authenticate
711
		$_COOKIE = array();
712
		remove_all_filters( 'authenticate' );
713
		remove_all_actions( 'wp_login_failed' );
714
715
		if ( Jetpack::is_active() ) {
716
			// Allow Jetpack authentication
717
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
718
		}
719
	}
720
721
	/**
722
	 * Load language files
723
	 * @action plugins_loaded
724
	 */
725
	public static function plugin_textdomain() {
726
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
727
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
728
	}
729
730
	/**
731
	 * Register assets for use in various modules and the Jetpack admin page.
732
	 *
733
	 * @uses wp_script_is, wp_register_script, plugins_url
734
	 * @action wp_loaded
735
	 * @return null
736
	 */
737
	public function register_assets() {
738 View Code Duplication
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
739
			wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
740
		}
741
742 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
743
			wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
744
		}
745
746 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
747
			wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
748
		}
749
750 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
751
			wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
752
		}
753
754
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
755
			wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
756
757
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
758
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
759
			if ( ! is_numeric( $fb_app_id ) ) {
760
				$fb_app_id = '';
761
			}
762
			wp_localize_script(
763
				'jetpack-facebook-embed',
764
				'jpfbembed',
765
				array(
766
					'appid' => $fb_app_id,
767
					'locale' => $this->get_locale(),
768
				)
769
			);
770
		}
771
772
		/**
773
		 * As jetpack_register_genericons is by default fired off a hook,
774
		 * the hook may have already fired by this point.
775
		 * So, let's just trigger it manually.
776
		 */
777
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
778
		jetpack_register_genericons();
779
780
		/**
781
		 * Register the social logos
782
		 */
783
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
784
		jetpack_register_social_logos();
785
786 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
787
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
788
	}
789
790
	/**
791
	 * Guess locale from language code.
792
	 *
793
	 * @param string $lang Language code.
794
	 * @return string|bool
795
	 */
796
	function guess_locale_from_lang( $lang ) {
797
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
798
			return 'en_US';
799
		}
800
801
		if ( ! class_exists( 'GP_Locales' ) ) {
802
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
803
				return false;
804
			}
805
806
			require JETPACK__GLOTPRESS_LOCALES_PATH;
807
		}
808
809
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
810
			// WP.com: get_locale() returns 'it'
811
			$locale = GP_Locales::by_slug( $lang );
812
		} else {
813
			// Jetpack: get_locale() returns 'it_IT';
814
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
815
		}
816
817
		if ( ! $locale ) {
818
			return false;
819
		}
820
821
		if ( empty( $locale->facebook_locale ) ) {
822
			if ( empty( $locale->wp_locale ) ) {
823
				return false;
824
			} else {
825
				// Facebook SDK is smart enough to fall back to en_US if a
826
				// locale isn't supported. Since supported Facebook locales
827
				// can fall out of sync, we'll attempt to use the known
828
				// wp_locale value and rely on said fallback.
829
				return $locale->wp_locale;
830
			}
831
		}
832
833
		return $locale->facebook_locale;
834
	}
835
836
	/**
837
	 * Get the locale.
838
	 *
839
	 * @return string|bool
840
	 */
841
	function get_locale() {
842
		$locale = $this->guess_locale_from_lang( get_locale() );
843
844
		if ( ! $locale ) {
845
			$locale = 'en_US';
846
		}
847
848
		return $locale;
849
	}
850
851
	/**
852
	 * Device Pixels support
853
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
854
	 */
855
	function devicepx() {
856
		if ( Jetpack::is_active() ) {
857
			wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
858
		}
859
	}
860
861
	/**
862
	 * Return the network_site_url so that .com knows what network this site is a part of.
863
	 * @param  bool $option
864
	 * @return string
865
	 */
866
	public function jetpack_main_network_site_option( $option ) {
867
		return network_site_url();
868
	}
869
	/**
870
	 * Network Name.
871
	 */
872
	static function network_name( $option = null ) {
873
		global $current_site;
874
		return $current_site->site_name;
875
	}
876
	/**
877
	 * Does the network allow new user and site registrations.
878
	 * @return string
879
	 */
880
	static function network_allow_new_registrations( $option = null ) {
881
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
882
	}
883
	/**
884
	 * Does the network allow admins to add new users.
885
	 * @return boolian
886
	 */
887
	static function network_add_new_users( $option = null ) {
888
		return (bool) get_site_option( 'add_new_users' );
889
	}
890
	/**
891
	 * File upload psace left per site in MB.
892
	 *  -1 means NO LIMIT.
893
	 * @return number
894
	 */
895
	static function network_site_upload_space( $option = null ) {
896
		// value in MB
897
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
898
	}
899
900
	/**
901
	 * Network allowed file types.
902
	 * @return string
903
	 */
904
	static function network_upload_file_types( $option = null ) {
905
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
906
	}
907
908
	/**
909
	 * Maximum file upload size set by the network.
910
	 * @return number
911
	 */
912
	static function network_max_upload_file_size( $option = null ) {
913
		// value in KB
914
		return get_site_option( 'fileupload_maxk', 300 );
915
	}
916
917
	/**
918
	 * Lets us know if a site allows admins to manage the network.
919
	 * @return array
920
	 */
921
	static function network_enable_administration_menus( $option = null ) {
922
		return get_site_option( 'menu_items' );
923
	}
924
925
	/**
926
	 * If a user has been promoted to or demoted from admin, we need to clear the
927
	 * jetpack_other_linked_admins transient.
928
	 *
929
	 * @since 4.3.2
930
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
931
	 *
932
	 * @param int    $user_id   The user ID whose role changed.
933
	 * @param string $role      The new role.
934
	 * @param array  $old_roles An array of the user's previous roles.
935
	 */
936
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
937
		if ( 'administrator' == $role
938
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
939
			|| is_null( $old_roles )
940
		) {
941
			delete_transient( 'jetpack_other_linked_admins' );
942
		}
943
	}
944
945
	/**
946
	 * Checks to see if there are any other users available to become primary
947
	 * Users must both:
948
	 * - Be linked to wpcom
949
	 * - Be an admin
950
	 *
951
	 * @return mixed False if no other users are linked, Int if there are.
952
	 */
953
	static function get_other_linked_admins() {
954
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
955
956
		if ( false === $other_linked_users ) {
957
			$admins = get_users( array( 'role' => 'administrator' ) );
958
			if ( count( $admins ) > 1 ) {
959
				$available = array();
960
				foreach ( $admins as $admin ) {
961
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
962
						$available[] = $admin->ID;
963
					}
964
				}
965
966
				$count_connected_admins = count( $available );
967
				if ( count( $available ) > 1 ) {
968
					$other_linked_users = $count_connected_admins;
969
				} else {
970
					$other_linked_users = 0;
971
				}
972
			} else {
973
				$other_linked_users = 0;
974
			}
975
976
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
977
		}
978
979
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
980
	}
981
982
	/**
983
	 * Return whether we are dealing with a multi network setup or not.
984
	 * The reason we are type casting this is because we want to avoid the situation where
985
	 * the result is false since when is_main_network_option return false it cases
986
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
987
	 * database which could be set to anything as opposed to what this function returns.
988
	 * @param  bool  $option
989
	 *
990
	 * @return boolean
991
	 */
992
	public function is_main_network_option( $option ) {
993
		// return '1' or ''
994
		return (string) (bool) Jetpack::is_multi_network();
995
	}
996
997
	/**
998
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
999
	 *
1000
	 * @param  string  $option
1001
	 * @return boolean
1002
	 */
1003
	public function is_multisite( $option ) {
1004
		return (string) (bool) is_multisite();
1005
	}
1006
1007
	/**
1008
	 * Implemented since there is no core is multi network function
1009
	 * Right now there is no way to tell if we which network is the dominant network on the system
1010
	 *
1011
	 * @since  3.3
1012
	 * @return boolean
1013
	 */
1014
	public static function is_multi_network() {
1015
		global  $wpdb;
1016
1017
		// if we don't have a multi site setup no need to do any more
1018
		if ( ! is_multisite() ) {
1019
			return false;
1020
		}
1021
1022
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1023
		if ( $num_sites > 1 ) {
1024
			return true;
1025
		} else {
1026
			return false;
1027
		}
1028
	}
1029
1030
	/**
1031
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1032
	 * @return null
1033
	 */
1034
	function update_jetpack_main_network_site_option() {
1035
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1036
	}
1037
	/**
1038
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1039
	 *
1040
	 */
1041
	function update_jetpack_network_settings() {
1042
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1043
		// Only sync this info for the main network site.
1044
	}
1045
1046
	/**
1047
	 * Get back if the current site is single user site.
1048
	 *
1049
	 * @return bool
1050
	 */
1051
	public static function is_single_user_site() {
1052
		global $wpdb;
1053
		$some_users = $wpdb->get_var( "select count(*) from (select user_id from $wpdb->usermeta where meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) as someusers" );
1054
		return 1 === (int) $some_users;
1055
	}
1056
1057
	/**
1058
	 * Returns true if the site has file write access false otherwise.
1059
	 * @return string ( '1' | '0' )
1060
	 **/
1061
	public static function file_system_write_access() {
1062
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1063
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1064
		}
1065
1066
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1067
1068
		$filesystem_method = get_filesystem_method();
1069
		if ( $filesystem_method === 'direct' ) {
1070
			return 1;
1071
		}
1072
1073
		ob_start();
1074
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1075
		ob_end_clean();
1076
		if ( $filesystem_credentials_are_stored ) {
1077
			return 1;
1078
		}
1079
		return 0;
1080
	}
1081
1082
	/**
1083
	 * Finds out if a site is using a version control system.
1084
	 * @return string ( '1' | '0' )
1085
	 **/
1086
	public static function is_version_controlled() {
1087
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1088
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1089
	}
1090
1091
	/**
1092
	 * Determines whether the current theme supports featured images or not.
1093
	 * @return string ( '1' | '0' )
1094
	 */
1095
	public static function featured_images_enabled() {
1096
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1097
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1098
	}
1099
1100
	/**
1101
	 * jetpack_updates is saved in the following schema:
1102
	 *
1103
	 * array (
1104
	 *      'plugins'                       => (int) Number of plugin updates available.
1105
	 *      'themes'                        => (int) Number of theme updates available.
1106
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1107
	 *      'translations'                  => (int) Number of translation updates available.
1108
	 *      'total'                         => (int) Total of all available updates.
1109
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1110
	 * )
1111
	 * @return array
1112
	 */
1113
	public static function get_updates() {
1114
		$update_data = wp_get_update_data();
1115
1116
		// Stores the individual update counts as well as the total count.
1117
		if ( isset( $update_data['counts'] ) ) {
1118
			$updates = $update_data['counts'];
1119
		}
1120
1121
		// If we need to update WordPress core, let's find the latest version number.
1122 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1123
			$cur = get_preferred_from_update_core();
1124
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1125
				$updates['wp_update_version'] = $cur->current;
1126
			}
1127
		}
1128
		return isset( $updates ) ? $updates : array();
1129
	}
1130
1131
	public static function get_update_details() {
1132
		$update_details = array(
1133
			'update_core' => get_site_transient( 'update_core' ),
1134
			'update_plugins' => get_site_transient( 'update_plugins' ),
1135
			'update_themes' => get_site_transient( 'update_themes' ),
1136
		);
1137
		return $update_details;
1138
	}
1139
1140
	public static function refresh_update_data() {
1141
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1142
1143
	}
1144
1145
	public static function refresh_theme_data() {
1146
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1147
	}
1148
1149
	/**
1150
	 * Is Jetpack active?
1151
	 */
1152
	public static function is_active() {
1153
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1154
	}
1155
1156
	/**
1157
	 * Is Jetpack in development (offline) mode?
1158
	 */
1159
	public static function is_development_mode() {
1160
		$development_mode = false;
1161
1162
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1163
			$development_mode = JETPACK_DEV_DEBUG;
1164
		}
1165
1166
		elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1167
			$development_mode = true;
1168
		}
1169
		/**
1170
		 * Filters Jetpack's development mode.
1171
		 *
1172
		 * @see https://jetpack.com/support/development-mode/
1173
		 *
1174
		 * @since 2.2.1
1175
		 *
1176
		 * @param bool $development_mode Is Jetpack's development mode active.
1177
		 */
1178
		return apply_filters( 'jetpack_development_mode', $development_mode );
1179
	}
1180
1181
	/**
1182
	* Get Jetpack development mode notice text and notice class.
1183
	*
1184
	* Mirrors the checks made in Jetpack::is_development_mode
1185
	*
1186
	*/
1187
	public static function show_development_mode_notice() {
1188
		if ( Jetpack::is_development_mode() ) {
1189
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1190
				$notice = sprintf(
1191
					/* translators: %s is a URL */
1192
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1193
					'https://jetpack.com/support/development-mode/'
1194
				);
1195
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1196
				$notice = sprintf(
1197
					/* translators: %s is a URL */
1198
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1199
					'https://jetpack.com/support/development-mode/'
1200
				);
1201
			} else {
1202
				$notice = sprintf(
1203
					/* translators: %s is a URL */
1204
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1205
					'https://jetpack.com/support/development-mode/'
1206
				);
1207
			}
1208
1209
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1210
		}
1211
1212
		// Throw up a notice if using a development version and as for feedback.
1213
		if ( Jetpack::is_development_version() ) {
1214
			/* translators: %s is a URL */
1215
			$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/' );
1216
1217
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1218
		}
1219
		// Throw up a notice if using staging mode
1220
		if ( Jetpack::is_staging_site() ) {
1221
			/* translators: %s is a URL */
1222
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1223
1224
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1225
		}
1226
	}
1227
1228
	/**
1229
	 * Whether Jetpack's version maps to a public release, or a development version.
1230
	 */
1231
	public static function is_development_version() {
1232
		/**
1233
		 * Allows filtering whether this is a development version of Jetpack.
1234
		 *
1235
		 * This filter is especially useful for tests.
1236
		 *
1237
		 * @since 4.3.0
1238
		 *
1239
		 * @param bool $development_version Is this a develoment version of Jetpack?
1240
		 */
1241
		return (bool) apply_filters(
1242
			'jetpack_development_version',
1243
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1244
		);
1245
	}
1246
1247
	/**
1248
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1249
	 */
1250
	public static function is_user_connected( $user_id = false ) {
1251
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1252
		if ( ! $user_id ) {
1253
			return false;
1254
		}
1255
1256
		return (bool) Jetpack_Data::get_access_token( $user_id );
1257
	}
1258
1259
	/**
1260
	 * Get the wpcom user data of the current|specified connected user.
1261
	 */
1262
	public static function get_connected_user_data( $user_id = null ) {
1263
		if ( ! $user_id ) {
1264
			$user_id = get_current_user_id();
1265
		}
1266
1267
		$transient_key = "jetpack_connected_user_data_$user_id";
1268
1269
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1270
			return $cached_user_data;
1271
		}
1272
1273
		Jetpack::load_xml_rpc_client();
1274
		$xml = new Jetpack_IXR_Client( array(
1275
			'user_id' => $user_id,
1276
		) );
1277
		$xml->query( 'wpcom.getUser' );
1278
		if ( ! $xml->isError() ) {
1279
			$user_data = $xml->getResponse();
1280
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1281
			return $user_data;
1282
		}
1283
1284
		return false;
1285
	}
1286
1287
	/**
1288
	 * Get the wpcom email of the current|specified connected user.
1289
	 */
1290 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1291
		if ( ! $user_id ) {
1292
			$user_id = get_current_user_id();
1293
		}
1294
		Jetpack::load_xml_rpc_client();
1295
		$xml = new Jetpack_IXR_Client( array(
1296
			'user_id' => $user_id,
1297
		) );
1298
		$xml->query( 'wpcom.getUserEmail' );
1299
		if ( ! $xml->isError() ) {
1300
			return $xml->getResponse();
1301
		}
1302
		return false;
1303
	}
1304
1305
	/**
1306
	 * Get the wpcom email of the master user.
1307
	 */
1308
	public static function get_master_user_email() {
1309
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1310
		if ( $master_user_id ) {
1311
			return self::get_connected_user_email( $master_user_id );
1312
		}
1313
		return '';
1314
	}
1315
1316
	function current_user_is_connection_owner() {
1317
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1318
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1319
	}
1320
1321
	/**
1322
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1323
	 */
1324
	function extra_oembed_providers() {
1325
		// Cloudup: https://dev.cloudup.com/#oembed
1326
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1327
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1328
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1329
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1330
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1331
	}
1332
1333
	/**
1334
	 * Synchronize connected user role changes
1335
	 */
1336
	function user_role_change( $user_id ) {
1337
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1338
		Jetpack_Sync_Users::user_role_change( $user_id );
1339
	}
1340
1341
	/**
1342
	 * Loads the currently active modules.
1343
	 */
1344
	public static function load_modules() {
1345
		if ( ! self::is_active() && !self::is_development_mode() ) {
1346
			if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
1347
				return;
1348
			}
1349
		}
1350
1351
		$version = Jetpack_Options::get_option( 'version' );
1352 View Code Duplication
		if ( ! $version ) {
1353
			$version = $old_version = JETPACK__VERSION . ':' . time();
1354
			/** This action is documented in class.jetpack.php */
1355
			do_action( 'updating_jetpack_version', $version, false );
1356
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1357
		}
1358
		list( $version ) = explode( ':', $version );
1359
1360
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1361
1362
		$modules_data = array();
1363
1364
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1365
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1366
			$updated_modules = array();
1367
			foreach ( $modules as $module ) {
1368
				$modules_data[ $module ] = Jetpack::get_module( $module );
1369
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1370
					continue;
1371
				}
1372
1373
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1374
					continue;
1375
				}
1376
1377
				$updated_modules[] = $module;
1378
			}
1379
1380
			$modules = array_diff( $modules, $updated_modules );
1381
		}
1382
1383
		$is_development_mode = Jetpack::is_development_mode();
1384
1385
		foreach ( $modules as $index => $module ) {
1386
			// If we're in dev mode, disable modules requiring a connection
1387
			if ( $is_development_mode ) {
1388
				// Prime the pump if we need to
1389
				if ( empty( $modules_data[ $module ] ) ) {
1390
					$modules_data[ $module ] = Jetpack::get_module( $module );
1391
				}
1392
				// If the module requires a connection, but we're in local mode, don't include it.
1393
				if ( $modules_data[ $module ]['requires_connection'] ) {
1394
					continue;
1395
				}
1396
			}
1397
1398
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1399
				continue;
1400
			}
1401
1402
			if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
1403
				unset( $modules[ $index ] );
1404
				self::update_active_modules( array_values( $modules ) );
1405
				continue;
1406
			}
1407
1408
			/**
1409
			 * Fires when a specific module is loaded.
1410
			 * The dynamic part of the hook, $module, is the module slug.
1411
			 *
1412
			 * @since 1.1.0
1413
			 */
1414
			do_action( 'jetpack_module_loaded_' . $module );
1415
		}
1416
1417
		/**
1418
		 * Fires when all the modules are loaded.
1419
		 *
1420
		 * @since 1.1.0
1421
		 */
1422
		do_action( 'jetpack_modules_loaded' );
1423
1424
		// 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.
1425
		if ( Jetpack::is_active() || Jetpack::is_development_mode() )
1426
			require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1427
	}
1428
1429
	/**
1430
	 * Check if Jetpack's REST API compat file should be included
1431
	 * @action plugins_loaded
1432
	 * @return null
1433
	 */
1434
	public function check_rest_api_compat() {
1435
		/**
1436
		 * Filters the list of REST API compat files to be included.
1437
		 *
1438
		 * @since 2.2.5
1439
		 *
1440
		 * @param array $args Array of REST API compat files to include.
1441
		 */
1442
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1443
1444
		if ( function_exists( 'bbpress' ) )
1445
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1446
1447
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1448
			require_once $_jetpack_rest_api_compat_include;
1449
	}
1450
1451
	/**
1452
	 * Gets all plugins currently active in values, regardless of whether they're
1453
	 * traditionally activated or network activated.
1454
	 *
1455
	 * @todo Store the result in core's object cache maybe?
1456
	 */
1457
	public static function get_active_plugins() {
1458
		$active_plugins = (array) get_option( 'active_plugins', array() );
1459
1460
		if ( is_multisite() ) {
1461
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1462
			// whereas active_plugins stores them in the values.
1463
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1464
			if ( $network_plugins ) {
1465
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1466
			}
1467
		}
1468
1469
		sort( $active_plugins );
1470
1471
		return array_unique( $active_plugins );
1472
	}
1473
1474
	/**
1475
	 * Gets and parses additional plugin data to send with the heartbeat data
1476
	 *
1477
	 * @since 3.8.1
1478
	 *
1479
	 * @return array Array of plugin data
1480
	 */
1481
	public static function get_parsed_plugin_data() {
1482
		if ( ! function_exists( 'get_plugins' ) ) {
1483
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1484
		}
1485
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1486
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1487
		$active_plugins = Jetpack::get_active_plugins();
1488
1489
		$plugins = array();
1490
		foreach ( $all_plugins as $path => $plugin_data ) {
1491
			$plugins[ $path ] = array(
1492
					'is_active' => in_array( $path, $active_plugins ),
1493
					'file'      => $path,
1494
					'name'      => $plugin_data['Name'],
1495
					'version'   => $plugin_data['Version'],
1496
					'author'    => $plugin_data['Author'],
1497
			);
1498
		}
1499
1500
		return $plugins;
1501
	}
1502
1503
	/**
1504
	 * Gets and parses theme data to send with the heartbeat data
1505
	 *
1506
	 * @since 3.8.1
1507
	 *
1508
	 * @return array Array of theme data
1509
	 */
1510
	public static function get_parsed_theme_data() {
1511
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1512
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1513
1514
		$themes = array();
1515
		foreach ( $all_themes as $slug => $theme_data ) {
1516
			$theme_headers = array();
1517
			foreach ( $header_keys as $header_key ) {
1518
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1519
			}
1520
1521
			$themes[ $slug ] = array(
1522
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1523
					'slug' => $slug,
1524
					'theme_root' => $theme_data->get_theme_root_uri(),
1525
					'parent' => $theme_data->parent(),
1526
					'headers' => $theme_headers
1527
			);
1528
		}
1529
1530
		return $themes;
1531
	}
1532
1533
	/**
1534
	 * Checks whether a specific plugin is active.
1535
	 *
1536
	 * We don't want to store these in a static variable, in case
1537
	 * there are switch_to_blog() calls involved.
1538
	 */
1539
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1540
		return in_array( $plugin, self::get_active_plugins() );
1541
	}
1542
1543
	/**
1544
	 * Check if Jetpack's Open Graph tags should be used.
1545
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1546
	 *
1547
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1548
	 * @action plugins_loaded
1549
	 * @return null
1550
	 */
1551
	public function check_open_graph() {
1552
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1553
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1554
		}
1555
1556
		$active_plugins = self::get_active_plugins();
1557
1558
		if ( ! empty( $active_plugins ) ) {
1559
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1560
				if ( in_array( $plugin, $active_plugins ) ) {
1561
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1562
					break;
1563
				}
1564
			}
1565
		}
1566
1567
		/**
1568
		 * Allow the addition of Open Graph Meta Tags to all pages.
1569
		 *
1570
		 * @since 2.0.3
1571
		 *
1572
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1573
		 */
1574
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1575
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1576
		}
1577
	}
1578
1579
	/**
1580
	 * Check if Jetpack's Twitter tags should be used.
1581
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1582
	 *
1583
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1584
	 * @action plugins_loaded
1585
	 * @return null
1586
	 */
1587
	public function check_twitter_tags() {
1588
1589
		$active_plugins = self::get_active_plugins();
1590
1591
		if ( ! empty( $active_plugins ) ) {
1592
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1593
				if ( in_array( $plugin, $active_plugins ) ) {
1594
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1595
					break;
1596
				}
1597
			}
1598
		}
1599
1600
		/**
1601
		 * Allow Twitter Card Meta tags to be disabled.
1602
		 *
1603
		 * @since 2.6.0
1604
		 *
1605
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1606
		 */
1607
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1608
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1609
		}
1610
	}
1611
1612
	/**
1613
	 * Allows plugins to submit security reports.
1614
 	 *
1615
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1616
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1617
	 * @param array   $args         See definitions above
1618
	 */
1619
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1620
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1621
	}
1622
1623
/* Jetpack Options API */
1624
1625
	public static function get_option_names( $type = 'compact' ) {
1626
		return Jetpack_Options::get_option_names( $type );
1627
	}
1628
1629
	/**
1630
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1631
 	 *
1632
	 * @param string $name    Option name
1633
	 * @param mixed  $default (optional)
1634
	 */
1635
	public static function get_option( $name, $default = false ) {
1636
		return Jetpack_Options::get_option( $name, $default );
1637
	}
1638
1639
	/**
1640
	* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
1641
	* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
1642
	* $name must be a registered option name.
1643
	*/
1644
	public static function create_nonce( $name ) {
1645
		$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
1646
1647
		Jetpack_Options::update_option( $name, $secret );
1648
		@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
1649
		if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
1650
			return new Jetpack_Error( 'missing_secrets' );
1651
1652
		return array(
1653
			'secret_1' => $secret_1,
1654
			'secret_2' => $secret_2,
1655
			'eol'      => $eol,
1656
		);
1657
	}
1658
1659
	/**
1660
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1661
 	 *
1662
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1663
	 * @param string $name  Option name
1664
	 * @param mixed  $value Option value
1665
	 */
1666
	public static function update_option( $name, $value ) {
1667
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1668
		return Jetpack_Options::update_option( $name, $value );
1669
	}
1670
1671
	/**
1672
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1673
 	 *
1674
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1675
	 * @param array $array array( option name => option value, ... )
1676
	 */
1677
	public static function update_options( $array ) {
1678
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
1679
		return Jetpack_Options::update_options( $array );
1680
	}
1681
1682
	/**
1683
	 * Deletes the given option.  May be passed multiple option names as an array.
1684
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
1685
	 *
1686
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
1687
	 * @param string|array $names
1688
	 */
1689
	public static function delete_option( $names ) {
1690
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
1691
		return Jetpack_Options::delete_option( $names );
1692
	}
1693
1694
	/**
1695
	 * Enters a user token into the user_tokens option
1696
	 *
1697
	 * @param int $user_id
1698
	 * @param string $token
1699
	 * return bool
1700
	 */
1701
	public static function update_user_token( $user_id, $token, $is_master_user ) {
1702
		// not designed for concurrent updates
1703
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
1704
		if ( ! is_array( $user_tokens ) )
1705
			$user_tokens = array();
1706
		$user_tokens[$user_id] = $token;
1707
		if ( $is_master_user ) {
1708
			$master_user = $user_id;
1709
			$options     = compact( 'user_tokens', 'master_user' );
1710
		} else {
1711
			$options = compact( 'user_tokens' );
1712
		}
1713
		return Jetpack_Options::update_options( $options );
1714
	}
1715
1716
	/**
1717
	 * Returns an array of all PHP files in the specified absolute path.
1718
	 * Equivalent to glob( "$absolute_path/*.php" ).
1719
	 *
1720
	 * @param string $absolute_path The absolute path of the directory to search.
1721
	 * @return array Array of absolute paths to the PHP files.
1722
	 */
1723
	public static function glob_php( $absolute_path ) {
1724
		if ( function_exists( 'glob' ) ) {
1725
			return glob( "$absolute_path/*.php" );
1726
		}
1727
1728
		$absolute_path = untrailingslashit( $absolute_path );
1729
		$files = array();
1730
		if ( ! $dir = @opendir( $absolute_path ) ) {
1731
			return $files;
1732
		}
1733
1734
		while ( false !== $file = readdir( $dir ) ) {
1735
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
1736
				continue;
1737
			}
1738
1739
			$file = "$absolute_path/$file";
1740
1741
			if ( ! is_file( $file ) ) {
1742
				continue;
1743
			}
1744
1745
			$files[] = $file;
1746
		}
1747
1748
		closedir( $dir );
1749
1750
		return $files;
1751
	}
1752
1753
	public static function activate_new_modules( $redirect = false ) {
1754
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
1755
			return;
1756
		}
1757
1758
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
1759 View Code Duplication
		if ( ! $jetpack_old_version ) {
1760
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
1761
			/** This action is documented in class.jetpack.php */
1762
			do_action( 'updating_jetpack_version', $version, false );
1763
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1764
		}
1765
1766
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
1767
1768
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
1769
			return;
1770
		}
1771
1772
		$active_modules     = Jetpack::get_active_modules();
1773
		$reactivate_modules = array();
1774
		foreach ( $active_modules as $active_module ) {
1775
			$module = Jetpack::get_module( $active_module );
1776
			if ( ! isset( $module['changed'] ) ) {
1777
				continue;
1778
			}
1779
1780
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
1781
				continue;
1782
			}
1783
1784
			$reactivate_modules[] = $active_module;
1785
			Jetpack::deactivate_module( $active_module );
1786
		}
1787
1788
		$new_version = JETPACK__VERSION . ':' . time();
1789
		/** This action is documented in class.jetpack.php */
1790
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
1791
		Jetpack_Options::update_options(
1792
			array(
1793
				'version'     => $new_version,
1794
				'old_version' => $jetpack_old_version,
1795
			)
1796
		);
1797
1798
		Jetpack::state( 'message', 'modules_activated' );
1799
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
1800
1801
		if ( $redirect ) {
1802
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
1803
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
1804
				$page = $_GET['page'];
1805
			}
1806
1807
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
1808
			exit;
1809
		}
1810
	}
1811
1812
	/**
1813
	 * List available Jetpack modules. Simply lists .php files in /modules/.
1814
	 * Make sure to tuck away module "library" files in a sub-directory.
1815
	 */
1816
	public static function get_available_modules( $min_version = false, $max_version = false ) {
1817
		static $modules = null;
1818
1819
		if ( ! isset( $modules ) ) {
1820
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
1821
			// Use the cache if we're on the front-end and it's available...
1822
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
1823
				$modules = $available_modules_option[ JETPACK__VERSION ];
1824
			} else {
1825
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
1826
1827
				$modules = array();
1828
1829
				foreach ( $files as $file ) {
1830
					if ( ! $headers = Jetpack::get_module( $file ) ) {
1831
						continue;
1832
					}
1833
1834
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
1835
				}
1836
1837
				Jetpack_Options::update_option( 'available_modules', array(
1838
					JETPACK__VERSION => $modules,
1839
				) );
1840
			}
1841
		}
1842
1843
		/**
1844
		 * Filters the array of modules available to be activated.
1845
		 *
1846
		 * @since 2.4.0
1847
		 *
1848
		 * @param array $modules Array of available modules.
1849
		 * @param string $min_version Minimum version number required to use modules.
1850
		 * @param string $max_version Maximum version number required to use modules.
1851
		 */
1852
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
1853
1854
		if ( ! $min_version && ! $max_version ) {
1855
			return array_keys( $mods );
1856
		}
1857
1858
		$r = array();
1859
		foreach ( $mods as $slug => $introduced ) {
1860
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
1861
				continue;
1862
			}
1863
1864
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
1865
				continue;
1866
			}
1867
1868
			$r[] = $slug;
1869
		}
1870
1871
		return $r;
1872
	}
1873
1874
	/**
1875
	 * Default modules loaded on activation.
1876
	 */
1877
	public static function get_default_modules( $min_version = false, $max_version = false ) {
1878
		$return = array();
1879
1880
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
1881
			$module_data = Jetpack::get_module( $module );
1882
1883
			switch ( strtolower( $module_data['auto_activate'] ) ) {
1884
				case 'yes' :
1885
					$return[] = $module;
1886
					break;
1887
				case 'public' :
1888
					if ( Jetpack_Options::get_option( 'public' ) ) {
1889
						$return[] = $module;
1890
					}
1891
					break;
1892
				case 'no' :
1893
				default :
1894
					break;
1895
			}
1896
		}
1897
		/**
1898
		 * Filters the array of default modules.
1899
		 *
1900
		 * @since 2.5.0
1901
		 *
1902
		 * @param array $return Array of default modules.
1903
		 * @param string $min_version Minimum version number required to use modules.
1904
		 * @param string $max_version Maximum version number required to use modules.
1905
		 */
1906
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
1907
	}
1908
1909
	/**
1910
	 * Checks activated modules during auto-activation to determine
1911
	 * if any of those modules are being deprecated.  If so, close
1912
	 * them out, and add any replacement modules.
1913
	 *
1914
	 * Runs at priority 99 by default.
1915
	 *
1916
	 * This is run late, so that it can still activate a module if
1917
	 * the new module is a replacement for another that the user
1918
	 * currently has active, even if something at the normal priority
1919
	 * would kibosh everything.
1920
	 *
1921
	 * @since 2.6
1922
	 * @uses jetpack_get_default_modules filter
1923
	 * @param array $modules
1924
	 * @return array
1925
	 */
1926
	function handle_deprecated_modules( $modules ) {
1927
		$deprecated_modules = array(
1928
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
1929
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
1930
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
1931
		);
1932
1933
		// Don't activate SSO if they never completed activating WPCC.
1934
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
1935
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
1936
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
1937
				$deprecated_modules['wpcc'] = null;
1938
			}
1939
		}
1940
1941
		foreach ( $deprecated_modules as $module => $replacement ) {
1942
			if ( Jetpack::is_module_active( $module ) ) {
1943
				self::deactivate_module( $module );
1944
				if ( $replacement ) {
1945
					$modules[] = $replacement;
1946
				}
1947
			}
1948
		}
1949
1950
		return array_unique( $modules );
1951
	}
1952
1953
	/**
1954
	 * Checks activated plugins during auto-activation to determine
1955
	 * if any of those plugins are in the list with a corresponding module
1956
	 * that is not compatible with the plugin. The module will not be allowed
1957
	 * to auto-activate.
1958
	 *
1959
	 * @since 2.6
1960
	 * @uses jetpack_get_default_modules filter
1961
	 * @param array $modules
1962
	 * @return array
1963
	 */
1964
	function filter_default_modules( $modules ) {
1965
1966
		$active_plugins = self::get_active_plugins();
1967
1968
		if ( ! empty( $active_plugins ) ) {
1969
1970
			// For each module we'd like to auto-activate...
1971
			foreach ( $modules as $key => $module ) {
1972
				// If there are potential conflicts for it...
1973
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
1974
					// For each potential conflict...
1975
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
1976
						// If that conflicting plugin is active...
1977
						if ( in_array( $plugin, $active_plugins ) ) {
1978
							// Remove that item from being auto-activated.
1979
							unset( $modules[ $key ] );
1980
						}
1981
					}
1982
				}
1983
			}
1984
		}
1985
1986
		return $modules;
1987
	}
1988
1989
	/**
1990
	 * Extract a module's slug from its full path.
1991
	 */
1992
	public static function get_module_slug( $file ) {
1993
		return str_replace( '.php', '', basename( $file ) );
1994
	}
1995
1996
	/**
1997
	 * Generate a module's path from its slug.
1998
	 */
1999
	public static function get_module_path( $slug ) {
2000
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2001
	}
2002
2003
	/**
2004
	 * Load module data from module file. Headers differ from WordPress
2005
	 * plugin headers to avoid them being identified as standalone
2006
	 * plugins on the WordPress plugins page.
2007
	 */
2008
	public static function get_module( $module ) {
2009
		$headers = array(
2010
			'name'                      => 'Module Name',
2011
			'description'               => 'Module Description',
2012
			'jumpstart_desc'            => 'Jumpstart Description',
2013
			'sort'                      => 'Sort Order',
2014
			'recommendation_order'      => 'Recommendation Order',
2015
			'introduced'                => 'First Introduced',
2016
			'changed'                   => 'Major Changes In',
2017
			'deactivate'                => 'Deactivate',
2018
			'free'                      => 'Free',
2019
			'requires_connection'       => 'Requires Connection',
2020
			'auto_activate'             => 'Auto Activate',
2021
			'module_tags'               => 'Module Tags',
2022
			'feature'                   => 'Feature',
2023
			'additional_search_queries' => 'Additional Search Queries',
2024
		);
2025
2026
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2027
2028
		$mod = Jetpack::get_file_data( $file, $headers );
2029
		if ( empty( $mod['name'] ) ) {
2030
			return false;
2031
		}
2032
2033
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2034
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2035
		$mod['deactivate']              = empty( $mod['deactivate'] );
2036
		$mod['free']                    = empty( $mod['free'] );
2037
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2038
2039
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2040
			$mod['auto_activate'] = 'No';
2041
		} else {
2042
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2043
		}
2044
2045
		if ( $mod['module_tags'] ) {
2046
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2047
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2048
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2049
		} else {
2050
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2051
		}
2052
2053
		if ( $mod['feature'] ) {
2054
			$mod['feature'] = explode( ',', $mod['feature'] );
2055
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2056
		} else {
2057
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2058
		}
2059
2060
		/**
2061
		 * Filters the feature array on a module.
2062
		 *
2063
		 * This filter allows you to control where each module is filtered: Recommended,
2064
		 * Jumpstart, and the default "Other" listing.
2065
		 *
2066
		 * @since 3.5.0
2067
		 *
2068
		 * @param array   $mod['feature'] The areas to feature this module:
2069
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2070
		 *     'Recommended' shows on the main Jetpack admin screen.
2071
		 *     'Other' should be the default if no other value is in the array.
2072
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2073
		 * @param array   $mod All the currently assembled module data.
2074
		 */
2075
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2076
2077
		/**
2078
		 * Filter the returned data about a module.
2079
		 *
2080
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2081
		 * so please be careful.
2082
		 *
2083
		 * @since 3.6.0
2084
		 *
2085
		 * @param array   $mod    The details of the requested module.
2086
		 * @param string  $module The slug of the module, e.g. sharedaddy
2087
		 * @param string  $file   The path to the module source file.
2088
		 */
2089
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2090
	}
2091
2092
	/**
2093
	 * Like core's get_file_data implementation, but caches the result.
2094
	 */
2095
	public static function get_file_data( $file, $headers ) {
2096
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2097
		$file_name = basename( $file );
2098
		$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
2099
		$key              = md5( $file_name . serialize( $headers ) );
2100
		$refresh_cache    = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2101
2102
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2103
		if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
2104
			return $file_data_option[ JETPACK__VERSION ][ $key ];
2105
		}
2106
2107
		$data = get_file_data( $file, $headers );
2108
2109
		// Strip out any old Jetpack versions that are cluttering the option.
2110
		$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
2111
		$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
2112
		Jetpack_Options::update_option( 'file_data', $file_data_option );
2113
2114
		return $data;
2115
	}
2116
2117
	/**
2118
	 * Return translated module tag.
2119
	 *
2120
	 * @param string $tag Tag as it appears in each module heading.
2121
	 *
2122
	 * @return mixed
2123
	 */
2124
	public static function translate_module_tag( $tag ) {
2125
		return jetpack_get_module_i18n_tag( $tag );
2126
	}
2127
2128
	/**
2129
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2130
	 *
2131
	 * @since 3.9.2
2132
	 *
2133
	 * @param array $modules
2134
	 *
2135
	 * @return string|void
2136
	 */
2137
	public static function get_translated_modules( $modules ) {
2138
		foreach ( $modules as $index => $module ) {
2139
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2140
			if ( isset( $module['name'] ) ) {
2141
				$modules[ $index ]['name'] = $i18n_module['name'];
2142
			}
2143
			if ( isset( $module['description'] ) ) {
2144
				$modules[ $index ]['description'] = $i18n_module['description'];
2145
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2146
			}
2147
		}
2148
		return $modules;
2149
	}
2150
2151
	/**
2152
	 * Get a list of activated modules as an array of module slugs.
2153
	 */
2154
	public static function get_active_modules() {
2155
		$active = Jetpack_Options::get_option( 'active_modules' );
2156
		if ( ! is_array( $active ) )
2157
			$active = array();
2158
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2159
			$active[] = 'vaultpress';
2160
		} else {
2161
			$active = array_diff( $active, array( 'vaultpress' ) );
2162
		}
2163
2164
		//If protect is active on the main site of a multisite, it should be active on all sites.
2165
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2166
			$active[] = 'protect';
2167
		}
2168
2169
		return array_unique( $active );
2170
	}
2171
2172
	/**
2173
	 * Check whether or not a Jetpack module is active.
2174
	 *
2175
	 * @param string $module The slug of a Jetpack module.
2176
	 * @return bool
2177
	 *
2178
	 * @static
2179
	 */
2180
	public static function is_module_active( $module ) {
2181
		return in_array( $module, self::get_active_modules() );
2182
	}
2183
2184
	public static function is_module( $module ) {
2185
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2186
	}
2187
2188
	/**
2189
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2190
	 *
2191
	 * @param bool $catch True to start catching, False to stop.
2192
	 *
2193
	 * @static
2194
	 */
2195
	public static function catch_errors( $catch ) {
2196
		static $display_errors, $error_reporting;
2197
2198
		if ( $catch ) {
2199
			$display_errors  = @ini_set( 'display_errors', 1 );
2200
			$error_reporting = @error_reporting( E_ALL );
2201
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2202
		} else {
2203
			@ini_set( 'display_errors', $display_errors );
2204
			@error_reporting( $error_reporting );
2205
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2206
		}
2207
	}
2208
2209
	/**
2210
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2211
	 */
2212
	public static function catch_errors_on_shutdown() {
2213
		Jetpack::state( 'php_errors', ob_get_clean() );
2214
	}
2215
2216
	public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
2217
		$jetpack = Jetpack::init();
2218
2219
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2220
		$modules = array_merge( $other_modules, $modules );
2221
2222
		// Look for standalone plugins and disable if active.
2223
2224
		$to_deactivate = array();
2225
		foreach ( $modules as $module ) {
2226
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2227
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2228
			}
2229
		}
2230
2231
		$deactivated = array();
2232
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2233
			list( $probable_file, $probable_title ) = $deactivate_me;
2234
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2235
				$deactivated[] = $module;
2236
			}
2237
		}
2238
2239
		if ( $deactivated && $redirect ) {
2240
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2241
2242
			$url = add_query_arg(
2243
				array(
2244
					'action'   => 'activate_default_modules',
2245
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2246
				),
2247
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2248
			);
2249
			wp_safe_redirect( $url );
2250
			exit;
2251
		}
2252
2253
		/**
2254
		 * Fires before default modules are activated.
2255
		 *
2256
		 * @since 1.9.0
2257
		 *
2258
		 * @param string $min_version Minimum version number required to use modules.
2259
		 * @param string $max_version Maximum version number required to use modules.
2260
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2261
		 */
2262
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2263
2264
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2265
		Jetpack::restate();
2266
		Jetpack::catch_errors( true );
2267
2268
		$active = Jetpack::get_active_modules();
2269
2270
		foreach ( $modules as $module ) {
2271
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2272
				$active[] = $module;
2273
				self::update_active_modules( $active );
2274
				continue;
2275
			}
2276
2277
			if ( in_array( $module, $active ) ) {
2278
				$module_info = Jetpack::get_module( $module );
2279
				if ( ! $module_info['deactivate'] ) {
2280
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2281 View Code Duplication
					if ( $active_state = Jetpack::state( $state ) ) {
2282
						$active_state = explode( ',', $active_state );
2283
					} else {
2284
						$active_state = array();
2285
					}
2286
					$active_state[] = $module;
2287
					Jetpack::state( $state, implode( ',', $active_state ) );
2288
				}
2289
				continue;
2290
			}
2291
2292
			$file = Jetpack::get_module_path( $module );
2293
			if ( ! file_exists( $file ) ) {
2294
				continue;
2295
			}
2296
2297
			// we'll override this later if the plugin can be included without fatal error
2298
			if ( $redirect ) {
2299
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2300
			}
2301
			Jetpack::state( 'error', 'module_activation_failed' );
2302
			Jetpack::state( 'module', $module );
2303
			ob_start();
2304
			require $file;
2305
2306
			$active[] = $module;
2307
			$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2308 View Code Duplication
			if ( $active_state = Jetpack::state( $state ) ) {
2309
				$active_state = explode( ',', $active_state );
2310
			} else {
2311
				$active_state = array();
2312
			}
2313
			$active_state[] = $module;
2314
			Jetpack::state( $state, implode( ',', $active_state ) );
2315
			Jetpack::update_active_modules( $active );
2316
2317
			ob_end_clean();
2318
		}
2319
		Jetpack::state( 'error', false );
2320
		Jetpack::state( 'module', false );
2321
		Jetpack::catch_errors( false );
2322
		/**
2323
		 * Fires when default modules are activated.
2324
		 *
2325
		 * @since 1.9.0
2326
		 *
2327
		 * @param string $min_version Minimum version number required to use modules.
2328
		 * @param string $max_version Maximum version number required to use modules.
2329
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2330
		 */
2331
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2332
	}
2333
2334
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2335
		/**
2336
		 * Fires before a module is activated.
2337
		 *
2338
		 * @since 2.6.0
2339
		 *
2340
		 * @param string $module Module slug.
2341
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2342
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2343
		 */
2344
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2345
2346
		$jetpack = Jetpack::init();
2347
2348
		if ( ! strlen( $module ) )
2349
			return false;
2350
2351
		if ( ! Jetpack::is_module( $module ) )
2352
			return false;
2353
2354
		// If it's already active, then don't do it again
2355
		$active = Jetpack::get_active_modules();
2356
		foreach ( $active as $act ) {
2357
			if ( $act == $module )
2358
				return true;
2359
		}
2360
2361
		$module_data = Jetpack::get_module( $module );
2362
2363
		if ( ! Jetpack::is_active() ) {
2364
			if ( !Jetpack::is_development_mode() )
2365
				return false;
2366
2367
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2368
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2369
				return false;
2370
		}
2371
2372
		// Check and see if the old plugin is active
2373
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2374
			// Deactivate the old plugin
2375
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2376
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2377
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2378
				Jetpack::state( 'deactivated_plugins', $module );
2379
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2380
				exit;
2381
			}
2382
		}
2383
2384
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2385
		Jetpack::state( 'module', $module );
2386
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2387
2388
		Jetpack::catch_errors( true );
2389
		ob_start();
2390
		require Jetpack::get_module_path( $module );
2391
		/** This action is documented in class.jetpack.php */
2392
		do_action( 'jetpack_activate_module', $module );
2393
		$active[] = $module;
2394
		Jetpack::update_active_modules( $active );
2395
2396
		Jetpack::state( 'error', false ); // the override
2397
		ob_end_clean();
2398
		Jetpack::catch_errors( false );
2399
2400
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2401 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2402
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2403
2404
			//Jump start is being dismissed send data to MC Stats
2405
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2406
2407
			$jetpack->do_stats( 'server_side' );
2408
		}
2409
2410
		if ( $redirect ) {
2411
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2412
		}
2413
		if ( $exit ) {
2414
			exit;
2415
		}
2416
		return true;
2417
	}
2418
2419
	function activate_module_actions( $module ) {
2420
		_deprecated_function( __METHOD__, 'jeptack-4.2' );
2421
	}
2422
2423
	public static function deactivate_module( $module ) {
2424
		/**
2425
		 * Fires when a module is deactivated.
2426
		 *
2427
		 * @since 1.9.0
2428
		 *
2429
		 * @param string $module Module slug.
2430
		 */
2431
		do_action( 'jetpack_pre_deactivate_module', $module );
2432
2433
		$jetpack = Jetpack::init();
2434
2435
		$active = Jetpack::get_active_modules();
2436
		$new    = array_filter( array_diff( $active, (array) $module ) );
2437
2438
		// A flag for Jump Start so it's not shown again.
2439 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2440
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2441
2442
			//Jump start is being dismissed send data to MC Stats
2443
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
2444
2445
			$jetpack->do_stats( 'server_side' );
2446
		}
2447
2448
		return self::update_active_modules( $new );
2449
	}
2450
2451
	public static function enable_module_configurable( $module ) {
2452
		$module = Jetpack::get_module_slug( $module );
2453
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2454
	}
2455
2456
	public static function module_configuration_url( $module ) {
2457
		$module = Jetpack::get_module_slug( $module );
2458
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
2459
	}
2460
2461
	public static function module_configuration_load( $module, $method ) {
2462
		$module = Jetpack::get_module_slug( $module );
2463
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
2464
	}
2465
2466
	public static function module_configuration_head( $module, $method ) {
2467
		$module = Jetpack::get_module_slug( $module );
2468
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
2469
	}
2470
2471
	public static function module_configuration_screen( $module, $method ) {
2472
		$module = Jetpack::get_module_slug( $module );
2473
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
2474
	}
2475
2476
	public static function module_configuration_activation_screen( $module, $method ) {
2477
		$module = Jetpack::get_module_slug( $module );
2478
		add_action( 'display_activate_module_setting_' . $module, $method );
2479
	}
2480
2481
/* Installation */
2482
2483
	public static function bail_on_activation( $message, $deactivate = true ) {
2484
?>
2485
<!doctype html>
2486
<html>
2487
<head>
2488
<meta charset="<?php bloginfo( 'charset' ); ?>">
2489
<style>
2490
* {
2491
	text-align: center;
2492
	margin: 0;
2493
	padding: 0;
2494
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2495
}
2496
p {
2497
	margin-top: 1em;
2498
	font-size: 18px;
2499
}
2500
</style>
2501
<body>
2502
<p><?php echo esc_html( $message ); ?></p>
2503
</body>
2504
</html>
2505
<?php
2506
		if ( $deactivate ) {
2507
			$plugins = get_option( 'active_plugins' );
2508
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2509
			$update  = false;
2510
			foreach ( $plugins as $i => $plugin ) {
2511
				if ( $plugin === $jetpack ) {
2512
					$plugins[$i] = false;
2513
					$update = true;
2514
				}
2515
			}
2516
2517
			if ( $update ) {
2518
				update_option( 'active_plugins', array_filter( $plugins ) );
2519
			}
2520
		}
2521
		exit;
2522
	}
2523
2524
	/**
2525
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2526
	 * @static
2527
	 */
2528
	public static function plugin_activation( $network_wide ) {
2529
		Jetpack_Options::update_option( 'activated', 1 );
2530
2531
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2532
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2533
		}
2534
2535
		if ( $network_wide )
2536
			Jetpack::state( 'network_nag', true );
2537
2538
		Jetpack::plugin_initialize();
2539
	}
2540
	/**
2541
	 * Runs before bumping version numbers up to a new version
2542
	 * @param  (string) $version    Version:timestamp
2543
	 * @param  (string) $old_version Old Version:timestamp or false if not set yet.
2544
	 * @return null              [description]
2545
	 */
2546
	public static function do_version_bump( $version, $old_version ) {
2547
2548
		if ( ! $old_version ) { // For new sites
2549
			// Setting up jetpack manage
2550
			Jetpack::activate_manage();
2551
		}
2552
	}
2553
2554
	/**
2555
	 * Sets the internal version number and activation state.
2556
	 * @static
2557
	 */
2558
	public static function plugin_initialize() {
2559
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
2560
			Jetpack_Options::update_option( 'activated', 2 );
2561
		}
2562
2563 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
2564
			$version = $old_version = JETPACK__VERSION . ':' . time();
2565
			/** This action is documented in class.jetpack.php */
2566
			do_action( 'updating_jetpack_version', $version, false );
2567
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2568
		}
2569
2570
		Jetpack::load_modules();
2571
2572
		Jetpack_Options::delete_option( 'do_activate' );
2573
	}
2574
2575
	/**
2576
	 * Removes all connection options
2577
	 * @static
2578
	 */
2579
	public static function plugin_deactivation( ) {
2580
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
2581
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
2582
			Jetpack_Network::init()->deactivate();
2583
		} else {
2584
			Jetpack::disconnect( false );
2585
			//Jetpack_Heartbeat::init()->deactivate();
2586
		}
2587
	}
2588
2589
	/**
2590
	 * Disconnects from the Jetpack servers.
2591
	 * Forgets all connection details and tells the Jetpack servers to do the same.
2592
	 * @static
2593
	 */
2594
	public static function disconnect( $update_activated_state = true ) {
2595
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
2596
		Jetpack::clean_nonces( true );
2597
2598
		// If the site is in an IDC because sync is not allowed,
2599
		// let's make sure to not disconnect the production site.
2600
		if ( ! self::validate_sync_error_idc_option() ) {
2601
			Jetpack::load_xml_rpc_client();
2602
			$xml = new Jetpack_IXR_Client();
2603
			$xml->query( 'jetpack.deregister' );
2604
		}
2605
2606
		Jetpack_Options::delete_option(
2607
			array(
2608
				'register',
2609
				'blog_token',
2610
				'user_token',
2611
				'user_tokens',
2612
				'master_user',
2613
				'time_diff',
2614
				'fallback_no_verify_ssl_certs',
2615
			)
2616
		);
2617
2618
		Jetpack_IDC::clear_all_idc_options();
2619
2620
		if ( $update_activated_state ) {
2621
			Jetpack_Options::update_option( 'activated', 4 );
2622
		}
2623
2624
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
2625
			// Check then record unique disconnection if site has never been disconnected previously
2626
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
2627
				$jetpack_unique_connection['disconnected'] = 1;
2628
			} else {
2629
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
2630
					//track unique disconnect
2631
					$jetpack = Jetpack::init();
2632
2633
					$jetpack->stat( 'connections', 'unique-disconnect' );
2634
					$jetpack->do_stats( 'server_side' );
2635
				}
2636
				// increment number of times disconnected
2637
				$jetpack_unique_connection['disconnected'] += 1;
2638
			}
2639
2640
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
2641
		}
2642
2643
		// Delete all the sync related data. Since it could be taking up space.
2644
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
2645
		Jetpack_Sync_Sender::get_instance()->uninstall();
2646
2647
		// Disable the Heartbeat cron
2648
		Jetpack_Heartbeat::init()->deactivate();
2649
	}
2650
2651
	/**
2652
	 * Unlinks the current user from the linked WordPress.com user
2653
	 */
2654
	public static function unlink_user( $user_id = null ) {
2655
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
2656
			return false;
2657
2658
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
2659
2660
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
2661
			return false;
2662
2663
		if ( ! isset( $tokens[ $user_id ] ) )
2664
			return false;
2665
2666
		Jetpack::load_xml_rpc_client();
2667
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
2668
		$xml->query( 'jetpack.unlink_user', $user_id );
2669
2670
		unset( $tokens[ $user_id ] );
2671
2672
		Jetpack_Options::update_option( 'user_tokens', $tokens );
2673
2674
		/**
2675
		 * Fires after the current user has been unlinked from WordPress.com.
2676
		 *
2677
		 * @since 4.1.0
2678
		 *
2679
		 * @param int $user_id The current user's ID.
2680
		 */
2681
		do_action( 'jetpack_unlinked_user', $user_id );
2682
2683
		return true;
2684
	}
2685
2686
	/**
2687
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
2688
	 */
2689
	public static function try_registration() {
2690
		// Let's get some testing in beta versions and such.
2691
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
2692
			// Before attempting to connect, let's make sure that the domains are viable.
2693
			$domains_to_check = array_unique( array(
2694
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
2695
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
2696
			) );
2697
			foreach ( $domains_to_check as $domain ) {
2698
				$result = Jetpack_Data::is_usable_domain( $domain );
2699
				if ( is_wp_error( $result ) ) {
2700
					return $result;
2701
				}
2702
			}
2703
		}
2704
2705
		$result = Jetpack::register();
2706
2707
		// If there was an error with registration and the site was not registered, record this so we can show a message.
2708
		if ( ! $result || is_wp_error( $result ) ) {
2709
			return $result;
2710
		} else {
2711
			return true;
2712
		}
2713
	}
2714
2715
	/**
2716
	 * Tracking an internal event log. Try not to put too much chaff in here.
2717
	 *
2718
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
2719
	 */
2720
	public static function log( $code, $data = null ) {
2721
		// only grab the latest 200 entries
2722
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
2723
2724
		// Append our event to the log
2725
		$log_entry = array(
2726
			'time'    => time(),
2727
			'user_id' => get_current_user_id(),
2728
			'blog_id' => Jetpack_Options::get_option( 'id' ),
2729
			'code'    => $code,
2730
		);
2731
		// Don't bother storing it unless we've got some.
2732
		if ( ! is_null( $data ) ) {
2733
			$log_entry['data'] = $data;
2734
		}
2735
		$log[] = $log_entry;
2736
2737
		// Try add_option first, to make sure it's not autoloaded.
2738
		// @todo: Add an add_option method to Jetpack_Options
2739
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
2740
			Jetpack_Options::update_option( 'log', $log );
2741
		}
2742
2743
		/**
2744
		 * Fires when Jetpack logs an internal event.
2745
		 *
2746
		 * @since 3.0.0
2747
		 *
2748
		 * @param array $log_entry {
2749
		 *	Array of details about the log entry.
2750
		 *
2751
		 *	@param string time Time of the event.
2752
		 *	@param int user_id ID of the user who trigerred the event.
2753
		 *	@param int blog_id Jetpack Blog ID.
2754
		 *	@param string code Unique name for the event.
2755
		 *	@param string data Data about the event.
2756
		 * }
2757
		 */
2758
		do_action( 'jetpack_log_entry', $log_entry );
2759
	}
2760
2761
	/**
2762
	 * Get the internal event log.
2763
	 *
2764
	 * @param $event (string) - only return the specific log events
2765
	 * @param $num   (int)    - get specific number of latest results, limited to 200
2766
	 *
2767
	 * @return array of log events || WP_Error for invalid params
2768
	 */
2769
	public static function get_log( $event = false, $num = false ) {
2770
		if ( $event && ! is_string( $event ) ) {
2771
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
2772
		}
2773
2774
		if ( $num && ! is_numeric( $num ) ) {
2775
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
2776
		}
2777
2778
		$entire_log = Jetpack_Options::get_option( 'log', array() );
2779
2780
		// If nothing set - act as it did before, otherwise let's start customizing the output
2781
		if ( ! $num && ! $event ) {
2782
			return $entire_log;
2783
		} else {
2784
			$entire_log = array_reverse( $entire_log );
2785
		}
2786
2787
		$custom_log_output = array();
2788
2789
		if ( $event ) {
2790
			foreach ( $entire_log as $log_event ) {
2791
				if ( $event == $log_event[ 'code' ] ) {
2792
					$custom_log_output[] = $log_event;
2793
				}
2794
			}
2795
		} else {
2796
			$custom_log_output = $entire_log;
2797
		}
2798
2799
		if ( $num ) {
2800
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
2801
		}
2802
2803
		return $custom_log_output;
2804
	}
2805
2806
	/**
2807
	 * Log modification of important settings.
2808
	 */
2809
	public static function log_settings_change( $option, $old_value, $value ) {
2810
		switch( $option ) {
2811
			case 'jetpack_sync_non_public_post_stati':
2812
				self::log( $option, $value );
2813
				break;
2814
		}
2815
	}
2816
2817
	/**
2818
	 * Return stat data for WPCOM sync
2819
	 */
2820
	public static function get_stat_data( $encode = true ) {
2821
		$heartbeat_data = Jetpack_Heartbeat::generate_stats_array();
2822
		$additional_data = self::get_additional_stat_data();
2823
2824
		$merged_data = array_merge( $heartbeat_data, $additional_data );
2825
2826
		if ( $encode ) {
2827
			return json_encode( $merged_data );
2828
		}
2829
2830
		return $merged_data;
2831
	}
2832
2833
	/**
2834
	 * Get additional stat data to sync to WPCOM
2835
	 */
2836
	public static function get_additional_stat_data( $prefix = '' ) {
2837
		global $wpdb;
2838
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
2839
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
2840
		$return["{$prefix}users"]          = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
2841
		$return["{$prefix}site-count"]     = 0;
2842
2843
		if ( function_exists( 'get_blog_count' ) ) {
2844
			$return["{$prefix}site-count"] = get_blog_count();
2845
		}
2846
		return $return;
2847
	}
2848
2849
	/* Admin Pages */
2850
2851
	function admin_init() {
2852
		// If the plugin is not connected, display a connect message.
2853
		if (
2854
			// the plugin was auto-activated and needs its candy
2855
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
2856
		||
2857
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
2858
			! Jetpack_Options::get_option( 'activated' )
2859
		) {
2860
			Jetpack::plugin_initialize();
2861
		}
2862
2863
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2864
			if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
2865
				Jetpack_Connection_Banner::init();
2866
			}
2867
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
2868
			// Upgrade: 1.1 -> 1.1.1
2869
			// Check and see if host can verify the Jetpack servers' SSL certificate
2870
			$args = array();
2871
			Jetpack_Client::_wp_remote_request(
2872
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
2873
				$args,
2874
				true
2875
			);
2876
		} else {
2877
			// Show the notice on the Dashboard only for now
2878
2879
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
2880
		}
2881
2882
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
2883
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
2884
		}
2885
2886
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
2887
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
2888
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
2889
2890
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
2891
			// Artificially throw errors in certain whitelisted cases during plugin activation
2892
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
2893
		}
2894
2895
		// Jetpack Manage Activation Screen from .com
2896
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
2897
2898
		// Add custom column in wp-admin/users.php to show whether user is linked.
2899
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
2900
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
2901
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
2902
	}
2903
2904
	function admin_body_class( $admin_body_class = '' ) {
2905
		$classes = explode( ' ', trim( $admin_body_class ) );
2906
2907
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
2908
2909
		$admin_body_class = implode( ' ', array_unique( $classes ) );
2910
		return " $admin_body_class ";
2911
	}
2912
2913
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
2914
		return $admin_body_class . ' jetpack-pagestyles ';
2915
	}
2916
2917
	/**
2918
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
2919
	 *
2920
	 * @return null
2921
	 */
2922
	function prepare_manage_jetpack_notice() {
2923
2924
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
2925
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
2926
	}
2927
2928
	function manage_activate_screen() {
2929
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
2930
	}
2931
	/**
2932
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
2933
	 * This function artificially throws errors for such cases (whitelisted).
2934
	 *
2935
	 * @param string $plugin The activated plugin.
2936
	 */
2937
	function throw_error_on_activate_plugin( $plugin ) {
2938
		$active_modules = Jetpack::get_active_modules();
2939
2940
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
2941
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
2942
			$throw = false;
2943
2944
			// Try and make sure it really was the stats plugin
2945
			if ( ! class_exists( 'ReflectionFunction' ) ) {
2946
				if ( 'stats.php' == basename( $plugin ) ) {
2947
					$throw = true;
2948
				}
2949
			} else {
2950
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
2951
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
2952
					$throw = true;
2953
				}
2954
			}
2955
2956
			if ( $throw ) {
2957
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
2958
			}
2959
		}
2960
	}
2961
2962
	function intercept_plugin_error_scrape_init() {
2963
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
2964
	}
2965
2966
	function intercept_plugin_error_scrape( $action, $result ) {
2967
		if ( ! $result ) {
2968
			return;
2969
		}
2970
2971
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
2972
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
2973
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
2974
			}
2975
		}
2976
	}
2977
2978
	function add_remote_request_handlers() {
2979
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
2980
	}
2981
2982
	function remote_request_handlers() {
2983
		switch ( current_filter() ) {
2984
		case 'wp_ajax_nopriv_jetpack_upload_file' :
2985
			$response = $this->upload_handler();
2986
			break;
2987
		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...
2988
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
2989
			break;
2990
		}
2991
2992
		if ( ! $response ) {
2993
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
2994
		}
2995
2996
		if ( is_wp_error( $response ) ) {
2997
			$status_code       = $response->get_error_data();
2998
			$error             = $response->get_error_code();
2999
			$error_description = $response->get_error_message();
3000
3001
			if ( ! is_int( $status_code ) ) {
3002
				$status_code = 400;
3003
			}
3004
3005
			status_header( $status_code );
3006
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3007
		}
3008
3009
		status_header( 200 );
3010
		if ( true === $response ) {
3011
			exit;
3012
		}
3013
3014
		die( json_encode( (object) $response ) );
3015
	}
3016
3017
	function upload_handler() {
3018
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3019
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3020
		}
3021
3022
		$user = wp_authenticate( '', '' );
3023
		if ( ! $user || is_wp_error( $user ) ) {
3024
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3025
		}
3026
3027
		wp_set_current_user( $user->ID );
3028
3029
		if ( ! current_user_can( 'upload_files' ) ) {
3030
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3031
		}
3032
3033
		if ( empty( $_FILES ) ) {
3034
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3035
		}
3036
3037
		foreach ( array_keys( $_FILES ) as $files_key ) {
3038
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3039
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3040
			}
3041
		}
3042
3043
		$media_keys = array_keys( $_FILES['media'] );
3044
3045
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3046
		if ( ! $token || is_wp_error( $token ) ) {
3047
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3048
		}
3049
3050
		$uploaded_files = array();
3051
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3052
		unset( $GLOBALS['post'] );
3053
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3054
			$file = array();
3055
			foreach ( $media_keys as $media_key ) {
3056
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3057
			}
3058
3059
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3060
3061
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3062
			if ( $hmac_provided !== $hmac_file ) {
3063
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3064
				continue;
3065
			}
3066
3067
			$_FILES['.jetpack.upload.'] = $file;
3068
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3069
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3070
				$post_id = 0;
3071
			}
3072
			$attachment_id = media_handle_upload(
3073
				'.jetpack.upload.',
3074
				$post_id,
3075
				array(),
3076
				array(
3077
					'action' => 'jetpack_upload_file',
3078
				)
3079
			);
3080
3081
			if ( ! $attachment_id ) {
3082
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3083
			} elseif ( is_wp_error( $attachment_id ) ) {
3084
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3085
			} else {
3086
				$attachment = get_post( $attachment_id );
3087
				$uploaded_files[$index] = (object) array(
3088
					'id'   => (string) $attachment_id,
3089
					'file' => $attachment->post_title,
3090
					'url'  => wp_get_attachment_url( $attachment_id ),
3091
					'type' => $attachment->post_mime_type,
3092
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3093
				);
3094
				// Zip files uploads are not supported unless they are done for installation purposed
3095
				// lets delete them in case something goes wrong in this whole process
3096
				if ( 'application/zip' === $attachment->post_mime_type ) {
3097
					// Schedule a cleanup for 2 hours from now in case of failed install.
3098
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3099
				}
3100
			}
3101
		}
3102
		if ( ! is_null( $global_post ) ) {
3103
			$GLOBALS['post'] = $global_post;
3104
		}
3105
3106
		return $uploaded_files;
3107
	}
3108
3109
	/**
3110
	 * Add help to the Jetpack page
3111
	 *
3112
	 * @since Jetpack (1.2.3)
3113
	 * @return false if not the Jetpack page
3114
	 */
3115
	function admin_help() {
3116
		$current_screen = get_current_screen();
3117
3118
		// Overview
3119
		$current_screen->add_help_tab(
3120
			array(
3121
				'id'		=> 'home',
3122
				'title'		=> __( 'Home', 'jetpack' ),
3123
				'content'	=>
3124
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3125
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3126
					'<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>',
3127
			)
3128
		);
3129
3130
		// Screen Content
3131
		if ( current_user_can( 'manage_options' ) ) {
3132
			$current_screen->add_help_tab(
3133
				array(
3134
					'id'		=> 'settings',
3135
					'title'		=> __( 'Settings', 'jetpack' ),
3136
					'content'	=>
3137
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3138
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3139
						'<ol>' .
3140
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3141
							'<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>' .
3142
						'</ol>' .
3143
						'<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>'
3144
				)
3145
			);
3146
		}
3147
3148
		// Help Sidebar
3149
		$current_screen->set_help_sidebar(
3150
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3151
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3152
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3153
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3154
		);
3155
	}
3156
3157
	function admin_menu_css() {
3158
		wp_enqueue_style( 'jetpack-icons' );
3159
	}
3160
3161
	function admin_menu_order() {
3162
		return true;
3163
	}
3164
3165 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3166
		$jp_menu_order = array();
3167
3168
		foreach ( $menu_order as $index => $item ) {
3169
			if ( $item != 'jetpack' ) {
3170
				$jp_menu_order[] = $item;
3171
			}
3172
3173
			if ( $index == 0 ) {
3174
				$jp_menu_order[] = 'jetpack';
3175
			}
3176
		}
3177
3178
		return $jp_menu_order;
3179
	}
3180
3181
	function admin_head() {
3182 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3183
			/** This action is documented in class.jetpack-admin-page.php */
3184
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3185
	}
3186
3187 View Code Duplication
	function admin_banner_styles() {
3188
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3189
3190
		wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
3191
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3192
		wp_style_add_data( 'jetpack', 'suffix', $min );
3193
	}
3194
3195
	function plugin_action_links( $actions ) {
3196
3197
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
3198
3199
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3200
			return array_merge(
3201
				$jetpack_home,
3202
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3203
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3204
				$actions
3205
				);
3206
			}
3207
3208
		return array_merge( $jetpack_home, $actions );
3209
	}
3210
3211
	/**
3212
	 * This is the first banner
3213
	 * It should be visible only to user that can update the option
3214
	 * Are not connected
3215
	 *
3216
	 * @return null
3217
	 */
3218
	function admin_jetpack_manage_notice() {
3219
		$screen = get_current_screen();
3220
3221
		// Don't show the connect notice on the jetpack settings page.
3222
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action )
3223
			return;
3224
3225
		// Only show it if don't have the managment option set.
3226
		// And not dismissed it already.
3227
		if ( ! $this->can_display_jetpack_manage_notice() || Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3228
			return;
3229
		}
3230
3231
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3232
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3233
		/**
3234
		 * I think it would be great to have different wordsing depending on where you are
3235
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3236
		 * etc..
3237
		 */
3238
3239
		?>
3240
		<div id="message" class="updated jp-banner">
3241
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3242
				<div class="jp-banner__description-container">
3243
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3244
					<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>
3245
					<p class="jp-banner__button-container">
3246
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3247
						<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>
3248
					</p>
3249
				</div>
3250
		</div>
3251
		<?php
3252
	}
3253
3254
	/**
3255
	 * Returns the url that the user clicks to remove the notice for the big banner
3256
	 * @return (string)
3257
	 */
3258
	function opt_out_jetpack_manage_url() {
3259
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
3260
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
3261
	}
3262
	/**
3263
	 * Returns the url that the user clicks to opt in to Jetpack Manage
3264
	 * @return (string)
3265
	 */
3266
	function opt_in_jetpack_manage_url() {
3267
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
3268
	}
3269
3270
	function opt_in_jetpack_manage_notice() {
3271
		?>
3272
		<div class="wrap">
3273
			<div id="message" class="jetpack-message is-opt-in">
3274
				<?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' ); ?>
3275
			</div>
3276
		</div>
3277
		<?php
3278
3279
	}
3280
	/**
3281
	 * Determines whether to show the notice of not true = display notice
3282
	 * @return (bool)
3283
	 */
3284
	function can_display_jetpack_manage_notice() {
3285
		// never display the notice to users that can't do anything about it anyways
3286
		if( ! current_user_can( 'jetpack_manage_modules' ) )
3287
			return false;
3288
3289
		// don't display if we are in development more
3290
		if( Jetpack::is_development_mode() ) {
3291
			return false;
3292
		}
3293
		// don't display if the site is private
3294
		if(  ! Jetpack_Options::get_option( 'public' ) )
3295
			return false;
3296
3297
		/**
3298
		 * Should the Jetpack Remote Site Management notice be displayed.
3299
		 *
3300
		 * @since 3.3.0
3301
		 *
3302
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
3303
		 */
3304
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
3305
	}
3306
3307
	/*
3308
	 * Registration flow:
3309
	 * 1 - ::admin_page_load() action=register
3310
	 * 2 - ::try_registration()
3311
	 * 3 - ::register()
3312
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3313
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3314
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3315
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3316
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3317
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3318
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3319
	 *       jetpack_id, jetpack_secret, jetpack_public
3320
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3321
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3322
	 * 5 - user logs in with WP.com account
3323
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3324
	 *		- Jetpack_Client_Server::authorize()
3325
	 *		- Jetpack_Client_Server::get_token()
3326
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3327
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3328
	 *			- which responds with access_token, token_type, scope
3329
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3330
	 *		- Jetpack::activate_default_modules()
3331
	 *     		- Deactivates deprecated plugins
3332
	 *     		- Activates all default modules
3333
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3334
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3335
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3336
	 *     Done!
3337
	 */
3338
3339
	/**
3340
	 * Handles the page load events for the Jetpack admin page
3341
	 */
3342
	function admin_page_load() {
3343
		$error = false;
3344
3345
		// Make sure we have the right body class to hook stylings for subpages off of.
3346
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3347
3348
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3349
			// Should only be used in intermediate redirects to preserve state across redirects
3350
			Jetpack::restate();
3351
		}
3352
3353
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3354
			// User clicked in the iframe to link their accounts
3355
			if ( ! Jetpack::is_user_connected() ) {
3356
				$connect_url = $this->build_connect_url( true, false, 'iframe' );
3357
				if ( isset( $_GET['notes_iframe'] ) )
3358
					$connect_url .= '&notes_iframe';
3359
				wp_redirect( $connect_url );
3360
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

Loading history...
3361
			} else {
3362
				if ( ! isset( $_GET['calypso_env'] ) ) {
3363
					Jetpack::state( 'message', 'already_authorized' );
3364
					wp_safe_redirect( Jetpack::admin_url() );
3365
				} else {
3366
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3367
					$connect_url .= '&already_authorized=true';
3368
					wp_redirect( $connect_url );
3369
				}
3370
			}
3371
		}
3372
3373
3374
		if ( isset( $_GET['action'] ) ) {
3375
			switch ( $_GET['action'] ) {
3376
			case 'authorize':
3377
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3378
					Jetpack::state( 'message', 'already_authorized' );
3379
					wp_safe_redirect( Jetpack::admin_url() );
3380
					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...
3381
				}
3382
				Jetpack::log( 'authorize' );
3383
				$client_server = new Jetpack_Client_Server;
3384
				$client_server->client_authorize();
3385
				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...
3386
			case 'register' :
3387
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3388
					$error = 'cheatin';
3389
					break;
3390
				}
3391
				check_admin_referer( 'jetpack-register' );
3392
				Jetpack::log( 'register' );
3393
				Jetpack::maybe_set_version_option();
3394
				$registered = Jetpack::try_registration();
3395
				if ( is_wp_error( $registered ) ) {
3396
					$error = $registered->get_error_code();
3397
					Jetpack::state( 'error', $error );
3398
					Jetpack::state( 'error', $registered->get_error_message() );
3399
					break;
3400
				}
3401
3402
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3403
3404
				wp_redirect( $this->build_connect_url( true, false, $from ) );
3405
				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...
3406
			case 'activate' :
3407
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3408
					$error = 'cheatin';
3409
					break;
3410
				}
3411
3412
				$module = stripslashes( $_GET['module'] );
3413
				check_admin_referer( "jetpack_activate-$module" );
3414
				Jetpack::log( 'activate', $module );
3415
				Jetpack::activate_module( $module );
3416
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3417
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3418
				exit;
3419
			case 'activate_default_modules' :
3420
				check_admin_referer( 'activate_default_modules' );
3421
				Jetpack::log( 'activate_default_modules' );
3422
				Jetpack::restate();
3423
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3424
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3425
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3426
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3427
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3428
				exit;
3429
			case 'disconnect' :
3430
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3431
					$error = 'cheatin';
3432
					break;
3433
				}
3434
3435
				check_admin_referer( 'jetpack-disconnect' );
3436
				Jetpack::log( 'disconnect' );
3437
				Jetpack::disconnect();
3438
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3439
				exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method admin_page_load() contains an exit expression.

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

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

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